1.过滤器创建
了解过滤器常见配置含义
<filter>
<filter-name>filter名字</filter-name>
<filter-class>对应到Java包名类名</filter-class>
</filter>
<filter-mapping>
<filter-name>filter名字</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
filter-mapping标签里面还有许多参数,可以参考学习博客
特别注意<filter-mapping>标签可以同一个过滤器写多个url-pattern
<filter-mapping>标签还可带参传入到java类中,使用<init-param><param-name><param-value>
在web.xml创建过滤器
<filter>
<filter-name>ElectronicFilter</filter-name>
<filter-class>com.chinasoft.it.attendance.filter.ElectronicFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>ElectronicFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
2.Java类创建
1>.实现Filter 接口
2>.init方法可读取web.xml中<init-param>参数值
3>.重写doFilter方法,实现自己所要的功能。
4>.如果不过滤走filterChain.doFilter(request, response)方法;
public class FilterName implements Filter {
protected String ip = "";
protected List<String> listUrl;
/**
* @see Filter#destroy()
*/
public void destroy() {
}
/**
* @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
*/
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain filterChain) throws IOException, ServletException {
String ipRemoteAddr = request.getRemoteAddr();//读取发送请求IP地址
//String reqUrl = ((HttpServletRequest) request).getRequestURI();
if (!listUrl.contains(ipRemoteAddr)) {
response.setCharacterEncoding("gb2312");
PrintWriter out = response.getWriter();
out.print("<p style='text-align:center; font-size:25'>IP限制!</p>");
} else {
filterChain.doFilter(request, response);
}
}
/**
* @see Filter#init(FilterConfig)
*/
public void init(FilterConfig filterConfig) throws ServletException {
}
}