struts2过滤器验证登陆状态

 

实现效果为:

用户在没登陆的情况下就不能访问管理页面,访问后会跳回登陆页面


  1. web.xml里,配置一个过滤器

 

<filter>  
    <filter-name>RightFilter</filter-name>  
    <filter-class>com.***.rights.RightFilter</filter-class>  
</filter>  
<filter-mapping>  
    <filter-name>RightFilter</filter-name>  
    <url-pattern>*.jsp</url-pattern>  
</filter-mapping>  
<filter-mapping>  
    <filter-name>RightFilter</filter-name>  
    <url-pattern>*.action</url-pattern>  
</filter-mapping>
 

 

 

 

  1. 在处理登陆的action中,登陆成功后,往session中写入一个值,作为是否登陆的标记,这里写入用户名username:

 HttpServletRequest request = ServletActionContext.getRequest();

request.getSession().setAttribute("username", username);

 

 

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.HttpServlet;  
import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;  
import javax.servlet.http.HttpSession;  
  
public class RightFilter extends HttpServlet implements Filter {  
  
    public void doFilter(ServletRequest arg0, ServletResponse arg1,  
            FilterChain arg2) throws IOException, ServletException {  
        HttpServletResponse response = (HttpServletResponse) arg1;    
        HttpServletRequest request=(HttpServletRequest)arg0;  
        HttpSession session = request.getSession(true);    
        String usercode = (String) session.getAttribute("usercode");//  
        String url=request.getRequestURI();  
        if(usercode==null || usercode.equals(""))  
        {  
            //判断获取的路径不为空且不是访问登录页面或执行登录操作时跳转  
            if(url!=null && !url.equals("") && ( url.indexOf("Login")<0 && url.indexOf("login")<0 ))  
            {  
                response.sendRedirect("登录路径");  
                return ;  
            }             
        }  
            //已通过验证,用户访问继续  
            arg2.doFilter(arg0, arg1);  
            return;  
    }  
  
    public void init(FilterConfig arg0) throws ServletException {  
        // TODO Auto-generated method stub  
  
    }  
 
  1. 编辑相应的过滤器类LoginFilter,过滤器检查session中username的值是否为空,为空则跳转至登陆页面:

 

这样就可以了,除了login页面外全部都会被过滤器检测。

注:

浏览器关闭后session将被销毁,用户需重新登陆。

退出操作则将session中的username值设置为null即可。

你可能感兴趣的:(struts2,拦截器,权限控制,登录验证)