刚才搞了一个字符集的filter,正好,把这个对用户是否在线,做个过滤器,只要用户session失效或者其他什么因素,反正掉线了,就自动转到登录页面,或者说更高级一些,你记一下跳转来之前的url地址,登录之后再跳回去~~
package com.tarena.web.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; public class UserFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { } // 判断用户合法性 private boolean process(HttpServletRequest request, HttpServletResponse response) { boolean bool = false; String uri = request.getServletPath(); String action = uri.substring(uri.lastIndexOf("/")+1,uri.lastIndexOf(".")); if(action.equals("login")||action.equals("regist")){ bool = true; } HttpSession session = request.getSession(false); if(session!=null&&session.getAttribute("user")!=null){ bool = true; } return bool; } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) servletRequest; HttpServletResponse response = (HttpServletResponse) servletResponse; if(process(request,response)){ filterChain.doFilter(servletRequest,servletResponse); }else{ response.sendRedirect("login.jsp"); } } @Override public void destroy() { } }
web.xml
<filter> <filter-name>UserFilter</filter-name> <filter-class>com.tarena.web.filter.UserFilter</filter-class> </filter> <filter> <filter-name>CharacterEncodingFilter</filter-name> <filter-class>com.tarena.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>ignore</param-name> <param-value>true</param-value> </init-param> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>UserFilter</filter-name> <url-pattern>*.jsp</url-pattern> </filter-mapping>
同上篇http://hi.baidu.com/ae6623/item/a006f07f0813c615d1dcb366,记得把web.xml中对于filter的配置提至最前...放在第一个<servlet>结点之前,有多前就放多前!