1. 配置自己想要的编码
2. 编写过滤器
public class EncodingFilter implements Filter {
String encoding;
public EncodingFilter() {
}
public void destroy() {
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest hRquest = (HttpServletRequest)request;
MyHttpRequest myRequest = new MyHttpRequest(hRquest,encoding);
//过滤链传递时要传递的是我们处理过的request
chain.doFilter(myRequest, response);
}
public void init(FilterConfig fConfig) throws ServletException {
encoding = fConfig.getInitParameter("encoding");
System.out.println("读取到的编码:"+encoding);
}
}
//使用装饰者模式重新构建getParameter方法
class MyHttpRequest extends HttpServletRequestWrapper{
//被装饰的对象
HttpServletRequest hRequest;
String encoding;
public MyHttpRequest(HttpServletRequest request,String encoding) {
super(request);
hRequest = request;
this.encoding = encoding;
}
@Override
public String getParameter(String name) {
//获取原来的参数
String value = hRequest.getParameter(name);
//如果是get方法,那么手动解码
if ("GET".equals(hRequest.getMethod())){
try {
return new String(value.getBytes("iso-8859-1"),encoding);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return value;
}
}
3. servlet获取前端输入的参数
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
String name = request.getParameter("name");
String password = request.getParameter("password");
System.out.println(name+":"+password);
/*
* 注意:
* 因为我们只是重写了request.getParameter()方法,其他方法无效哦*/
}