有这样一个需求,用户密码登录网站,在session中保留了用户的信息,但是用户很长时间没有再操作该界面,用户的session则被浏览器清除,而一些业务逻辑则是需要用到用户的信息,那么用户再执行操作后,则会引起业务代码报错,这时我们就需要在用户访问的时候判断一下用户的信息是否存在,如何实现这个功能,我们这里用到了过滤器这个功能,在用户访问特定界面或者特定接口的时候,先进行过滤,复合条件再执行下一步操作,具体代码如下:
package com.demo.filter; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import com.demo.entity.User; /** * 全站判断用户是否登录过滤器 * @author zhangdi * */ public class AuthFilter implements Filter{ @Override public void destroy() { } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletResponse resp = (HttpServletResponse)response; HttpServletRequest req = (HttpServletRequest)request; HttpSession session = req.getSession(); User user = (User)session.getAttribute("user"); String uri = req.getRequestURI(); //简单判断缓存中是否有用户 if(user==null){//没有用户 //判断用户是否是选择跳到登录界面 if(uri.endsWith("login.jsp")||uri.endsWith("login.do")){ chain.doFilter(request, response); }else{ resp.sendRedirect(req.getContextPath()+"/login.jsp"); } }else{//有用户 chain.doFilter(request, response); } chain.doFilter(request, response); } @Override public void init(FilterConfig filterConfig) throws ServletException { } }
注意,这个过滤器需要在web.xml中声明,不然不会被项目调用,代码如下:
<!-- 登录认证过滤器 --> <filter> <filter-name>auth</filter-name> <filter-class>com.demo.filter.AuthFilter</filter-class> </filter> <filter-mapping> <filter-name>auth</filter-name> <url-pattern>*.jsp</url-pattern> </filter-mapping> <filter-mapping> <filter-name>auth</filter-name> <url-pattern>*.do</url-pattern> </filter-mapping>
这里配置过滤的范围是所有的jsp界面以及所有以.do结尾的接口