根据Servlet的Filter自定义实现字符编码过滤器

1.在web.xml中配置
<context-param>
  	<param-name>encoding</param-name>
  	<param-value>UTF-8</param-value>
  </context-param>
  
  <filter>
  	<filter-name>encodingFilter</filter-name>
  	<filter-class>com.hj.servlet.encoding.EncodingFilter</filter-class>
  </filter>
  <filter-mapping>
  	<filter-name>encodingFilter</filter-name>
  	<url-pattern>/*</url-pattern>
  </filter-mapping>
  
2.实现自定义的Filter--HttpFilter
package com.hj.servlet;

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

public abstract class HttpFilter implements Filter{

	private FilterConfig config;
	
	@Override
	public void destroy() {

		
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse resp,
			FilterChain chain) throws IOException, ServletException {

		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) resp;
		doFilter(request, response, chain);
	}

	public abstract void doFilter(HttpServletRequest request,HttpServletResponse response,
			FilterChain chain)throws IOException, ServletException;
	
	@Override
	public void init(FilterConfig config) throws ServletException {

		this.config = config;
		init();
	}

	protected void init() {
		
	}

	public FilterConfig getConfig() {
		return config;
	}

	public void setConfig(FilterConfig config) {
		this.config = config;
	}
	
	
}  
  
3.实现字符过滤器
    package com.hj.servlet.encoding;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.hj.servlet.HttpFilter;

public class EncodingFilter extends HttpFilter{

	private String encoding;
	
	@Override
	protected void init(){
		encoding = getConfig().getServletContext().getInitParameter("encoding");
	}
	
	@Override
	public void doFilter(HttpServletRequest request,
			HttpServletResponse response, FilterChain chain)
			throws IOException, ServletException {

		request.setCharacterEncoding(encoding);
		chain.doFilter(request, response);
	}

}  

从而避免中文乱码


你可能感兴趣的:(根据Servlet的Filter自定义实现字符编码过滤器)