1、拦载器
package com.Interceptor;import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;import javax.security.auth.login.LoginException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;import org.apache.commons.lang3.StringUtils;import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;public class PayInterceptor implements HandlerInterceptor {@Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {//获取进过拦截器的路径String requestURI = request.getRequestURI();String method = request.getMethod();if ("POST".equals(method)) {RequestBodyWrapper requestBodyWrapper = new RequestBodyWrapper(request);String body = requestBodyWrapper.getBody();System.out.println(body);//数据处理JSONObject requestJO = JSON.parseObject(body);System.out.println(requestJO.getString("payItemNo"));}if ("GET".equals(method)) {String queryString = request.getQueryString();if (StringUtils.isNotEmpty(queryString)) {String decodeUrl = URLDecoder.decode(queryString, "utf-8");System.out.println(decodeUrl);//String[] strs = decodeUrl.split("&");//拆分//数据处理Map<String, String> params = new HashMap<String, String>();Map<String, String[]> requestParams = request.getParameterMap();for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {String name = (String) iter.next();String[] values = (String[]) requestParams.get(name);String valueStr = "";for (int i = 0; i < values.length; i++) {valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";}// 乱码解决,这段代码在出现乱码时使用。// valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");params.put(name, valueStr);}System.out.println(params.get("dade"));}}//放行//return true;//拦截//response.sendRedirect(request.getContextPath() + "/login");returnJson(response,"{\"code\":400,\"msg\":\"不合法\"}");return false;}/*返回客户端数据*/private void returnJson(HttpServletResponse response, String json) throws Exception{PrintWriter writer = null;response.setCharacterEncoding("UTF-8");response.setContentType("text/html; charset=utf-8");try {writer = response.getWriter();writer.print(json);} catch (IOException e) {} finally {if (writer != null)writer.close();}}@Overridepublic void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {}@Overridepublic void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {}
}
2、使拦载器生效
package com.Interceptor;import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.validation.MessageCodesResolver;
import org.springframework.validation.Validator;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.config.annotation.*;import java.util.List;@Configuration
public class PayMvcConfig implements WebMvcConfigurer {@Overridepublic void configurePathMatch(PathMatchConfigurer pathMatchConfigurer) {}@Overridepublic void configureContentNegotiation(ContentNegotiationConfigurer contentNegotiationConfigurer) {}@Overridepublic void configureAsyncSupport(AsyncSupportConfigurer asyncSupportConfigurer) {}@Overridepublic void configureDefaultServletHandling(DefaultServletHandlerConfigurer defaultServletHandlerConfigurer) {}@Overridepublic void addFormatters(FormatterRegistry formatterRegistry) {}@Overridepublic void addInterceptors(InterceptorRegistry interceptorRegistry) {//注册拦载器,拦载全部,放行login和registerinterceptorRegistry.addInterceptor(new PayInterceptor()).addPathPatterns("/**").excludePathPatterns("/login", "/register");}@Overridepublic void addResourceHandlers(ResourceHandlerRegistry resourceHandlerRegistry) {}@Overridepublic void addCorsMappings(CorsRegistry corsRegistry) {}@Overridepublic void addViewControllers(ViewControllerRegistry viewControllerRegistry) {}@Overridepublic void configureViewResolvers(ViewResolverRegistry viewResolverRegistry) {}@Overridepublic void addArgumentResolvers(List<HandlerMethodArgumentResolver> list) {}@Overridepublic void addReturnValueHandlers(List<HandlerMethodReturnValueHandler> list) {}@Overridepublic void configureMessageConverters(List<HttpMessageConverter<?>> list) {}@Overridepublic void extendMessageConverters(List<HttpMessageConverter<?>> list) {}@Overridepublic void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> list) {}@Overridepublic void extendHandlerExceptionResolvers(List<HandlerExceptionResolver> list) {}@Overridepublic Validator getValidator() {return null;}@Overridepublic MessageCodesResolver getMessageCodesResolver() {return null;}
}
3、post请求处理
package com.Interceptor;import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.*;public class RequestBodyWrapper extends HttpServletRequestWrapper {private final String body;public RequestBodyWrapper(HttpServletRequest request) {super(request);StringBuilder stringBuilder = new StringBuilder();BufferedReader bufferedReader = null;InputStream inputStream = null;try {inputStream = request.getInputStream();if (inputStream != null) {bufferedReader = new BufferedReader(new InputStreamReader(inputStream));char[] charBuffer = new char[128];int bytesRead = -1;while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {stringBuilder.append(charBuffer, 0, bytesRead);}} else {stringBuilder.append("");}} catch (IOException ex) {} finally {if (inputStream != null) {try {inputStream.close();}catch (IOException e) {e.printStackTrace();}}if (bufferedReader != null) {try {bufferedReader.close();}catch (IOException e) {e.printStackTrace();}}}body = stringBuilder.toString();}@Overridepublic ServletInputStream getInputStream() throws IOException {final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(body.getBytes());ServletInputStream servletInputStream = new ServletInputStream() {@Overridepublic boolean isFinished() {return false;}@Overridepublic boolean isReady() {return false;}@Overridepublic void setReadListener(ReadListener readListener) {}@Overridepublic int read() throws IOException {return byteArrayInputStream.read();}};return servletInputStream;}@Overridepublic BufferedReader getReader() throws IOException {return new BufferedReader(new InputStreamReader(this.getInputStream()));}public String getBody() {return this.body;}}