首页 > 编程语言 > Session过期后实现自动跳转登录页面
2020
12-02

Session过期后实现自动跳转登录页面

最近研究如果用原生的Filter来判别session存在否或者过期否。来跳转到的页面实例,下载来展示代码。

因为顾虑器是每次请求能会进入的,所以可以设置了,进行拦截判断

1.配置web.xml

<filter>
  <filter-name>BackEndFilter</filter-name>
  <filter-class>com.sun.BackFilter</filter-class>
</filter>
<filter-mapping>
  <filter-name>BackFilter</filter-name>
  <url-pattern>/backend/issues/*</url-pattern>
  <url-pattern>/backend/repairmen/*</url-pattern>
  <url-pattern>/backend/payment/*</url-pattern>
</filter-mapping>

2.新建BackFilter类,实现Filter接口。

package com.xyt.backend;
 
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.xyt.common.Logging;
import com.xyt.common.RedisClient;
import com.xyt.jdbc.entity.Admin;
 
/**
 * 后台管理系统登录拦截器
 */
public class BackFilter implements Filter {
 
  @Override
  public void init(FilterConfig filterConfig) throws ServletException {
    //useless
  }
 
  @Override
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws IOException, ServletException {
    HttpSession sess = ((HttpServletRequest)request).getSession();
    String ad = sess.getAttribute("admin");
    if(ad==null ){
      ((HttpServletResponse)response).sendRedirect(((HttpServletRequest)request).getContextPath()+"//login");
    }else{
      chain.doFilter(request, response);
    }
  }
 
  @Override
  public void destroy() {
    //useless
  }
 
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持自学编程网。

编程技巧