过滤器
生命周期
init(FilterConfig) doFilter(request,response,filterChain) destroy()
1、Filter对象在tomcat服务器启动时 创建,调用init方法 (只会创建一个对象,init方法执行一次)
2、doFilter 每次拦截目标资源时,执行
3、destroy 服务器关闭时执行
1、如果连接目标资源是一个Servlet,可以选择url和servlet名称两种配置方式
<!-- 拦截/hello是Servlet 路径 -->
<url-pattern>/hello</url-pattern>
<!-- 拦截Servlet 还可以通过Servlet 名称进行拦截 -->
<servlet-name>HelloServlet</servlet-name>
2、url-pattern 和 Servlet中路径写法一样,有三种 : 完全匹配、目录匹配、扩展名匹配
3、<dispatcher>指定过滤器所拦截的资源被 Servlet 容器调用的方式
容器调用服务器端资源 有四种方式
REQUEST、FORWARD、INCLUDE、ERROR
解决编码问题的过滤器
package com.hrh.web.filter;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Map;
public class GenericEncodingFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void destroy() {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
//向下转型
HttpServletRequest httpservletRequest = (HttpServletRequest) servletRequest;
//包装
ServletRequest myRequest=new MyRequest(httpservletRequest);
filterChain.doFilter(myRequest,servletResponse);
//servletResponse.setCharacterEncoding("utf-8");
//servletResponse.setContentType("text/html;charset=utf-8");
}
class MyRequest extends HttpServletRequestWrapper{
private HttpServletRequest request;
//flag map是否已经重新编码过
private boolean isUpdate = false;
public MyRequest(HttpServletRequest request){
super(request);
this.request=request;
}
@Override
public Map<String,String[]> getParameterMap(){
//获得请求方式
String method = request.getMethod();
if("post".equalsIgnoreCase(method)){
try {
request.setCharacterEncoding("utf-8");
return request.getParameterMap();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}else if("get".equalsIgnoreCase(method)){
Map<String, String[]> parameterMap = request.getParameterMap();
if(parameterMap!=null&&isUpdate==false){
//遍历map 将所有vlaue全部编码再解码
for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
String[] value = entry.getValue();
for(int i=0;i<value.length;i++){
try {
value[i]=new String(value[i].getBytes("iso-8859-1"),"utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
//flag重新赋值
isUpdate=true;
}
return parameterMap;
}
//其他请求方式 则返回父类Map
return super.getParameterMap();
}
@Override
public String getParameter(String name){
//获得编码正确后的map 直接取数据
Map<String, String[]> parameterMap = this.getParameterMap();
String[] valueArr=parameterMap.get(name);
if(valueArr!=null){
return valueArr[0];
}else{
return null;
}
}
@Override
public String[] getParameterValues(String name){
Map<String, String[]> parameterMap = this.getParameterMap();
String[] valueArr = parameterMap.get(name);
return valueArr;
}
}
}
监听器