LayUI+Shiro 는 동적 메뉴 를 구현 하고 메뉴 쇼 의 예 시 를 기억 합 니 다.
Maven 의존
<dependencies>
<!-- FastJson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.39</version>
</dependency>
<!-- -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring-boot-starter</artifactId>
<version>1.4.0-RC2</version>
</dependency>
<!-- thymeleaf shiro -->
<dependency>
<groupId>com.github.theborakompanioni</groupId>
<artifactId>thymeleaf-extras-shiro</artifactId>
<version>2.0.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.4</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
메뉴1.메 인 메뉴
/**
* @author wxhntmy
*/
@Getter
@Setter
public class Menu {
private String name;
private String icon;
private String url;
private Boolean hidden;
private List<MenuList> list;
}
2.하위 메뉴
/**
* @author wxhntmy
*/
@Getter
@Setter
public class MenuList {
private String name;
private String url;
public MenuList(String name, String url) {
this.name = name;
this.url = url;
}
}
3.Shiro 설정1、ShiroConfig
/**
* @author wxhntmy
*/
@Configuration
public class ShiroConfig {
/**
*
* <p>
* URL , 1). anon : , 2). authc : 3). logout: 4).
* roles :
* <p>
* URL 1). ?: , /admin? /admin1, /admin /admin/; 2).
* *: , /admin* /admin /admin123, /admin/1; 2).
* **: , /admin/** /admin/a /admin/a/b
* <p>
* ,
*/
@Bean
public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager) {
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
shiroFilterFactoryBean.setSecurityManager(securityManager);
Map<String, String> filterChainDefinitionMap = new LinkedHashMap<String, String>();
//
filterChainDefinitionMap.put("/layui/**", "anon");
filterChainDefinitionMap.put("/js/**", "anon");
filterChainDefinitionMap.put("/admin/**", "anon");
filterChainDefinitionMap.put("/**/*.eot", "anon");
filterChainDefinitionMap.put("/**/*.svg", "anon");
filterChainDefinitionMap.put("/**/*.svgz", "anon");
filterChainDefinitionMap.put("/**/*.ttf", "anon");
filterChainDefinitionMap.put("/**/*.woff", "anon");
filterChainDefinitionMap.put("/**/*.woff2", "anon");
filterChainDefinitionMap.put("/**/*.gif", "anon");
filterChainDefinitionMap.put("/favicon.ico", "anon");
filterChainDefinitionMap.put("/login", "anon");
filterChainDefinitionMap.put("/menu", "anon");
filterChainDefinitionMap.put("/user/login", "anon");
//
filterChainDefinitionMap.put("/logout", "logout");
// , ,
filterChainDefinitionMap.put("/**", "authc");
shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
//
shiroFilterFactoryBean.setLoginUrl("/login");
//
//shiroFilterFactoryBean.setSuccessUrl("/index");
//
shiroFilterFactoryBean.setUnauthorizedUrl("/error");
return shiroFilterFactoryBean;
}
/**
* SecurityManager ;shiro
*
* @return
*/
@Bean
public DefaultWebSecurityManager securityManager() {
DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager(myRealm());
return defaultWebSecurityManager;
}
/**
* Realm
*
* @return
*/
@Bean
public MyRealm myRealm() {
MyRealm myRealm = new MyRealm();
myRealm.setCredentialsMatcher(myCredentialsMatcher());
return myRealm;
}
/**
*
* @return
*/
@Bean
public MyCredentialsMatcher myCredentialsMatcher() {
return new MyCredentialsMatcher();
}
/**
* Shiro
*/
@Bean
public LifecycleBeanPostProcessor lifecycleBeanPostProcessor() {
return new LifecycleBeanPostProcessor();
}
/**
* , ,Shiro 。
*/
@Bean
@DependsOn({ "lifecycleBeanPostProcessor" })
public DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator() {
DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator = new DefaultAdvisorAutoProxyCreator();
advisorAutoProxyCreator.setProxyTargetClass(true);
return advisorAutoProxyCreator;
}
/**
* Shiro
*/
@Bean
public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor() {
AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
authorizationAttributeSourceAdvisor.setSecurityManager(securityManager());
return authorizationAttributeSourceAdvisor;
}
@Bean
public ShiroDialect shiroDialect() {
return new ShiroDialect();
}
}
2.사용자 정의 shiro 비밀번호 검사
/**
* shiro
* @author wxhntmy
*/
public class MyCredentialsMatcher implements CredentialsMatcher {
@Resource
private UserMapper userMapper;
@Override
public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
UsernamePasswordToken utoken = (UsernamePasswordToken) token;
String password = new String(utoken.getPassword());
String username = utoken.getUsername();
User user = userMapper.getUserById(username);
return user.getPwd().equals(password);
}
}
3、MyRealm
/**
* @author wxhntmy
*/
public class MyRealm extends AuthorizingRealm {
@Resource
private RoleMapper roleMapper;
@Resource
private UserRoleListMapper userRoleListMapper;
//
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
User user = (User) principalCollection.getPrimaryPrincipal();
if (user == null) {
return null;
}
List<UserRoleList> roleLists = userRoleListMapper.getUserRoleByUserId(user.getId());
List<Role> roles = roleMapper.getAllRoles();
if (roleLists != null && !roleLists.isEmpty()) {
for (UserRoleList roleList : roleLists) {
for (Role role : roles) {
if (Objects.equals(roleList.getRole_id(), role.getId())) {
authorizationInfo.addRole(role.getRole());
}
}
}
}
return authorizationInfo;
}
//
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
//
UsernamePasswordToken utoken = (UsernamePasswordToken) authenticationToken;
//
String password = new String(utoken.getPassword());
String username = utoken.getUsername();
User user = new User();
user.setId(username);
user.setPwd(password);
// realm , getName()
String realmName = getName();
// ,
ByteSource salt = ByteSource.Util.bytes(password);
SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, password, salt, realmName);
return info;
}
}
4.제어 류1、LoginController
@RestController
public class LoginController {
@Resource
private RoleMapper roleMapper;
@Resource
private UserRoleListMapper userRoleListMapper;
@Resource
private UserMapper userMapper;
@RequestMapping(value = "/user/login", method = RequestMethod.GET)
public Msg<String> getUserByName(@RequestParam String user,
@RequestParam String pwd,
@RequestParam String usertype,
@RequestParam String box) {
Role role = roleMapper.getRoleByRoleName(usertype);
User uUser = userMapper.getUserById(user);
if (uUser == null){
return Msg.fail("UserUnexit");
}
//
UsernamePasswordToken token = new UsernamePasswordToken(user, pwd);
Subject subject = SecurityUtils.getSubject();
try {
subject.login(token);
} catch (AuthenticationException e) {
return Msg.fail("PasswordError");
}
// , , 30
SecurityUtils.getSubject().getSession().setTimeout(1800000);
return Msg.ok("Success");
}
}
2、PageController
@Controller
public class PageController {
@Resource
private UserMapper userMapper;
@RequestMapping(value = "/login", method = RequestMethod.GET)
public String Login(){
return "login";
}
@RequestMapping(value = "/user/index", method = RequestMethod.GET)
public String Index(Model model){
User user = (User) SecurityUtils.getSubject().getPrincipal();
User uuser = userMapper.getUserById(user.getId());
if (StringUtils.isEmpty(user)) {
return "redirect:/login";
}
model.addAttribute("user", uuser);
return "index";
}
}
3、MenuController
/**
* @author wxhntmy
*/
@RestController
public class MenuController {
@Resource
private RoleMapper roleMapper;
@Resource
private UserRoleListMapper userRoleListMapper;
//
private Map<String, Map> menu_map = new HashMap<>();
@RequestMapping(value = "/menu", method = RequestMethod.GET)
public Msg<List<Menu>> getMenu() {
User user = (User) SecurityUtils.getSubject().getPrincipal();
List<Menu> list = new ArrayList<>();
if (StringUtils.isEmpty(user)) {
return Msg.fail(list, " ! !");
}
//
Map<String, Boolean> map_store = new HashMap<>();
if (menu_map.containsKey(user.getId())){
map_store = menu_map.get(user.getId());
}
Map<String, String> map = new HashMap();
List<UserRoleList> roleLists = userRoleListMapper.getUserRoleByUserId(user.getId());
for (UserRoleList roleList : roleLists) {
Role role = roleMapper.getRoleByRoleId(roleList.getRole_id());
map.put(role.getRole(), roleList.getUser_id());
}
Menu menu1 = new Menu();
menu1.setName(" ");
menu1.setIcon("");
menu1.setUrl("/user/index");
menu1.setHidden(false);
List<MenuList> menuLists2 = new ArrayList<>();
menu1.setList(menuLists2);
list.add(menu1);
if (map.containsKey("student")){
Menu menu2 = new Menu();
Menu menu3 = new Menu();
menu2.setName(" ");
menu2.setIcon("");
menu2.setUrl("");
menu2.setHidden(map_store.getOrDefault(" ", false));
List<MenuList> menuLists = new ArrayList<>();
MenuList menuList1 = new MenuList(" ", "");
MenuList menuList2 = new MenuList(" ", "");
MenuList menuList22 = new MenuList(" ", "");
menuLists.add(menuList1);
menuLists.add(menuList2);
menuLists.add(menuList22);
menu2.setList(menuLists);
menu3.setName(" ");
menu3.setIcon("");
menu3.setUrl("");
menu3.setHidden(map_store.getOrDefault(" ", false));
List<MenuList> menuLists3 = new ArrayList<>();
MenuList menuList3 = new MenuList(" ", "");
MenuList menuList33 = new MenuList(" ", "");
MenuList menuList4 = new MenuList(" ", "");
MenuList menuList5 = new MenuList(" ", "");
menuLists3.add(menuList3);
menuLists3.add(menuList33);
menuLists3.add(menuList4);
menuLists3.add(menuList5);
menu3.setList(menuLists3);
list.add(menu2);
list.add(menu3);
}
if (map.containsKey("teacher")){
Menu menu2 = new Menu();
Menu menu3 = new Menu();
menu2.setName(" ");
menu2.setIcon("");
menu2.setUrl("");
menu2.setHidden(map_store.getOrDefault(" ", false));
List<MenuList> menuLists = new ArrayList<>();
MenuList menuList1 = new MenuList(" ", "");
MenuList menuList2 = new MenuList(" ", "");
menuLists.add(menuList1);
menuLists.add(menuList2);
menu2.setList(menuLists);
menu3.setName(" ");
menu3.setIcon("");
menu3.setUrl("");
menu3.setHidden(map_store.getOrDefault(" ", false));
List<MenuList> menuLists3 = new ArrayList<>();
MenuList menuList3 = new MenuList(" ", "");
MenuList menuList33 = new MenuList(" ", "");
MenuList menuList4 = new MenuList(" ", "");
menuLists3.add(menuList3);
menuLists3.add(menuList33);
menuLists3.add(menuList4);
menu3.setList(menuLists3);
list.add(menu2);
list.add(menu3);
}
if (map.containsKey("professionor")){
Menu menu2 = new Menu();
Menu menu3 = new Menu();
menu2.setName(" ");
menu2.setIcon("");
menu2.setUrl("");
menu2.setHidden(map_store.getOrDefault(" ", false));
List<MenuList> menuLists = new ArrayList<>();
MenuList menuList1 = new MenuList(" ", "");
MenuList menuList2 = new MenuList(" ", "");
MenuList menuList3 = new MenuList(" ", "");
menuLists.add(menuList1);
menuLists.add(menuList2);
menuLists.add(menuList3);
menu2.setList(menuLists);
menu3.setName(" ");
menu3.setIcon("");
menu3.setUrl("");
menu3.setHidden(map_store.getOrDefault(" ", false));
List<MenuList> menuLists1 = new ArrayList<>();
MenuList menuList11 = new MenuList(" ", "");
MenuList menuList21 = new MenuList(" ", "");
menuLists1.add(menuList11);
menuLists1.add(menuList21);
menu3.setList(menuLists1);
list.add(menu2);
list.add(menu3);
}
if (map.containsKey("admin")){
Menu menu2 = new Menu();
Menu menu3 = new Menu();
menu2.setName(" ");
menu2.setIcon("");
menu2.setUrl("");
menu2.setHidden(map_store.getOrDefault(" ", false));
List<MenuList> menuLists = new ArrayList<>();
MenuList menuList0 = new MenuList(" ", "");
MenuList menuList1 = new MenuList(" ", "");
MenuList menuList2 = new MenuList(" ", "");
MenuList menuList3 = new MenuList(" ", "");
menuLists.add(menuList0);
menuLists.add(menuList1);
menuLists.add(menuList2);
menuLists.add(menuList3);
menu2.setList(menuLists);
menu3.setName(" ");
menu3.setIcon("");
menu3.setUrl("");
menu3.setHidden(map_store.getOrDefault(" ", false));
List<MenuList> menuLists3 = new ArrayList<>();
MenuList menuList4 = new MenuList(" ", "");
MenuList menuList5 = new MenuList(" ", "");
menuLists3.add(menuList4);
menuLists3.add(menuList5);
menu3.setList(menuLists3);
list.add(menu2);
list.add(menu3);
}
Menu menu4 = new Menu();
menu4.setName(" ");
menu4.setIcon("");
menu4.setUrl("");
menu4.setHidden(map_store.getOrDefault(" ", false));
List<MenuList> menuLists4 = new ArrayList<>();
MenuList menuList5 = new MenuList(" ", "");
MenuList menuList6 = new MenuList(" ", "");
MenuList menuList7 = new MenuList(" ", "");
menuLists4.add(menuList5);
menuLists4.add(menuList6);
menuLists4.add(menuList7);
menu4.setList(menuLists4);
Menu menu5 = new Menu();
menu5.setName(" ");
menu5.setIcon("");
menu5.setUrl("/logout");
menu5.setHidden(false);
List<MenuList> menuLists5 = new ArrayList<>();
menu5.setList(menuLists5);
list.add(menu4);
list.add(menu5);
if (map.containsKey("student")){
return Msg.ok(list, "STU");
}
String message = null;
if (map.containsKey("teacher")){
message = "TEA";
}
if (map.containsKey("professionor")){
message = "PRI";
}
if (map.containsKey("admin")){
message = "ADM";
}
return Msg.ok(list, message);
}
@RequestMapping(value = "/menu_storage", method = RequestMethod.GET)
public Msg<String> menu_storage(@RequestParam String data) {
JSONArray jsonArray = JSONArray.parseArray(data);
User user = (User) SecurityUtils.getSubject().getPrincipal();
if (StringUtils.isEmpty(user)) {
return Msg.fail(" ! !");
}
//
Map<String, Boolean> map_store = new HashMap<>();
for (Object o : jsonArray) {
JSONObject jsonObject = JSONObject.parseObject(o.toString());
map_store.put(jsonObject.getString("name"), Boolean.valueOf(jsonObject.getString("hidden")));
}
menu_map.put(user.getId(), map_store);
return Msg.ok();
}
}
데이터베이스1.사용자 표
2.역할 표
3、user_role_리스트 리스트
6.전단 페이지
1.Ajax 요청 메뉴 데이터
let config = {};
function set_menu() {
//ajax
$.ajax({
type: "get",
async: false,
url: "/menu",// LoginServlet
dataType: 'json',
success: function (msg) {
if (msg.ok === true && msg.data) {
config["name"] = msg.message;
config["menu"] = msg.data;
}
if (msg.ok === false) {
window.location.href = "/logout";
}
if (!msg.data) {
window.location.href = "/logout";
}
},
error: function (msg) {
//
layer.alert(' !!!', function (index) {
//do something
layer.close(index);
});
}
});
}
set_menu();
$(document).ready(function () {
//
$(".del").click(function () {
var url = $(this).attr("href");
var id = $(this).attr("data-id");
layer.confirm(' ?', {
btn: [' ', ' ']
}, function () {
$.get(url, function (data) {
if (data.code === 1) {
$(id).fadeOut();
layer.msg(data.msg, {icon: 1});
} else {
layer.msg(data.msg, {icon: 2});
}
});
}, function () {
layer.msg(" !");
});
return false;
});
})
layui.use('form', function () {
var form = layui.form,
layer = layui.layer;
});
var vue = new Vue({
el: '#app',
data: {
webname: config.name,
menu: [],
address: []
},
created: function () {
this.menu = config.menu;
this.thisActive();
this.thisAttr();
},
methods: {
//
onActive: function (pid, id = false) {
let data;
if (id === false) {
data = this.menu[pid];
if (data.url.length > 0) {
this.menu.forEach((v, k) => {
v.active = false;
v.list.forEach((v2, k2) => {
v2.active = false;
})
})
data.active = true;
}
data.hidden = !data.hidden;
} else {
this.menu.forEach((v, k) => {
v.active = false;
v.list.forEach((v2, k2) => {
v2.active = false;
})
})
data = this.menu[pid].list[id];
}
this.updateStorage();
if (data.url.length > 0) {
if (data.target) {
if (data.target === '_blank') {
window.open(data.url);
} else {
window.location.href = data.url;
}
} else {
window.location.href = data.url;
}
}
},
//
updateStorage() {
//sessionStorage.menu = JSON.stringify(this.menu);
$.ajax({
type: "get",
async: false,
url: "/menu_storage",// LoginServlet
data: {
"data": JSON.stringify(this.menu)
},
dataType: 'json',
success: function (msg) {
},
error: function (msg) {
//
var index = layer.load();
layer.close(index);
layer.alert(' !!!', function (index) {
//do something
layer.close(index);
});
}
});
},
//
thisActive: function () {
let pathname = window.location.pathname;
let host = window.location.host;
let pid = false;
let id = false;
this.menu.forEach((v, k) => {
let url = v.url;
if (url.length > 0) {
if (url[0] !== '/' && url.substr(0, 4) !== 'http') {
url = '/' + url;
}
}
if (pathname === url) {
pid = k;
}
v.list.forEach((v2, k2) => {
let url = v2.url;
if (url.length > 0) {
if (url[0] !== '/' && url.substr(0, 4) !== 'http') {
url = '/' + url;
}
}
if (pathname === url) {
pid = k;
id = k2;
}
})
})
if (id !== false) {
this.menu[pid].list[id].active = true;
} else {
if (pid !== false) {
this.menu[pid].active = true;
}
}
this.updateStorage();
},
//
thisAttr: function () {
//
let address = [{
name: ' ',
url: '/user/index'
}];
this.menu.forEach((v, k) => {
v.list.forEach((v2, k2) => {
if (v2.active) {
address.push({
name: v.name,
url: 'javascript:;'
})
address.push({
name: v2.name,
url: v2.url,
})
this.address = address;
}
})
})
}
}
})
2.메뉴 표시 줄 보이 기
<ul class="cl">
<!-- -->
<li v-for="vo,index in menu" :class="{hidden:vo.hidden}">
<a href="javascript:;" rel="external nofollow" rel="external nofollow" :class="{active:vo.active}" @click="onActive(index)">
<i class="layui-icon" v-html="vo.icon"></i>
<span v-text="vo.name"></span>
<i class="layui-icon arrow" v-show="vo.url.length==0"></i> <i v-show="vo.active"
class="layui-icon active"></i>
</a>
<!-- -->
<div v-for="vo2,index2 in vo.list">
<a href="javascript:;" rel="external nofollow" rel="external nofollow" :class="{active:vo2.active}" @click="onActive(index,index2)"
v-text="vo2.name"></a>
<i v-show="vo2.active" class="layui-icon active"></i>
</div>
</li>
</ul>
7.전체 코드전체 코드 변환 Gitee:wxhntmy / SpringBootLayuiMenu
LayUI+Shiro 가 동적 메뉴 를 구현 하고 메뉴 를 기억 하 는 예제 에 관 한 이 글 은 여기까지 소개 되 었 습 니 다.LayUI Shiro 동적 메뉴 에 관 한 내용 은 이전 글 을 검색 하거나 아래 의 관련 글 을 계속 찾 아 보 세 요.앞으로 도 많은 응원 부 탁 드 리 겠 습 니 다!
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Shiro 지식 포인트 비망록더 읽 기 1. Shiro 수 동 인증 2 、 Shiro 비밀번호 없 이 로그 인 3 、 Shiro 로그 인 성공 후 지정 한 URL 로 건 너 뛰 기 인용 하 다. http://www.cnblogs.com/seve...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.