字符编码过滤器

EncodeFilter.java 

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 EncodeFilter implements Filter {
	protected String encoding = null;
	protected FilterConfig filterConfig = null;

	public void destroy() {
		System.out.println("过滤器销毁!");
		this.encoding = null;
		this.filterConfig = null;

	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		String encoding = this.encoding;
		if (encoding != null) {
			request.setCharacterEncoding(encoding);
		} else {
			request.setCharacterEncoding("UTF-8");
		}
		chain.doFilter(request, response);// 传递过滤链

	}

	public void init(FilterConfig config) throws ServletException {
		System.out.println("过滤器初始化!");
		this.filterConfig = config;
		this.encoding = filterConfig.getInitParameter("encoding");// 获取传递过来的初使化编码

	}

}
 

web.xml

 

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
	<display-name></display-name>

	<filter>
		<filter-name>encodingFilter</filter-name>
		<filter-class>com.cqcet.filter.EncodeFilter</filter-class>
		<init-param>
			<param-name>encoding</param-name>
			<param-value>UTF-8</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>encodingFilter</filter-name>
		<url-pattern>/*</url-pattern>
		<dispatcher>FORWARD</dispatcher>
		<dispatcher>REQUEST</dispatcher>
	</filter-mapping>
</web-app>
 

 

 

你可能感兴趣的:(字符编码)