前言
- 上一篇文章,小编主要介绍了Jquery的Ztree动态菜单的生成问题,这只是表面上控制住了用户的权限,相信任何AO系统都有登录页面,假如用户跳过登录页面直接访问系统的资源,岂不是很危险。下面小编继续介绍一下粗粒度的权限控制,利用Session判断用户是否登录。
需要解决的问题
- 每次请求都需要判断用户是否已经登录。
- 用户登录后Session信息不能永久在服务器上存着。
总体思路
存放session信息
- 用户登录系统后,我们根据用户id查询用户所拥有的角色,再根据角色id查询用户所拥有的权限,我们将用户信息,角色信息、权限信息存到Session中去。
过滤请求
- 添加一个全局的过滤器,拦截一些有必要的请求,每次请求都要从过滤器中拿出Session中的用户信息,判断用户是否已经登录,假如用户没有登录,我们就导航到登录页面,让用户重新登录。假如用户Session信息过期,我们也提醒用户重新登录。
存放Session信息代码
//将ElecUser对象放置到Session中
request.getSession().setAttribute("globle_user", elecUser);
//将Hashtable中存放的角色信息,放置到Session中
request.getSession().setAttribute("globle_role", ht);
//将权限的字符串(格式:aa@ab@ac@ad@ae)存放到Session中
request.getSession().setAttribute("globle_popedom", popedom);
过滤器代码
public class SystemUtils implements Filter {
List<String> list = new ArrayList<String>();
public void init(FilterConfig arg0) throws ServletException {
//这些初始化页面,没有用户Session信息,需要放行
list.add("/index.jsp");
list.add("/system/elecMenuAction_menuHome.do");
//5秒倒计时的页面
list.add("/error.jsp");
list.add("/system/elecMenuAction_logout.do");
}
public void doFilter(ServletRequest req, ServletResponse res,FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
//获取访问servlet的路径
String path=request.getServletPath();
/**添加粗颗粒权限控制*/
//没有Session需要放行的连接
if(list.contains(path)){
//放行
chain.doFilter(request, response);
return;
}
//判断Session是否存在
ElecUser elecUser = (ElecUser)request.getSession().getAttribute("globle_user");
//Session中存在数据,放行,指定对应的URL的页面
if(elecUser!=null){
//放行
chain.doFilter(request, response);
return;
}
//如果Session中不存在数据,重定向到error.jsp的页面上
response.sendRedirect(request.getContextPath()+"/error.jsp");
}
}
- -
过滤器配置
<filter>
<filter-name>SystemUtils</filter-name>
<filter-class>com.dmsd.utils.SystemUtils</filter-class>
</filter>
<filter-mapping>
<filter-name>SystemUtils</filter-name>
<url-pattern>*.do</url-pattern>
<url-pattern>*.jsp</url-pattern>
</filter-mapping>
- 注意,小编用的有Struts2,一定将次过滤器的配置放到Struts核心过滤器的前面。
控制Session在服务器上的时间
在web.xml中添加配置,存在时间为10分钟。
<session-config>
<session-timeout>10</session-timeout>
</session-config>
小结
- 以上还是粗粒度的权限控制,假如某用猜出来了某个功能的地址,然后改用户在浏览器中直接访问,用户依然可以非法操控某些没有权限的页面,那么我们怎么防止用户这种行为操作那,怎样细粒度的操控权限哪?请看小编的下一篇博文。