servlet过滤器配置白名单、黑名单

时间:2021-10-26 01:07:18

1、web.xml配置

 <filter>
<description>过滤是否登陆</description>
<filter-name>encodingFilter</filter-name>
<filter-class>com.stxx.manager.filter.EncodingFilter</filter-class>
<init-param>
<description>配置白名单</description>
<param-name>noCheck</param-name>
<param-value>
/login.jsp,
/register.jsp
</param-value>
</init-param>
<init-param>
<description>过滤不成功转向地址</description>
<param-name>redirectPath</param-name>
<param-value>/login.jsp</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>*.jsp</url-pattern>
</filter-mapping>

2、创建过滤器

 import java.io.IOException;
import java.util.ArrayList;
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.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger; /**
* 登陆过滤 配置白名单、黑名单
* @author zxf
*
*/
public class EncodingFilter implements Filter { Logger log = Logger.getLogger(EncodingFilter.class); private static final String NO_CHECK = "noCheck";
private static final String REDIRECT_PATH = "redirectPath";
private List<String> noCheckList = new ArrayList<String>();
private String redirectPath = "/login.jsp"; public void init(FilterConfig init) throws ServletException {
log.info("初始化filter....");
String noChecks = init.getInitParameter(NO_CHECK);
if(StringUtils.isNotBlank(noChecks)){
if(StringUtils.indexOf(noChecks,",")!=-){
for(String no : noChecks.split(",")){
noCheckList.add(StringUtils.trimToEmpty(no));
}
}else{
noCheckList.add(noChecks);
}
}
String path = init.getInitParameter(REDIRECT_PATH);
if(StringUtils.isNotBlank(path)){
redirectPath = path;
}
} private boolean check(String path) {
if (noCheckList == null || noCheckList.size() <= )
return false;
for (String s : noCheckList) {
if (path.indexOf(s) > -) {
return true;
}
}
return false;
} public void doFilter(ServletRequest arg0, ServletResponse arg1,
FilterChain arg2) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) arg0;
HttpServletResponse response = (HttpServletResponse) arg1;
log.info("被filter过滤.......");
String contextpath = request.getContextPath();
if("/".equals(contextpath)){contextpath="";}
if(check(request.getRequestURI())){
log.info("白名单");
arg2.doFilter(request, response);
}else{
log.info("黑名单");
response.sendRedirect(response.encodeURL(contextpath+redirectPath));
}
} public void destroy() {
log.info("销毁filter....");
} }