Filter过滤器的代码
package cn.yellowimg.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.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
/**
* Servlet Filter implementation class EncodingFilter
*/
//过滤全站
@WebFilter("/*")
public class EncodingFilter implements Filter {
public void destroy() {
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest rq = (HttpServletRequest)request;
//解决post编码问题
if(rq.getMethod().equals("POST"))
{
rq.setCharacterEncoding("utf-8");
chain.doFilter(rq, response);
}
//解决get编码问题
else {
//调包request 装饰者模式
EncodingRequest eq = new EncodingRequest(rq);
chain.doFilter(eq, response);
}
}
public void init(FilterConfig fConfig) throws ServletException {
}
}
调包request(即增强request中的getParameter()方法)
package cn.yellowimg.filter;
import java.io.UnsupportedEncodingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
//继承tomcat提供的HttpServletRequestWrapper,增强request
public class EncodingRequest extends HttpServletRequestWrapper {
HttpServletRequest httpServletRequest;
public EncodingRequest(HttpServletRequest request) {
super(request);
this.httpServletRequest = request;
}
@Override
//重写getParameter方法,将iso-8859-1专成utf-8编码
public String getParameter(String name) {
String value = super.getParameter(name);
try {
value = new String(value.getBytes("iso-8859-1"), "utf-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return value;
}
}