字符编码 Filter 常用来解决 Tomcat 等服务器里 request、response 乱码的问题。
原理: 在request 提交到 Servlet 之前对request 进行指定编码方式的编码。
Filter 代码如下:
package cn.joker.filter;
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.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
/**
* Servlet Filter implementation class CharacterEncodingFilter
*/
@WebFilter(
urlPatterns = { "/*" },
initParams = {
@WebInitParam(name = "characterEncoding", value = "utf-8", description = "字符编码"),
@WebInitParam(name = "enabled", value = "true", description = "是否启用该字符编码过滤器")
})
public class CharacterEncodingFilter implements Filter {
private String characterEncoding;
private boolean enabled;
/**
* Default constructor.
*/
public CharacterEncodingFilter() {
// TODO Auto-generated constructor stub
}
/**
* @see Filter#destroy()
*/
public void destroy() {
// TODO Auto-generated method stub
}
/**
* @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
*/
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
// TODO Auto-generated method stub
// place your code here
if(enabled || characterEncoding != null) {
request.setCharacterEncoding(characterEncoding);
response.setCharacterEncoding(characterEncoding);
}
System.out.println("do characterEncodingFilter");
// pass the request along the filter chain
chain.doFilter(request, response);
}
/**
* @see Filter#init(FilterConfig)
*/
public void init(FilterConfig fConfig) throws ServletException {
// TODO Auto-generated method stub
characterEncoding = fConfig.getInitParameter("characterEncoding"); //获取初始化参数
enabled = "true".equalsIgnoreCase(fConfig.getInitParameter("enabled").trim());
System.out.println(characterEncoding +" "+enabled);
}
}
页面编码方式必须与Filter指定的编码方式一致。
如果表单是 GET 方式提交的,还需要修改 Tomcat的 /conf/server.xml 配置文件,指定 URIEncoding(默认为ISO-8859-1);否则依然会乱码。