在过滤器中判断用户登录(session过期跳转到登陆页面)

本文介绍了一种通过过滤器实现用户Session过期检测,并在过期时进行重定向的方法,确保用户在未登录的情况下无法进行敏感操作。

今天一直想重写DispatchAction的excute方法来判断用户session是否过期,但是由于项目中所有的Action从一开始都是extends DispatchAction,全盘替换总怕出什么问题,所以想换一种方式,考虑在进入具体action前先走过滤器,那么是否可以在过滤器中试一下呢?上网一搜果然可以,先将代码备份一下作将来参考用:

public class SetCharacterEncodingFilter implements Filter {

 // ----------------------------------------------------- Instance Variables

 /**
  * The default character encoding to set for requests that pass through this
  * filter.
  */
 protected String encoding = null;

 /**
  * The filter configuration object we are associated with. If this value is
  * null, this filter instance is not currently configured.
  */
 protected FilterConfig filterConfig = null;

 /**
  * Should a character encoding specified by the client be ignored?
  */
 protected boolean ignore = true;

 // --------------------------------------------------------- Public Methods

 /**
  * Take this filter out of service.
  */
 public void destroy() {

  this.encoding = null;
  this.filterConfig = null;

 }

 private final static String[] ignore_url={"/index.do"};//进入各子平台时不用坐登录check
 /**
  * Select and set (if specified) the character encoding to be used to
  * interpret request parameters for this request.
  *
  * @param request
  *            The servlet request we are processing
  * @param result
  *            The servlet response we are creating
  * @param chain
  *            The filter chain we are processing
  *
  * @exception IOException
  *                if an input/output error occurs
  * @exception ServletException
  *                if a servlet error occurs
  */
 public void doFilter(ServletRequest request, ServletResponse response,
   FilterChain chain) throws IOException, ServletException {

  System.out.println("&&&&&&&&&&&&&&&&doFilter&&&&&&&&&&&&&&");
  // Conditionally select and set the character encoding to be used
  
  boolean haveFind = true;
  if (ignore || (request.getCharacterEncoding() == null)) {
   String encoding = selectEncoding(request);
   if (encoding != null)
   {
    request.setCharacterEncoding(encoding);
    response.setCharacterEncoding(encoding);
   }
  }
  RequestDispatcher dispatcher = request.getRequestDispatcher("logout.jsp");//这里设置如果没有登陆将要转发到的页面  
    HttpServletRequest req = (HttpServletRequest) request;  
    HttpServletResponse res = (HttpServletResponse) response;  
    HttpSession session = req.getSession(true);  
   
    if (req.getRequestURI().indexOf(".jsp") >= 0 || req.getRequestURI().indexOf(".do") >= 0)  
             haveFind = false;
    //System.out.println(haveFind);
    for (int i = 0; i < ignore_url.length; i++) {  
             if (req.getRequestURI().indexOf(ignore_url[i]) >= 0) {  
                 haveFind = true;  
                 break;  
             } 
    }

    //System.out.println(req.getRequestURI()+haveFind);
   
    // 从session里取的用户名信息  
    String username = (String) session.getAttribute("Hthm_RealName");//这里获取session,为了检查session里有没有保存用户信息,没有的话回转发到登陆页面  
   
    // 判断如果没有取到用户信息,就跳转到登陆页面  
    if (!haveFind&&(username == null || "".equals(username)))  
    {  
     // 跳转到登陆页面  
     dispatcher.forward(request,response);  
     System.out.println("用户没有登陆,不允许操作");  
       
     res.setHeader("Cache-Control","no-store");     
     res.setDateHeader("Expires",0);  
     res.setHeader("Pragma","no-cache");  
    }  
    else 
    {  
     // 已经登陆,继续此次请求  
     chain.doFilter(request,response);  
//     System.out.println("用户已经登陆,允许操作");  
    }  

 

    
  // Pass control on to the next filter
  //chain.doFilter(request, response);
  
     Map map = request.getParameterMap();
     Set set = map.entrySet();
     if(map!= null)
     {
      for(Iterator it = set.iterator();it.hasNext();)
      {
       Map.Entry entry = (Entry) it.next();
       if(entry.getValue() instanceof String[])
       {
        String[] values = (String[]) entry.getValue();
       //TransHtmlTag是spring中类文件.
        for(int i = 0 ; i < values.length ; i++)
         values[i] = TransHtmlTag.TransHtmlTag(values[i]);
         entry.setValue(values);
       }

      }
     }

 }

 /**
  * Place this filter into service.
  *
  * @param filterConfig
  *            The filter configuration object
  */
 public void init(FilterConfig filterConfig) throws ServletException {

  this.filterConfig = filterConfig;
  this.encoding = filterConfig.getInitParameter("encoding");
  String value = filterConfig.getInitParameter("ignore");
  if (value == null)
   this.ignore = true;
  else if (value.equalsIgnoreCase("true"))
   this.ignore = true;
  else if (value.equalsIgnoreCase("yes"))
   this.ignore = true;
  else
   this.ignore = false;

 }

 // ------------------------------------------------------ Protected Methods

 /**
  * Select an appropriate character encoding to be used, based on the
  * characteristics of the current request and/or filter initialization
  * parameters. If no character encoding should be set, return
  * <code>null</code>.
  * <p>
  * The default implementation unconditionally returns the value configured
  * by the <strong>encoding</strong> initialization parameter for this
  * filter.
  *
  * @param request
  *            The servlet request we are processing
  */
 protected String selectEncoding(ServletRequest request) {

  return (this.encoding);

 }

}// EOC

在编写一个Web应用程序,如Spring MVC或者Struts2等框架中,当用户通过用户名和密码成功登录后,通常会将用户登录状态信息存储在一个会话(session)中。为了确保只有登录成功的用户才能访问后续的欢迎页面,你可以创建一个过滤器(Filter)来进行权限验证。 以下是简单的步骤: 1. 首先,创建一个`LoginFilter`类,继承自`Filter`或其对应的框架里的过滤器基类,例如Spring MVC的`OncePerRequestFilter`。 ```java import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import java.io.IOException; public class LoginFilter implements Filter { @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest) request; // 检查session是否存在或登录信息是否有效 if (!isValidSession(req)) { // 如果未登录session过期,设置响应码并重定向到登录页面 HttpServletResponse res = (HttpServletResponse) response; res.sendRedirect("/login"); return; // 结束filter链,不再向下传递请求 } chain.doFilter(request, response); // 让请求继续传递到下一个过滤器或目标资源 } private boolean isValidSession(HttpServletRequest request) { // 根据session中的登录信息判断用户是否已登录 String username = (String) request.getSession().getAttribute("username"); // 实际应用中需验证用户名和密码,此处简化处理 return username != null; } @Override public void init(FilterConfig filterConfig) throws ServletException { // 初始化配置 } @Override public void destroy() { // 销毁过滤器实例 } } ``` 然后,在web.xml或对应的配置文件中注册这个过滤器,通常放在`<filter-mapping>`标签下: ```xml <filter> <filter-name>LoginFilter</filter-name> <filter-class>com.example.LoginFilter</filter-class> </filter> <filter-mapping> <filter-name>LoginFilter</filter-name> <url-pattern>/welcome/*</url-pattern> <!-- 这里指定需要保护的欢迎页面路径 --> </filter-mapping> ``` 这样,如果用户尝试直接访问欢迎页面,未经登录验证的请求会被`LoginFilter`拦截并重定向到登录页
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值