Servlet编码过滤器的实现

1 编写过滤器类 EncodingFilter

package test;
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;
public class EncodingFilter implements Filter {
	//设置字符编码
	private String charSet;
	public void init(FilterConfig config) throws ServletException {
		this.charSet=config.getInitParameter("charset");
	}
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		//设置统一编码
		request.setCharacterEncoding(this.charSet);
	}
	public void destroy() {
	}
}

 

2 配置部署文件web.xml

	<filter>
		<filter-name>encoding</filter-name>
		<filter-class>test.EncodingFilter</filter-class>
		<init-param>
			<param-name>charset</param-name>
			<param-value>GBK</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>encoding</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

  

  

你可能感兴趣的:(Web,xml,servlet)