EncodingFilter.java
代码:
package com.demo.servlet;
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.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import sun.security.krb5.Config;
public class EncodingFilter implements Filter {
protected FilterConfig filterConfig;
protected String targetEncoding = "gb2312";
public void init(FilterConfig config) throws ServletException {
// TODO Auto-generated method stub
this.filterConfig=config;
this.targetEncoding =config.getInitParameter("encoding");
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
// TODO Auto-generated method stub
System.out.println("使用一下方法对请求进行编码:encoding="+targetEncoding);
HttpServletRequest request2=(HttpServletRequest)request;
request.setCharacterEncoding(targetEncoding);
chain.doFilter( request,response );
}
public void setFilterConfig(FilterConfig filterConfig) {
this.filterConfig = filterConfig;
}
public void destroy() {
// TODO Auto-generated method stub
this.filterConfig = null;
}
}
web.xml
<filter>
<filter-name>encoding</filter-name>
<filter-class>com.demo.servlet.EncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>gb2312</param-value>
</init-param>
</filter>