1、web.xml配置
1 <filter> 2 <description>过滤是否登陆</description> 3 <filter-name>encodingFilter</filter-name> 4 <filter-class>com.stxx.manager.filter.EncodingFilter</filter-class> 5 <init-param> 6 <description>配置白名单</description> 7 <param-name>noCheck</param-name> 8 <param-value> 9 /login.jsp, 10 /register.jsp 11 </param-value> 12 </init-param> 13 <init-param> 14 <description>过滤不成功转向地址</description> 15 <param-name>redirectPath</param-name> 16 <param-value>/login.jsp</param-value> 17 </init-param> 18 </filter> 19 <filter-mapping> 20 <filter-name>encodingFilter</filter-name> 21 <url-pattern>*.jsp</url-pattern> 22 </filter-mapping>
2、创建过滤器
1 import java.io.IOException; 2 import java.util.ArrayList; 3 import java.util.List; 4 import javax.servlet.Filter; 5 import javax.servlet.FilterChain; 6 import javax.servlet.FilterConfig; 7 import javax.servlet.ServletException; 8 import javax.servlet.ServletRequest; 9 import javax.servlet.ServletResponse; 10 import javax.servlet.http.HttpServletRequest; 11 import javax.servlet.http.HttpServletResponse; 12 import org.apache.commons.lang.StringUtils; 13 import org.apache.log4j.Logger; 14 15 /** 16 * 登陆过滤 配置白名单、黑名单 17 * @author zxf 18 * 19 */ 20 public class EncodingFilter implements Filter { 21 22 Logger log = Logger.getLogger(EncodingFilter.class); 23 24 private static final String NO_CHECK = "noCheck"; 25 private static final String REDIRECT_PATH = "redirectPath"; 26 private List<String> noCheckList = new ArrayList<String>(); 27 private String redirectPath = "/login.jsp"; 28 29 public void init(FilterConfig init) throws ServletException { 30 log.info("初始化filter...."); 31 String noChecks = init.getInitParameter(NO_CHECK); 32 if(StringUtils.isNotBlank(noChecks)){ 33 if(StringUtils.indexOf(noChecks,",")!=-1){ 34 for(String no : noChecks.split(",")){ 35 noCheckList.add(StringUtils.trimToEmpty(no)); 36 } 37 }else{ 38 noCheckList.add(noChecks); 39 } 40 } 41 String path = init.getInitParameter(REDIRECT_PATH); 42 if(StringUtils.isNotBlank(path)){ 43 redirectPath = path; 44 } 45 } 46 47 private boolean check(String path) { 48 if (noCheckList == null || noCheckList.size() <= 0) 49 return false; 50 for (String s : noCheckList) { 51 if (path.indexOf(s) > -1) { 52 return true; 53 } 54 } 55 return false; 56 } 57 58 public void doFilter(ServletRequest arg0, ServletResponse arg1, 59 FilterChain arg2) throws IOException, ServletException { 60 HttpServletRequest request = (HttpServletRequest) arg0; 61 HttpServletResponse response = (HttpServletResponse) arg1; 62 log.info("被filter过滤......."); 63 String contextpath = request.getContextPath(); 64 if("/".equals(contextpath)){contextpath="";} 65 if(check(request.getRequestURI())){ 66 log.info("白名单"); 67 arg2.doFilter(request, response); 68 }else{ 69 log.info("黑名单"); 70 response.sendRedirect(response.encodeURL(contextpath+redirectPath)); 71 } 72 } 73 74 public void destroy() { 75 log.info("销毁filter...."); 76 } 77 78 }