public abstract interface Filter{
public abstract void init(FilterConfig paramFilterConfig) throws ServletException;
public abstract void doFilter(ServletRequest paramServletRequest, ServletResponse paramServletResponse, FilterChain
paramFilterChain) throws IOException, ServletException;
public abstract void destroy();
}
过滤器范例:
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;
/**
* @author yangcq
* @description 过滤器Filter的工作原理
*/
public class FilterTest implements Filter{
public void destroy() {
System.out.println("----Filter销毁----");
}
public void doFilter(ServletRequest request, ServletResponse response,FilterChain filterChain) throws IOException, ServletException {
// 对request、response进行一些预处理
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
System.out.println("----调用service之前执行一段代码----");
filterChain.doFilter(request, response); // 执行目标资源,放行
System.out.println("----调用service之后执行一段代码----");
}
public void init(FilterConfig arg0) throws ServletException {
System.out.println("----Filter初始化----");
}
}
index.jsp
FilterTest
com.yangcq.filter.FilterTest
FilterTest
/*
encodingFilter
org.springframework.web.filter.CharacterEncodingFilter
encoding
UTF-8
forceEncoding
true
encodingFilter
/*
package org.springframework.web.filter;
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.util.ClassUtils;
public class CharacterEncodingFilter extends OncePerRequestFilter{
private static final boolean responseSetCharacterEncodingAvailable = ClassUtils.hasMethod(
class$javax$servlet$http$HttpServletResponse, "setCharacterEncoding", new Class[] { String.class });
// 需要设置的编码方式,为了支持可配置,Spring把编码方式设置成了一个变量
private String encoding;
// 是否强制使用统一编码,也是为了支持可配置
private boolean forceEncoding;
// 构造器,在这里,Spring把forceEncoding的值默认设置成了false
public CharacterEncodingFilter(){
this.forceEncoding = false;
}
// encoding/forceEncoding的setter方法
public void setEncoding(String encoding){
this.encoding = encoding;
}
public void setForceEncoding(boolean forceEncoding){
this.forceEncoding = forceEncoding;
}
// Spring通过GenericFilterBean抽象类,对Filter接口进行了整合,
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException{
if ((this.encoding != null) && (((this.forceEncoding) || (request.getCharacterEncoding() == null)))) {
request.setCharacterEncoding(this.encoding);
if ((this.forceEncoding) && (responseSetCharacterEncodingAvailable)) {
response.setCharacterEncoding(this.encoding);
}
}
filterChain.doFilter(request, response);
}
}
import java.io.IOException;
import java.util.Enumeration;
import javax.servlet.FilterChain;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.filter.CharacterEncodingFilter;
/*
* InvalidCharacterFilter:过滤request请求中的非法字符,防止脚本攻击
* InvalidCharacterFilter继承了Spring框架的CharacterEncodingFilter过滤器,当然,我们也可以自己实现这样一个过滤器
*/
public class InvalidCharacterFilter extends CharacterEncodingFilter{
// 需要过滤的非法字符
private static String[] invalidCharacter = new String[]{
"script","select","insert","document","window","function",
"delete","update","prompt","alert","create","alter",
"drop","iframe","link","where","replace","function","onabort",
"onactivate","onafterprint","onafterupdate","onbeforeactivate",
"onbeforecopy","onbeforecut","onbeforedeactivateonfocus",
"onkeydown","onkeypress","onkeyup","onload",
"expression","applet","layer","ilayeditfocus","onbeforepaste",
"onbeforeprint","onbeforeunload","onbeforeupdate",
"onblur","onbounce","oncellchange","oncontextmenu",
"oncontrolselect","oncopy","oncut","ondataavailable",
"ondatasetchanged","ondatasetcomplete","ondeactivate",
"ondrag","ondrop","onerror","onfilterchange","onfinish","onhelp",
"onlayoutcomplete","onlosecapture","onmouse","ote",
"onpropertychange","onreadystatechange","onreset","onresize",
"onresizeend","onresizestart","onrow","onscroll",
"onselect","onstaronsubmit","onunload","IMgsrc","infarction"
};
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException{
String parameterName = null;
String parameterValue = null;
// 获取请求的参数
@SuppressWarnings("unchecked")
Enumeration allParameter = request.getParameterNames();
while(allParameter.hasMoreElements()){
parameterName = allParameter.nextElement();
parameterValue = request.getParameter(parameterName);
if(null != parameterValue){
for(String str : invalidCharacter){
if (StringUtils.containsIgnoreCase(parameterValue, str)){
request.setAttribute("errorMessage", "非法字符:" + str);
RequestDispatcher requestDispatcher = request.getRequestDispatcher("/error.jsp");
requestDispatcher.forward(request, response);
return;
}
}
}
}
super.doFilterInternal(request, response, filterChain);
}
}
InvalidCharacterFilter
com.yangcq.filter.InvalidCharacterFilter
InvalidCharacterFilter
/*
import java.io.IOException;
import java.util.Enumeration;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import org.apache.commons.lang.StringUtils;
/**
* SelfDefineInvalidCharacterFilter:过滤request请求中的非法字符,防止脚本攻击
*/
public class SelfDefineInvalidCharacterFilter implements Filter{
public void destroy() {
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
String parameterName = null;
String parameterValue = null;
// 获取请求的参数
@SuppressWarnings("unchecked")
Enumeration allParameter = request.getParameterNames();
while(allParameter.hasMoreElements()){
parameterName = allParameter.nextElement();
parameterValue = request.getParameter(parameterName);
if(null != parameterValue){
for(String str : invalidCharacter){
if (StringUtils.containsIgnoreCase(parameterValue, str)){
request.setAttribute("errorMessage", "非法字符:" + str);
RequestDispatcher requestDispatcher = request.getRequestDispatcher("/error.jsp");
requestDispatcher.forward(request, response);
return;
}
}
}
}
filterChain.doFilter(request, response); // 执行目标资源,放行
}
public void init(FilterConfig filterConfig) throws ServletException {
}
// 需要过滤的非法字符
private static String[] invalidCharacter = new String[]{
"script","select","insert","document","window","function",
"delete","update","prompt","alert","create","alter",
"drop","iframe","link","where","replace","function","onabort",
"onactivate","onafterprint","onafterupdate","onbeforeactivate",
"onbeforecopy","onbeforecut","onbeforedeactivateonfocus",
"onkeydown","onkeypress","onkeyup","onload",
"expression","applet","layer","ilayeditfocus","onbeforepaste",
"onbeforeprint","onbeforeunload","onbeforeupdate",
"onblur","onbounce","oncellchange","oncontextmenu",
"oncontrolselect","oncopy","oncut","ondataavailable",
"ondatasetchanged","ondatasetcomplete","ondeactivate",
"ondrag","ondrop","onerror","onfilterchange","onfinish","onhelp",
"onlayoutcomplete","onlosecapture","onmouse","ote",
"onpropertychange","onreadystatechange","onreset","onresize",
"onresizeend","onresizestart","onrow","onscroll",
"onselect","onstaronsubmit","onunload","IMgsrc","infarction"
};
}
SelfDefineInvalidCharacterFilter
com.yangcq.filter.SelfDefineInvalidCharacterFilter
SelfDefineInvalidCharacterFilter
/*
package com.yangcq.filter;
import java.io.IOException;
import java.util.Enumeration;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
public class FilterTest implements Filter {
/* 过滤器初始化
* @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
*/
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("----过滤器初始化----");
/**
*
FilterTest
com.yangcq.filter.FilterTest
FilterTest
name
gacl
配置FilterTest过滤器的初始化参数
like
java
FilterDemo02
/*
*/
//得到过滤器的名字
String filterName = filterConfig.getFilterName();
//得到在web.xml文件中配置的初始化参数
String initParam1 = filterConfig.getInitParameter("name");
String initParam2 = filterConfig.getInitParameter("like");
//返回过滤器的所有初始化参数的名字的枚举集合。
Enumeration initParameterNames = filterConfig.getInitParameterNames();
System.out.println(filterName);
System.out.println(initParam1);
System.out.println(initParam2);
while (initParameterNames.hasMoreElements()) {
String paramName = (String) initParameterNames.nextElement();
System.out.println(paramName);
}
}
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
System.out.println("FilterDemo02执行前!!!");
chain.doFilter(request, response); //让目标资源执行,放行
System.out.println("FilterDemo02执行后!!!");
}
@Override
public void destroy() {
System.out.println("----过滤器销毁----");
}
}
过滤器名称
自定义的名字
com.yangcq.filter.FilterTest
配置过滤器的初始化参数
name
gacl
配置FilterTest过滤器的初始化参数
like
java