1、过滤器
package com.life.struts.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; public class SellerLoginFilter implements Filter { @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { // TODO Auto-generated method stub //取session HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest; HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; System.out.println("seller过滤器"+httpServletRequest.getRequestURI()); String seller = (String) httpServletRequest.getSession(true) .getAttribute("seller"); if (!isSellerExcludePages(httpServletRequest.getRequestURI())) { System.out.println("哈哈"); if (seller == null) { System.out.println("呵呵"); httpServletResponse.sendRedirect(httpServletRequest .getContextPath() + "/seller/login.jsp"); return; } } filterChain.doFilter(servletRequest, servletResponse); } private boolean isSellerExcludePages(String requestURI) { // TODO Auto-generated method stub return requestURI.indexOf("logout.") != -1 || requestURI.indexOf("login.") != -1 || requestURI.indexOf("action.") != -1 || requestURI.endsWith(".css") || requestURI.endsWith(".js") || requestURI.endsWith(".gif") || requestURI.endsWith(".jpg") || requestURI.endsWith(".png"); } @Override public void init(FilterConfig arg0) throws ServletException { // TODO Auto-generated method stub } @Override public void destroy() { // TODO Auto-generated method stub } }
注意:httpServletRequest.getRequestURI() 是 httpServletRequest.getRequestURI()。
不要在isSellerExcludePages加上|| !requestURI.contains("seller.jsp"),看上去是对包含seller.jsp进行拦截,但是如果不包含它的则都会通过了
web.xml配置
(1) 扩展匹配
<filter> <filter-name>LoginFilter</filter-name> <filter-class>com.life.struts.filter.LoginFilter</filter-class> </filter> <filter-mapping> <filter-name>LoginFilter</filter-name> <url-pattern>*.jsp</url-pattern> </filter-mapping>
(2)路径匹配:/seller/*,但是不要混搭/*.jsp
Done!