今天做项目又遇到了乱码问题,懒得再写或上网copy了,干脆记在这里,随时用随时取,同时也能方便大家工作或学习!有好的想法要多多交流啊!
1. 在你的工程中EncodingFilter类,然后把下边代码粘贴进去。
import java.io.IOException;
import java.io.PrintWriter;
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.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
public class EncodingFilter extends HttpServlet implements Filter {
private FilterConfig filterConfig;
private String trargetEncoding=null;
public void init(FilterConfig filterConfig)throws ServletException{
this.filterConfig=filterConfig;
this.trargetEncoding=this.filterConfig.getInitParameter("encoding");
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) {
// TODO Auto-generated method stub
try{
//在控制台输出目标编码
System.out.println("trargetEncoding:"+trargetEncoding+"\n");
//执行编码,实际的处理内容
request.setCharacterEncoding(trargetEncoding);
filterChain.doFilter(request,response);
} catch (ServletException sx) {
filterConfig.getServletContext().log(sx.getMessage());
}
catch (IOException iox){
filterConfig.getServletContext().log(iox.getMessage());
}
}
public void destroy() {
//清空资源
this.filterConfig=null;
this.trargetEncoding=null;
}
}
2.在web.xml中插入下面的代码,
<filter>
<filter-name>encodingfilter</filter-name>
<filter-class>xxxx.EncodingFilter</filter-class>//xxxx为你的Java程序的包名,EncodingFilter是你的java的类名。
<init-param>
<description>encode to UTF-8</description>//UTF-8表示中文编码
<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>
ok中文乱码问题全部解决。整了一下,分享给大家。