java中用过滤器解决字符编码问题
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中配置
<filter>
<filter-name>EncodingFilter</filter-name>
<filter-class>EncodingFilter</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>
方式二
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<values.length;i++){
values[i]=new String(values[i].getBytes("iso-8859-1"),"utf-8");//把所有字符都转换为指定的编码格式
}
}
}else{
request.setCharacterEncoding("utf-8");
}
chain.doFilter(request, response);
}
public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub
}
}
web.xml中配置
<filter>
<filter-name>WordFilter</filter-name>
<filter-class>filter.WordFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>WordFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>