package com.lzw.Filter;

/ * *

  • @author lzw
  • @Description
  • @creat 2020-11-24-14:07

/ import javax.servlet.; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.Map;

/ * *

  • Filter to resolve all garbled get and POST requests

*/ public class GenericEncodingFilter implements Filter {

public void destroy() { } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {HttpServletResponse myResponse=(HttpServletResponse) response; myResponse.setContentType("text/html; charset=UTF-8"); HttpServletRequest = (HttpServletRequest) request; HttpServletRequest = (HttpServletRequest) request; Myrequest = new myRequest (HttpServletRequest); chain.doFilter(myrequest, response); } public void init(FilterConfig filterConfig) throws ServletException { }Copy the code

}

/ / custom request object, it’s a wrapper class class MyRequest extends HttpServletRequestWrapper {

private HttpServletRequest request; Private Boolean hasEncode; Public MyRequest(HttpServletRequest Request) {super(request); public MyRequest(HttpServletRequest Request) {super(request); // super must write this.request = request; } @override public Map getParameterMap() {String method = request.getMethod(); If (method equalsIgnoreCase (" post ")) {/ / post request try {/ / processing post gibberish request. SetCharacterEncoding (" utf-8 "); return request.getParameterMap(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); }} else if (method.equalSignorecase ("get")) {// Get request Map<String, String[]> parameterMap = request.getParameterMap(); if (! HasEncode) {// Ensure that the get manual encoding logic is run only once for (String parameterName: parameterMap.keySet()) { String[] values = parameterMap.get(parameterName); if (values ! = null) { for (int i = 0; i < values.length; Values [I] = new String(values[I].getBytes(" ISo-8859-1 "), "utF-8 "); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } } } hasEncode = true; } return parameterMap; } return super.getParameterMap(); } @override public String getParameter(String name) {Map<String, String[]> parameterMap = getParameterMap(); String[] values = parameterMap.get(name); if (values == null) { return null; } return values[0]; @override public String[] getParameterValues(String name) {Map<String, String[]> parameterMap = getParameterMap(); String[] values = parameterMap.get(name); return values; }Copy the code

}