1. Write HttpWrapper to inherit HttpServletRequestWrapper:
package com.xx.httpwrapper; import javax.servlet.ServletInputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; import java.io. *; import java.net.URLDecoder; import java.util. *; /** * describe: * * @author ssl * @create 2018/05/03 16:05 */ public class HttpWrapper extends HttpServletRequestWrapper { private Map<String, String[]> paramsMap; @Override public Map getParameterMap() { return paramsMap; } @Override public String getParameter(String name) {// Rewrite getParameter, which means the parameter is obtained from the map in the current class String[] values = paramsMap.get(name); if (values == null || values.length == 0) { return null; } return values[0]; } @Override public String[] getParameterValues(String name) {// 同上 return paramsMap.get(name); } @Override public Enumeration getParameterNames() { return Collections.enumeration(paramsMap.keySet()); } private String getRequestBody(InputStream stream) { String line = ""; StringBuilder body = new StringBuilder(); int counter = 0; // Read the data content submitted by POST BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); try { while ((line = reader.readLine()) != null) { if (counter > 0) { body.append("rn"); } body.append(line); counter++; } } catch (IOException e) { e.printStackTrace (); } return body.toString(); } private HashMap<String, String[]> getParamMapFromPost(HttpServletRequest request) { String body = ""; try { body = getRequestBody(request.getInputStream()); } catch (IOException e) { e.printStackTrace (); } HashMap<String, String[]> result = new HashMap<String, String[]>(); if (null == body || 0 == body.length()) { return result; } return parseQueryString(body); } // custom decoding function private String decodeValue(String value) { if (value.contains("%u")) { return Encodes.urlDecode(value); } else { try { return URLDecoder.decode(value, "UTF-8"); } catch (UnsupportedEncodingException e) { return "";// non-UTF-8 encoding } } } public HashMap<String, String[]> parseQueryString(String s) { String valArray[] = null; if (s == null) { throw new IllegalArgumentException(); } HashMap<String, String[]> ht = new HashMap<String, String[]>(); StringTokenizer st = new StringTokenizer(s, "&"); while (st.hasMoreTokens()) { String pair = (String) st.nextToken(); int pos = pair.indexOf('='); if (pos == -1) { continue; } String key = pair.substring(0, pos); String val = pair.substring(pos + 1, pair.length()); if (ht.containsKey(key)) { String oldVals[] = (String[]) ht.get(key); valArray = new String[oldVals.length + 1]; for (int i = 0; i < oldVals.length; i++) { valArray[i] = oldVals[i]; } valArray[oldVals.length] = decodeValue(val); } else { valArray = new String[1]; valArray[0] = decodeValue(val); } ht.put(key, valArray); } return ht; } private Map<String, String[]> getParamMapFromGet(HttpServletRequest request) { return parseQueryString(request.getQueryString()); } private final byte[] body; // 报文 public HttpWrapper(HttpServletRequest request) throws IOException { super(request); body = readBytes(request.getInputStream()); // First get data from POST if ("POST".equals(request.getMethod().toUpperCase())) { paramsMap = getParamMapFromPost(this); } else { paramsMap = getParamMapFromGet(this); } } @Override public BufferedReader getReader() throws IOException { return new BufferedReader(new InputStreamReader(getInputStream())); } @Override public ServletInputStream getInputStream() throws IOException { final ByteArrayInputStream bais = new ByteArrayInputStream(body); return new ServletInputStream() { @Override public int read() throws IOException { return bais.read(); } }; } private static byte[] readBytes(InputStream in) throws IOException { BufferedInputStream bufin = new BufferedInputStream(in); int buffSize = 1024; ByteArrayOutputStream out = new ByteArrayOutputStream(buffSize); byte[] temp = new byte[buffSize]; int size = 0; while ((size = bufin.read(temp)) != -1) { out.write(temp, 0, size); } bufin.close(); byte[] content = out.toByteArray(); return content; } }
2. Write HttpServletRequestReplacedFilter to inherit Filter:
package com.xx.httpwrapper; import org.apache.commons.lang3.StringUtils; import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import java.io.IOException; /** * describe: * * @author ssl * @create 2018/05/03 16:07 */ public class HttpServletRequestReplacedFilter implements Filter { @Override public void destroy() { } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { ServletRequest requestWrapper = null; if (request instanceof HttpServletRequest) { HttpServletRequest httpServletRequest = (HttpServletRequest) request; if ("POST".equals(httpServletRequest.getMethod().toUpperCase()) && StringUtils.isNotBlank(httpServletRequest.getContentType()) && httpServletRequest.getContentType().equalsIgnoreCase( "application/json;charset=utf-8")) { requestWrapper = new WeHttpWrapper((HttpServletRequest) request); } } if (requestWrapper == null) { chain.doFilter(request, response); } else { chain.doFilter(requestWrapper, response); } } @Override public void init(FilterConfig arg0) throws ServletException { } }
3. Write the Encodes class:
package com.xx.httpwrapper; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.net.URLEncoder; import com.xx.utils.Exceptions; import org.apache.commons.codec.DecoderException; import org.apache.commons.codec.binary.Base64; import org.apache.commons.codec.binary.Hex; import org.apache.commons.lang3.StringEscapeUtils; /** * describe: * * @author shi_senlin * @create 2018/05/03 20:50 */ public class Encodes { private static final String DEFAULT_URL_ENCODING = "UTF-8"; private static final char[] BASE62 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".toCharArray(); /** *Hex encoding. */ public static String encodeHex(byte[] input) { return Hex.encodeHexString(input); } /** * Hex decoding. */ public static byte[] decodeHex(String input) { try { return Hex.decodeHex(input.toCharArray()); } catch (DecoderException e) { throw Exceptions.unchecked(e); } } /** * Base64 encoding. */ public static String encodeBase64(byte[] input) { return Base64.encodeBase64String(input); } /** * Base64 encoded, URL safe (converts illegal characters '+' and '/' in Base64 URLs to '-' and '_', see RFC3548). */ public static String encodeUrlSafeBase64(byte[] input) { return Base64.encodeBase64URLSafeString(input); } /** * Base64 decoding. */ public static byte[] decodeBase64(String input) { return Base64.decodeBase64(input); } /** *Base62 encoded. */ public static String encodeBase62(byte[] input) { char[] chars = new char[input.length]; for (int i = 0; i < input.length; i++) { chars[i] = BASE62[(input[i] & 0xFF) % BASE62.length]; } return new String(chars); } /** * Html transcoding. */ public static String escapeHtml(String html) { return StringEscapeUtils.escapeHtml4(html); } /** * Html decoding. */ public static String unescapeHtml(String htmlEscaped) { return StringEscapeUtils.unescapeHtml4(htmlEscaped); } /** * Xml transcoding. */ public static String escapeXml(String xml) { return StringEscapeUtils.escapeXml(xml); } /** * Xml decoding. */ public static String unescapeXml(String xmlEscaped) { return StringEscapeUtils.unescapeXml(xmlEscaped); } /** * URL encoding, Encode defaults to UTF-8. */ public static String urlEncode(String part) { try { return URLEncoder.encode(part, DEFAULT_URL_ENCODING); } catch (UnsupportedEncodingException e) { throw Exceptions.unchecked(e); } } /** * URL decoding, Encode defaults to UTF-8. */ public static String urlDecode(String part) { try { return URLDecoder.decode(part, DEFAULT_URL_ENCODING); } catch (UnsupportedEncodingException e) { throw Exceptions.unchecked(e); } } }4. Write Exceptions:
/** * Copyright (c) 2005-2012 springside.org.cn */ package com.xx.utils; import javax.servlet.http.HttpServletRequest; import java.io.PrintWriter; import java.io.StringWriter; /** * Tool class about exceptions. * @author calvin * @version 2013-01-15 */ public class Exceptions { /** * Convert CheckedException to UncheckedException. */ public static RuntimeException unchecked(Exception e) { if (e instanceof RuntimeException) { return (RuntimeException) e; } else { return new RuntimeException(e); } } /** * Convert ErrorStack to String. */ public static String getStackTraceAsString(Throwable e) { if (e == null){ return ""; } StringWriter stringWriter = new StringWriter(); e.printStackTrace(new PrintWriter(stringWriter)); return stringWriter.toString(); } /** * Determine whether the exception is caused by some underlying exception. */ public static boolean isCausedBy(Exception ex, @SuppressWarnings("unchecked") Class<? extends Exception>... causeExceptionClasses) { Throwable cause = ex.getCause(); while (cause != null) { for (Class<? extends Exception> causeClass : causeExceptionClasses) { if (causeClass.isInstance(cause)) { return true; } } cause = cause.getCause(); } return false; } /** * Get exception class in request * @param request * @return */ public static Throwable getThrowable(HttpServletRequest request){ Throwable ex = null; if (request.getAttribute("exception") != null) { ex = (Throwable) request.getAttribute("exception"); } else if (request.getAttribute("javax.servlet.error.exception") != null) { ex = (Throwable) request.getAttribute("javax.servlet.error.exception"); } return ex; } }
5. Add the following fragment to web.xml:
<filter> <filter-name>requestFilter</filter-name> <filter-class>com.xx.httpwrapper.HttpServletRequestReplacedFilter</filter-class> </filter> <filter-mapping> <filter-name>requestFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>