WEB.XML
<!-- 用户session的 键 sessionKEY --> <context-param> <param-name>userSessionKey</param-name> <param-value>USERSESSIONKEY</param-value> </context-param> <!-- 重定向的页面 --> <context-param> <param-name>rediretPage</param-name> <param-value>/u_member/Login.jsp</param-value> </context-param> <!-- 不须要过滤的页面 --> <context-param> <param-name>uncheckUrls</param-name> <param-value>/u_member/insert.jsp,/u_member/Login.jsp</param-value> </context-param>
Filter 过滤器代码
package go.onlineShop.filter; import java.io.IOException; import java.util.Arrays; import java.util.List; 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.annotation.WebFilter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet Filter implementation class IsLoginFilter * 推断是否登陆过滤器 */ @WebFilter("/u_member") public class IsLoginFilter implements Filter { //从xml中取值 String uncheckUrls =null; String userSessionKey=null; String rediretPage=null; /** * Default constructor. */ public IsLoginFilter() { // TODO Auto-generated constructor stub } /** * @see Filter#destroy() */ public void destroy() { // TODO Auto-generated method stub } /** * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain) */ public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { // TODO Auto-generated method stub //1.得到訪问路径 HttpServletRequest request = (HttpServletRequest)req; HttpServletResponse response = (HttpServletResponse)res; String reqUrl = request.getRequestURL().toString(); String reqURI = request.getRequestURI(); String servletPath = request.getServletPath(); // String[] uncheckUrl = uncheckUrls.split(","); List<String> urls = Arrays.asList(uncheckUrls.split(",")); //2.假设是属于不须要过滤的地址就直接 放行 方法结束 if(urls.contains(servletPath)){ chain.doFilter(request, response); return; } //3.从session中获取sessionKey相应的值。若不存在 则跳转到登陆页面 Object user = request.getSession().getAttribute(userSessionKey); if(user==null){ request.getRequestDispatcher(rediretPage).forward(request, response); return; } //4若存在 则放行; chain.doFilter(request, response); } /** * @see Filter#init(FilterConfig) */ public void init(FilterConfig fConfig) throws ServletException { rediretPage=fConfig.getServletContext().getInitParameter("rediretPage"); uncheckUrls=fConfig.getServletContext().getInitParameter("uncheckUrls"); userSessionKey=fConfig.getServletContext().getInitParameter("userSessionKey"); } }
Login页面