Filter过滤登录权限 不过滤登录页面 及死循环问题解决

来源:互联网 发布:淘宝分享有赏 编辑:程序博客网 时间:2024/06/05 07:03

最近自己写的一个项目部分功能写的差不多了结果发现程序入口还没写。。。太赶了~写到权限这块 我想了好几种办法 ,每个页面中都添加用户是否登录判断,写个Struts拦截器,或者写个Filter等,第一种加载的代码太多,而且也容易出错,第二种要在Struts配置文件 package里面个个配置。个人比较懒,果断用第三种,过滤器些好了,但是却死循环   进入登录页面获取不到session值没有权限,把你踢到登录界面,无限死循环

Firefox 检测到该服务器正在将此地址的请求循环重定向

或者干脆是路径如图


纠结了一天网上也找了很多资料,但是有干货的寥寥无几,全是抄袭修改连方法名都不改的,最后一点点调试出来了

public class checkLoginFilter extends HttpServlet implements Filter {@Overridepublic void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) throws IOException, ServletException {HttpServletRequest req = (HttpServletRequest) request;HttpServletResponse res = (HttpServletResponse) response;// 获得请求的URLString url = req.getRequestURL().toString();// 获得session中的对象HttpSession session = req.getSession();UserEntity user = (UserEntity) session.getAttribute("user");// 使用endsWith()判断url结尾的字符串if (url.endsWith("login.jsp") || user != null|| url.endsWith("number1.jsp") || url.endsWith(".css") || url.endsWith(".js") || url.endsWith(".gif")|| url.endsWith(".png") || url.endsWith(".jpg") || url.endsWith("SSM/") || url.endsWith("/user_Login") ) {chain.doFilter(request, response);} else {//不满足条件重定向PrintWriter out = res.getWriter();out.print("<script language>alert('请先登录');top.location.href='login.jsp'</script>");//res.sendRedirect(req.getContextPath() + "/login.jsp");//System.out.println(req.getContextPath() + "/login.jsp");}}@Overridepublic void init(FilterConfig Config) throws ServletException {// TODO Auto-generated method stub}}

    web.xml配置如下

<!-- 配置登录过滤器 -->    <filter><filter-name>checkLoginFilter</filter-name><filter-class>com.user.filter.checkLoginFilter</filter-class>  </filter>  <filter-mapping><filter-name>checkLoginFilter</filter-name><url-pattern>/*</url-pattern>  </filter-mapping>   <filter>

补充一点,对于业务不仅需要过滤.jsp,还要拦截Action的朋友来说,需要在web.xml中把filter配置放于struts2的核心filter之前就可以了,放在于之后只能拦截jsp.而对action无效。我推测应该是配置struts2的核心filter  将Action传入方式改变导致自己写的filter拦截不到,纯手打的,点个赞呗!




阅读全文
0 0