无论是post请求还是get请求都不会出现乱码问题
使用的技术是servlet的过滤器
package filter;
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;
/**
* Servlet Filter implementation class EncodingFilter
*/
public class EncodingFilter implements Filter {
public void destroy() {
}
/**
* 调包request
* 1. 写一个request的装饰类
* 2. 在放行时,使用我们自己的request
*/
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
request.setCharacterEncoding("UTF-8");
HttpServletRequest req = (HttpServletRequest)request;//转为子类HttpServletRequest
if(req.getMethod().equals("GET")){
EncodingRequest er = new EncodingRequest(req);
chain.doFilter(er, response);
}else if (req.getMethod().equals("POST")) {
chain.doFilter(request, response);
}
}
public void init(FilterConfig fConfig) throws ServletException {
}
}
具体实现类
package filter;
import java.io.UnsupportedEncodingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
/**
* 装饰者模式
* 装饰request
* @author My World
*
*/
public class EncodingRequest extends HttpServletRequestWrapper{
private HttpServletRequest req;
public EncodingRequest(HttpServletRequest request) {
super(request);
this.req = request;
}
@Override
public String getParameter(String name) {
String value = req.getParameter(name);
//处理编码问题
try {
value = new String(value.getBytes("ISO-8859-1"),"UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return value;
}
}
web.xml的配置
/*代码所有的页面都通过它过滤
<filter>
<display-name>EncodingFilter</display-name>
<filter-name>EncodingFilter</filter-name>
<filter-class>filter.EncodingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>EncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>