JavaWeb項目設置Session失效時長,失效後自動跳轉頁面

一、在項目的web.xml文件中設置session失效時間,並添加過濾器java

<!-- 配置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>

二、過濾器類web

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 { } }
相關文章
相關標籤/搜索