关于字符编码过滤器的问题
package com.csdn.tool;
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 java.io.IOException;
public class CharacterEncodingFilter implements Filter {
private FilterConfig config;
private String encoding = "UTF-8";
public void destroy() {
config = null;
}
@Override
public void doFilter(ServletRequest request,ServletResponse response,FilterChain chain) throws IOException, ServletException {
request.setCharacterEncoding(encoding);
chain.doFilter(request, response);
}
public void init(FilterConfig config) throws ServletException {
this.config = config;
String s = config.getInitParameter("encoding");
if (s != null) {
encoding = s;
}
}
}
@Override
public void doFilter(ServletRequest request,ServletResponse response,FilterChain chain) throws IOException, ServletException {
request.setCharacterEncoding(encoding);
chain.doFilter(request, response);
}
public void doFilter(ServletRequest arg0, ServletResponse arg1,
FilterChain arg2) throws IOException, ServletException {
//参数转换,因为我们已经它肯定是Http协议的请求。
HttpServletRequest request = (HttpServletRequest)arg0;
HttpServletResponse response = (HttpServletResponse)arg1;
//设置request和response使用的编码均为UTF-8。
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
//设置完成后,交回给服务器。
arg2.doFilter(arg0, arg1);
}
详细出处参考:http://www.jb51.net/article/21017.htm