当session失效,页面跳转到登陆界面的处理

本文介绍了一种通过拦截器实现的Session管理方式,包括如何设置Session的有效时间、如何使用拦截器来处理Session失效的情况以及如何在Spring MVC配置文件中配置拦截器。

每个系统页面操作过程中都有一个session,session可以存放少量的用户信息,供我们的页面操作使用。当session超时失效的时候我们就要重新往session中写入登陆的用户信息,而这个写入的操作一般写在在用户成功登陆系统的时候,所以当session失效时,我们页面中所有的操作都要监听,然后跳转到登陆的界面重新登陆。

1、设置session有效时间

在web.xml里面设置:

<!-- session失效时间 -->
    <session-config>
        <session-timeout>30</session-timeout>
    </session-config>

2、增加一个拦截器,拦截到后台的请求

package com.ht.spring.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class SystemSessionInterceptor implements HandlerInterceptor{

    @Override
    public void afterCompletion(HttpServletRequest arg0,
            HttpServletResponse arg1, Object arg2, Exception arg3)
            throws Exception {
        // TODO Auto-generated method stub
        
    }

    @Override
    public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
            Object arg2, ModelAndView arg3) throws Exception {
        // TODO Auto-generated method stub
        
    }

    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse res,
            Object arg2) throws Exception {
        HttpSession session = req.getSession(true);
        String userCode = (String) session.getAttribute("userCodeModel");
        String path = req.getSession().getServletContext().getContextPath() + "/jsps/login.jsp";
        /*if(userCode == null || "".equals(userCode)){
            res.sendRedirect(path);
            return false;
            throw new SessionTimeoutException();
        }else{
            return true;
        }*/
        /*if(req.getHeader("x-requested-with")!=null
                &&req.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest")){
            res.setHeader("sessionStatus", "timeout");
        }
        res.getWriter().print("timeout");
        return true;*/
        if(userCode == null || "".equals(userCode)){
            if(req.getHeader("x-requested-with")!=null
                    &&req.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest")){
                res.setHeader("sessionStatus", "timeout");
            }else{
                res.sendRedirect(path);
            }
            return false;
        }
        return true;
    }

}
3、在spring-mvc.xml里面加这个拦截器的拦截过滤

<!-- session失效拦截 -->
    <mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/**" /><!-- 拦截的目录-->
            <mvc:exclude-mapping path="/user/login.do" /><!-- 不需要拦截的请求-->
            <mvc:exclude-mapping path="/user/loginAgain.do" />
            <mvc:exclude-mapping path="/jsps" />
            <mvc:exclude-mapping path="/jquery-easyui-1.5.3" />
            <mvc:exclude-mapping path="/content" />
            <mvc:exclude-mapping path="/WEB-INF" /> 
            <bean class="com.ht.spring.interceptor.SystemSessionInterceptor"></bean><!-- 拦截器的加载类-->
        </mvc:interceptor>
    </mvc:interceptors>

4、增加一个异常处理的js,在每一个页面加以引用

$.ajaxSetup({
    error:function(XMLHttpRequest, textStatus, errorThrown){
        if(XMLHttpRequest.status==403){
            alert("您没有权限访问此资源或者进行操作");
            return false;
        }
    },
    complete:function(XMLHttpRequest, textStatus){
        var sessionStatus = XMLHttpRequest.getResponseHeader("sessionStatus");
        if(sessionStatus == "timeout"){
             $.messager.alert("系统提示", "登录超时,请重新登录");
             setTimeout(function(){
                 var top = getTopWinow();
                //$.messager.alert("系统提示", "登录超时,请重新登录");
                var curPath = window.document.location.href;
                var pathName = window.document.location.pathname;
                var pos = curPath.indexOf(pathName);
                var lacalhostPath = curPath.substring(0,pos);
                var prjName = pathName.substring(0,pathName.substr(1).indexOf("/")+1);
                //top.location.href="${pageContext.request.contextPath}"+"/jsps/login.jsp";
                top.location.href = lacalhostPath + prjName +"/jsps/login.jsp";
             },1000);
        }
    }
});
function getTopWinow(){
    var p =window;
    while(p != p.parent){
        p = p.parent;
    }
    return p;
}
 

 

### Spring Boot Session超时时自动重定向至登录页 为了实现当会话过期时自动跳转到特定页面的功能,在Spring Security框架下可以通过自定义`SecurityConfig`来完成这一需求。如果项目并未引入Spring Security,则需通过监听HttpSession事件的方式处理。 对于已集成Spring Security的应用程序而言,可以在安全配置类中设置未认证用户的默认目标地址: ```java @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/login", "/css/**").permitAll() //允许匿名访问登陆界面及相关资源 .anyRequest().authenticated()//其他请求都需要验证身份 .and() .formLogin() .loginPage("/login")//指定登录表单位置 .defaultSuccessUrl("/")//成功后的转向链接,默认根目录 .failureUrl("/login?error=true")//失败后返回带错误提示参数的登录页 .and() .logout() .clearAuthentication(true)//登出操作清除认证信息 .invalidateHttpSession(true)//使HTTP会话失效 .deleteCookies("JSESSIONID")//删除cookie防止浏览器缓存凭证 .logoutUrl("/perform_logout")//执行注销动作所需路径 .logoutSuccessUrl("/login?loggedout=true");//退出成功的回调url //设定session管理策略 http.sessionManagement() .invalidSessionUrl("/login?expired=true"); //会话无效(如超时)则导向此URL //启用CSRF防护机制(可选) http.csrf().disable(); } } ``` 上述代码片段展示了如何利用Spring Security特性定制化应用程序的安全行为,特别是针对未经验证或会话已经结束的情况作出响应[^1]。 如果不适用Spring Security组件而仅依靠Servlet API的话,则可以创建一个过滤器用于捕捉非法状态异常并实施相应的转发逻辑: ```java @Component @WebFilter(urlPatterns = "/*") public class CustomSessionTimeoutFilter implements Filter { private static final Logger logger = LoggerFactory.getLogger(CustomSessionTimeoutFilter.class); @Override public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpRequest = (HttpServletRequest)req; HttpServletResponse httpResponse = (HttpServletResponse)resp; HttpSession session = httpRequest.getSession(false); if(session==null || session.getAttribute("user")==null){ String contextPath=httpRequest.getContextPath(); httpResponse.sendRedirect(contextPath+"/login?timeout=true"); return ; } try{ chain.doFilter(req,resp); }catch(IllegalStateException e){ logger.error(e.getMessage(),e); throw new RuntimeException("The response has already been committed."); } } @Override public void init(FilterConfig filterConfig) throws ServletException {} @Override public void destroy() {} } ``` 这段Java代码实现了对所有进入系统的HTTP请求进行预检的工作流程;一旦发现不存在有效的用户对象于当前会话之中便立即中断正常的服务调用链路,并强制客户端重新导航回登录入口处[^2]。 另外需要注意的是,除了编程手段外还可以借助application.properties 或 application.yml 来调整服务器层面关于会话的有效期限以及存储模式等选项,从而间接影响到用户体验的一致性和安全性。例如修改Tomcat容器内建的会话持久化时间长度: ```properties server.servlet.session.timeout=30m # 设置为三十分钟 ``` 或者采用更灵活的数据结构保存在线记录以便更好地支持分布式部署场景下的共享读写能力[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

w_iceh

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值