创建拦截器类,需要实现javax.servlet.Filter接口
public class FilterDemo1 implements Filter {
@Override
public void init(FilterConfig arg0) throws ServletException {
System.err.println("服务器启动时调用此方法,只调用一次,用来初始化");
}
@Override
public void destroy() {
System.err.println("服务器退出时调用此方法,只调用一次");
}
@Override
public void doFilter(ServletRequest arg0, ServletResponse arg1,
HttpServletRequest request = (HttpServletRequest) arg0;
HttpServletResponse response = (HttpServletResponse) arg1;
MyRequest request1 = new MyRequest(request);
//设置request的编码方式
request1.setCharacterEncoding("utf-8");
//解除拦截
chain.doFilter(request1, response);
}
自定义内部类,继承HttpServletRequestWrapper类
注:HttpServletRequestWrapper类实现了HttpServletRequest接口,重写了接口方法
class MyRequest extends HttpServletRequestWrapper{
private HttpServletRequest request ;
public MyRequest(HttpServletRequest request) {
super(request);
this.request = request;
}
@Override
public String getParameter(String name) {
String value = request.getParameter(name);
//判Null空
if(value==null){
return null;
}
//判请求方式
if(request.getMethod().equalsIgnoreCase("POST")){
return value;
}
try {
//转换编码方式
value = new String(value.getBytes("ISO-8859-1"),"utf-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
return value;
}
}
在web.xml配置文件中加载Filter拦截器
<filter>
<filter-name>FilterDemo1</filter-name>
<filter-class>filter.demo.FilterDemo1</filter-class>
</filter>
<filter-mapping>
<filter-name>FilterDemo1</filter-name>
<!-- /*为拦截所有请求 -->
<url-pattern>/*</url-pattern>
</filter-mapping>