码迷,mamicode.com
首页 > 编程语言 > 详细

JavaWeb项目设置Session失效时长,失效后自动跳转页面

时间:2018-01-31 20:16:05      阅读:1077      评论:0      收藏:0      [点我收藏+]

标签:相对   servlet   use   java   ide   return   uri   请求   package   

1、在项目的web.xml文件中设置session失效时间,并添加过滤器

<!-- 配置session30分钟后过期 -->
<session-config>
  <session-timeout>30</session-timeout>
</session-config>


<!-- 配置过滤器,filter-class路径为所编写的过滤器类的路径 --> <filter> <filter-name>loginFilter</filter-name> <filter-class>com.sale.filter.LoginFilter</filter-class> </filter> <filter-mapping> <filter-name>loginFilter</filter-name> <url-pattern>*.action</url-pattern> </filter-mapping>

2、过滤器类

package com.sale.filter;
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;  
/**
 * 过滤器类
 * @author Saffi
 * @date 2018年1月31日
 */ public class LoginFilter implements Filter { @Override public void destroy() { } @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpReq=(HttpServletRequest)req; HttpServletResponse httpRes=(HttpServletResponse)res; HttpSession httpSession=httpReq.getSession(); String path = httpReq.getRequestURI(); //当前请求相对url String loginUrl = httpReq.getContextPath()+ "/loginout.action"; //登录界面url String initUrl = httpReq.getContextPath()+ "loginInit.action"; //初始化界面url String userName = (String)httpSession.getAttribute("currentUsername"); //在session中获取当前用户名 // 登陆页面、初始化页面均无需过滤 if(loginUrl.equals(path) || initUrl.equals(path)) { chain.doFilter(req, res); return; } if(userName==null){ httpRes.sendRedirect(loginUrl); return; }else{ chain.doFilter(req, res); return; } } @Override public void init(FilterConfig arg0) throws ServletException { } }

 

JavaWeb项目设置Session失效时长,失效后自动跳转页面

标签:相对   servlet   use   java   ide   return   uri   请求   package   

原文地址:https://www.cnblogs.com/shoose/p/8393624.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!