java的web程序经常出现中文乱码的问题,用一个实现了Filter接口的过滤器类可以较好地解决这个问题。
方式一 EncodingFilter
import java.io.IOException;
import javax.servlet.*;
public class EncodingFilter implements Filter {
private FilterConfig filterConfig = null;
private String encoding = null;
@Override
public void destroy() {
filterConfig = null;
encoding = null;
}
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain filterChain) throws IOException, ServletException {
if (request.getCharacterEncoding() == null) {
if (encoding != null) {
request.setCharacterEncoding(encoding);
}
filterChain.doFilter(request, response);
}
}
@Override//初始化的时候就去web.xml配置文件中拿到对应编码格式
public void init(FilterConfig filterConfig) throws ServletException {
this.filterConfig = filterConfig;
this.encoding = filterConfig.getInitParameter("encoding");
}
}
web.xml中配置
方式二
import java.io.IOException;
import java.util.Enumeration;
import javax.servlet.*;
public class WordFilter implements Filter {
public void destroy() {
// TODO Auto-generated method stub
}
@SuppressWarnings("unchecked")
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest request=(HttpServletRequest)req;
HttpServletResponse response=(HttpServletResponse)res;
if(request.getMethod().equalsIgnoreCase("get")){//get提交方式
Enumeration em=request.getParameterNames();
while(em.hasMoreElements()){
String name=em.nextElement().toString();
String[] values=request.getParameterValues(name);
for(int i=0;i
}
}
}else{
request.setCharacterEncoding("utf-8");
}
chain.doFilter(request, response);
}
public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub
}
}
web.xml中配置