日期:2014-05-17 浏览次数:20991 次
package uri; 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 UserLoginFilter implements Filter { private String redirectURI = null;// 检查路径 public UserLoginFilter() { } public void destroy() { } public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain filterChain) throws IOException, ServletException { // 配置参数 HttpServletRequest request = (HttpServletRequest) arg0; HttpServletResponse response = (HttpServletResponse) arg1; // 创建会话 HttpSession session = request.getSession(); // 判断用户是否已经登录 if (session.getAttribute("User") == null) { // 设置拦截的路径 if (!request.getRequestURI().contains("Login") || request.getRequestURI().contains("functionMenu") || request.getRequestURI().contains("showFiles")) { // 不包含登录路径的强制跳转到登录页面 request.getRequestDispatcher(redirectURI).forward(request, response); return; } // 包含的就放行 filterChain.doFilter(request, response); return; }else{ //已登录就放行 filterChain.doFilter(request, response); return; } } public void init(FilterConfig arg0) throws ServletException { redirectURI = "Loging.jsp";// 跳转页面 } }
//调用登录方法返回一个用户 User empUser=new User(); empUser=LoginDao.Login(mallID, password); //会话跟踪用户 HttpSession userSession=request.getSession(); userSession.setAttribute("User", empUser);
<session-config> <session-timeout>15</session-timeout> </session-config> <filter> <filter-name>UserLoginFilter</filter-name> <filter-class>uri.UserLoginFilter</filter-class> </filter> <filter-mapping> <filter-name>UserLoginFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>