|
1. 首先在你的工程中创建Servlet,package为xiaogu ,name为EncodingFilter,然后把下边代码粘贴过去。
package xiaogu;
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中把下面的代码插到</servlet>与<servlet-mapping>中间,
<filter>
<filter-name>encodingfilter</filter-name>
<filter-class>xiaogu.EncodingFilter</filter-class>//xiaogu为你的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> |
|