在Web.xml中增加个配置过滤器loginFilter:
1 <filter> 2 <filter-name>loginFilter</filter-name> 3 <filter-class>com.filter.LoginFilter</filter-class> 4 </filter> 5 <filter-mapping> 6 <filter-name>loginFilter</filter-name> 7 <url-pattern>/*</url-pattern> 8 </filter-mapping>
在处理登陆的action中,登陆成功后,往session中写入一个值,作为是否登陆的标记,这里写入用户名username:
1 HttpServletRequest request = ServletActionContext.getRequest(); 2 request.getSession().setAttribute("username", username);
然后编辑相应的过滤器类LoginFilter,过滤器检查session中username的值是否为空,为空则跳转至登陆页面:
1 package com.filter; 2 3 import java.io.IOException; 4 import javax.servlet.Filter; 5 import javax.servlet.FilterChain; 6 import javax.servlet.FilterConfig; 7 import javax.servlet.ServletException; 8 import javax.servlet.ServletRequest; 9 import javax.servlet.ServletResponse; 10 import javax.servlet.http.HttpServlet; 11 import javax.servlet.http.HttpServletRequest; 12 import javax.servlet.http.HttpServletResponse; 13 import javax.servlet.http.HttpSession; 14 15 public class LoginFilter extends HttpServlet implements Filter { 16 public void destroy() { 17 } 18 19 public void doFilter(ServletRequest sRequest, ServletResponse sResponse, 20 FilterChain filterChain) throws IOException, ServletException{ 21 22 HttpServletRequest request = (HttpServletRequest) sRequest; 23 HttpServletResponse response = (HttpServletResponse) sResponse; 24 HttpSession session = request.getSession(); 25 String url=request.getServletPath(); 26 String contextPath=request.getContextPath(); 27 if(url.equals("")) url+="/"; 28 if((url.startsWith("/")&&!url.startsWith("/login"))){//若访问后台资源 过滤到login 29 String user=(String)session.getAttribute("username"); 30 if(user==null){//转入管理员登陆页面 31 response.sendRedirect(contextPath+"/login.jsp"); 32 return; 33 } 34 } 35 filterChain.doFilter(sRequest, sResponse); 36 } 37 38 public void init(FilterConfig arg0) throws ServletException { 39 40 } 41 }
这样就可以了,除了login页面外全部都会被过滤器检测。
注:
浏览器关闭后session将被销毁,用户需重新登陆。
退出操作则将session中的username值设置为null即可。