字符集过滤

web.xml中的配置
<!-- 字符集过滤器 -->
	<filter>
		<filter-name>encodingFilter</filter-name>
		<filter-class>com.itmg.interseptor.PageEncodingFilter</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>
	</filter-mapping>

PageEncodingFilter类
package com.itmg.interseptor;

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;
import javax.servlet.http.HttpServletRequest;

public class PageEncodingFilter implements Filter {
	private FilterConfig filterConfig;
	private String encoding = null;

	public void init(FilterConfig filterConfig) throws ServletException {
		this.filterConfig = filterConfig;
	}

	@SuppressWarnings("unchecked")
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException,
			ServletException {
		try {
			if (encoding == null) {
				encoding = filterConfig.getInitParameter("encoding");
			}
		} catch (Exception iox) {
			iox.printStackTrace();
		}
		request.setCharacterEncoding(encoding);
		response.setCharacterEncoding(encoding);
		HttpServletRequest req = (HttpServletRequest) request;

		// get请求时,重新编码
		if ("GET".equals(req.getMethod())) {
			Enumeration names = request.getParameterNames();
			while (names.hasMoreElements()) {
				String name = (String) names.nextElement();
				String[] values = request.getParameterValues(name);
				for (int i = 0; i < values.length; i++) {
					values[i] = new String(values[i].getBytes("ISO-8859-1"), encoding);
				}
			}
		}
		filterChain.doFilter(request, response);
	}

	public void destroy() {
		filterConfig = null;
		encoding = null;
	}
}


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