思路一:比较麻烦(不推荐使用),每增加一个菜单还要改java程序,这里仅做参考
(1)
在index.ftl中设置菜单:
<li style=${hellotestdo}><a href="/ps_admin/hellotest.do" title="菜单11"><span>菜单11</span></a></li>
<li style=${hellotest2do}><a href="/ps_admin/hellotest2.do" title="菜单12"><span>菜单12</span></a></li>
<li style=${hellotest3do}><a href="/ps_admin/hellotest3.do" title="菜单21"><span>菜单21</span></a></li>
<li style=${hellotest4do}><a href="/ps_admin/hellotest4.do" title="菜单22"><span>菜单22</span></a></li>
页面中将style从后台取值。
(2)登录系统时,自动进入首页
@RequestMapping("/index.do")
public String index(ModelMap modelMap, HttpServletRequest request) {
addMenu(map);//初始化所有的菜单
String authorities = (String) map.get("AUTHORITIES");//获取角色
if(authorities.indexOf("ROLE_ADMIN")>-1) {//如果是管理员,所有的菜单都会看得见
map.put("hellotestdo", "display:block");
map.put("hellotest2do", "display:block");
map.put("hellotest3do", "display:block");
map.put("hellotest4do", "display:block");
}
else//其他用户登录限制菜单
{
controlMenu(map, authorities);
}
return "/admin/index.ftl";
}
/***
* 初始化菜单
*/
public void addMenu(ModelMap map){
map.put("hellotestdo", "display:none");//所有的菜单都要进行初始化
map.put("hellotest2do", "display:none");//所有的菜单都要进行初始化
map.put("hellotest3do", "display:none");
map.put("hellotest4do", "display:none");
}
/***
* 根据资源配置,普通用户无法看见只有admin有权限的菜单
*/
public void controlMenu(ModelMap map, String authorities){
authorities = authorities.replaceAll("\\[", "");
authorities = authorities.replaceAll("\\]", "");
List<String> roleOfResource = filterService.getRoleForResource(authorities);//获取该角色可以访问的URL
int len = roleOfResource.size();
for(int i=0;i<len;i++)
{
String menuControl = roleOfResource.get(i);
map.put(menuControl, "display:block");
}
}
/*数据表结构见前面Spring security实现登录验证+权限控制,这里获取的可以访问的url类似为/ps_admin/hellotest.do,返回结果为hellotestdo*/
public List<String> getRoleForResource(String authorities)
{
String sql = "select t1.value from ps_resource t1,ps_role t2,ps_role_resource t3 where t2.role_name=? and t2.id=t3.role_id and t3.resource_id=t1.id";
List<String> list = urlJdbcTemplate.query(sql, new Object[]{authorities}, new RowMapper<String>() {
@Override
public String mapRow(ResultSet rs, int i) throws SQLException {
String url = rs.getString("value");
String menuControl = url.replaceAll("/", "");
menuControl = menuControl.replaceAll("\\.", "");
menuControl = menuControl.replaceAll("ps_admin", "");
return menuControl;
}
});
return list;
}