过滤器入门案例分析

package com.ry.filter;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Map;

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.HttpServletRequestWrapper;

public class RyEncodingFilter implements Filter {
private FilterConfig config = null;
private String encode = null;
public void destroy() {

}

public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
//--全站响应乱码解决
response.setContentType("text/html;charset="+encode);
//--全站请求乱码解决
chain.doFilter(new MyHttpServletRequest((HttpServletRequest) request), response);
}
/**
* request中有请求乱码,没法直接解决
* 所以我们的思路是,通过装饰,改造request对象上和获取请求参数相关的三个方法,使这三个方法拿到有乱码的之后,解决乱码再返回
* @author park
*
*/
class MyHttpServletRequest extends HttpServletRequestWrapper{
HttpServletRequest request = null;
boolean hasNotEncode = true;
public MyHttpServletRequest(HttpServletRequest request) {
super(request);
this.request = request;
}

@Override
public Map<String,String[]> getParameterMap() {
try {
if(request.getMethod().equals("POST")){//--对于POST请求,一行代码解决乱码,返回Map
request.setCharacterEncoding(encode);
return request.getParameterMap();
}else if(request.getMethod().equals("GET")){//--对于GET请求
//--拿到map,有乱码!
Map<String,String[]> map = request.getParameterMap();
//--遍历map,处理所有的乱码
if(hasNotEncode){//--由于request会缓存第一次获取过的map,所以乱码解决只在第一次做即可,利用这个标记,使乱码解决代码只在第一次执行
for(Map.Entry<String, String[]>entry : map.entrySet()){
String [] vs = entry.getValue();
for(int i = 0;i<vs.length;i++){
vs[i] = new String(vs[i].getBytes("iso8859-1"),encode);
}
}
hasNotEncode = false;
}
//--返回处理过乱码的map
return map;
}else{//--其他请求方式,不做处理,直接返回
return request.getParameterMap();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}

@Override
public String[] getParameterValues(String name) {
return getParameterMap().get(name);
}

@Override
public String getParameter(String name) {
String [] vs = getParameterValues(name);
return  vs == null ? null : vs[0];
}

}

public void init(FilterConfig filterConfig) throws ServletException {
this.config = filterConfig;
this.encode = filterConfig.getInitParameter("encoding");
}

}
==========附件中有详细的标注讲解==========
(ps:希望爱好编程的小伙伴能加这个群,互相帮助,共同学习。群号: 141877583  )

你可能感兴趣的:(filter)