springboot 通过拦截器获取请求参数
环境:windows10 ,jdk1.8,springboot
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-core</artifactId>
<version>5.5.7</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.11</version>
</dependency>
1.通过拦截器获取请求参数,get/post形式
public class ParamValidInterceptor implements HandlerInterceptor { enum SUBMIT_TYPE{ FORM, BODY_JSON } Map<SUBMIT_TYPE,IValidTransParam> map = new HashMap<SUBMIT_TYPE,IValidTransParam>(){ { put(SUBMIT_TYPE.FORM,new FormParam()); put(SUBMIT_TYPE.BODY_JSON,new BodyJsonParam()); } }; @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception { if(VerifyConstants.PROPERTEIS_VALID == VerifyConstants.IS_VALID){ String submitSign; IValidTransParam iValidTransParam ; Map<String, String[]> parameterMap = request.getParameterMap(); if(parameterMap.size() == 1 && ObjectUtil.isNotEmpty(parameterMap.get(VerifyConstants.VALID_KEY))){ //body请求参数提交 iValidTransParam = map.get(SUBMIT_TYPE.BODY_JSON); }else { //form表单参数提交 iValidTransParam = map.get(SUBMIT_TYPE.FORM); } String param = iValidTransParam.getVerifySignParam(request); System.out.println("请求参数:"+param); return true; } return true; } @Override public void postHandle(HttpServletRequest var1, HttpServletResponse var2, Object var3, ModelAndView var4) throws Exception { } @Override public void afterCompletion(HttpServletRequest var1, HttpServletResponse var2, Object var3, Exception var4) throws Exception { } private void consoleLog(String msg,String... params){ if(VerifyConstants.PROPERTIES_VALID_PRINT == VerifyConstants.IS_VALID_PRINT){ Console.log(msg, params); } } }
public interface IValidTransParam { String getVerifySignParam(HttpServletRequest request); }
public abstract class AbstrctValidTransParam implements IValidTransParam { protected void consoleLog(String msg,String... params){ Console.log(msg, params); } }
public class BodyJsonParam extends AbstrctValidTransParam { @Override public String getVerifySignParam(HttpServletRequest request) { BodyHttpServletRequestWrapper bodyHttpServletRequestWrapper = (BodyHttpServletRequestWrapper)request; String body = bodyHttpServletRequestWrapper.getBody(); JSONObject jsonObject = JSON.parseObject(body); System.out.println("################# body param ###################"); System.out.println("body = " + body); System.out.println("################# body param ###################"); return body; } }
public class FormParam extends AbstrctValidTransParam { @Override public String getVerifySignParam(HttpServletRequest request) { consoleLog("############################form param ###########################"); Map<String, String[]> parameterMap = request.getParameterMap(); Map<String, String> sortMap = new LinkedHashMap<String, String>(); //排序 parameterMap.entrySet().stream() .sorted(Map.Entry.comparingByKey()) .forEachOrdered(x -> sortMap.put(x.getKey(), x.getValue()[0])); StringBuilder stringBuilder = new StringBuilder(); sortMap.remove(VerifyConstants.VALID_KEY); //构建加密原文 for(Map.Entry<String,String> entry : sortMap.entrySet()){ if (ObjectUtil.isNotEmpty(entry.getKey())|| ObjectUtil.isNotEmpty(entry.getValue())) { consoleLog("key -> {},val -> {}", entry.getKey(), entry.getValue()); stringBuilder.append(entry.getKey()).append("=").append(entry.getValue()).append("&"); } } consoleLog("############################form param end ###########################"); stringBuilder = stringBuilder.deleteCharAt(stringBuilder.length() - 1); return stringBuilder.toString(); } }
2.考虑获取body时是获取的流,request只能获取一次,所以需要重写filter
public class BodyHttpServletRequestWrapper extends HttpServletRequestWrapper { private byte[] body; private ServletInputStream inputStream; public BodyHttpServletRequestWrapper(HttpServletRequest request) throws IOException { super(request); StandardServletMultipartResolver standardServletMultipartResolver = new StandardServletMultipartResolver(); //做判断,过滤掉form表单形式的,避免form表单的参数 if(standardServletMultipartResolver.isMultipart(request)){ }else { body = StreamUtils.copyToByteArray(request.getInputStream()); inputStream = new RequestCachingInputStream(body); } } public String getBody(){ return new String(body); } @Override public ServletInputStream getInputStream() throws IOException { if (inputStream != null) { return inputStream; } return super.getInputStream(); } @Override public Map<String, String[]> getParameterMap() { return super.getParameterMap(); } private static class RequestCachingInputStream extends ServletInputStream { private final ByteArrayInputStream inputStream; public RequestCachingInputStream(byte[] bytes) { inputStream = new ByteArrayInputStream(bytes); } @Override public int read() throws IOException { return inputStream.read(); } @Override public boolean isFinished() { return inputStream.available() == 0; } @Override public boolean isReady() { return true; } @Override public void setReadListener(ReadListener readlistener) { } } }
3.将过滤和filter配置起来.
配置过滤器
1.第一种方法在配置文件中配置:(此只为方式,仅作为参考,拷贝过去肯定报错)
<mvc:interceptors> <mvc:interceptor> <mvc:mapping path="/**"/> <bean class="xxxx.xx.xxx.xxxInterceptor"></bean> </mvc:interceptor> </mvc:interceptors> 2.编写类来进行配置 (此只为方式,仅作为参考,拷贝过去肯定报错) @Configuration public class WebMvcConfig implements WebMvcConfigurer { @Autowired private MyInterceptor myInterceptor; @Override public void addInterceptors(InterceptorRegistry registry) { // 添加拦截器 registry.addInterceptor(myInterceptor) .excludePathPatterns("") // 排除拦截器要拦截的路径 .addPathPatterns(""); // 添加拦截器需要要拦截的路径 } }
配置filter 1.第一种方式,编写类来进行配置,然后通过配置扫描来扫这个包,当然如果再springboot启动类之下的无需单独配置.. @Configuration public class RequserAgainFilter implements Filter { public RequserAgainFilter() { } public void init(FilterConfig filterConfig) throws ServletException { } public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { filterChain.doFilter(new BodyHttpServletRequestWrapper((HttpServletRequest)servletRequest), servletResponse); } public void destroy() { } } 2.通过编写配置类 @Configuration public class FilterConfig { @Autowired private AuthFilter authFilter; @Bean public FilterRegistrationBean registerAuthFilter() { FilterRegistrationBean registration = new FilterRegistrationBean(); registration.setFilter(authFilter); registration.addUrlPatterns("/*"); registration.setName("authFilter"); registration.setOrder(1); //值越小,Filter越靠前。 return registration; } //如果有多个Filter,再写一个public FilterRegistrationBean registerOtherFilter(){...}即可。 }