springboot 拦截请求,统一化处理post get
适用场景:为了方便后台做统一化处理,方便前后端交互,在拦截器中将post get 统一处理,在control就不需要区分该请求是post 还是get请求,很方便。
@Component
public class RequestParamInterceptor implements HandlerInterceptor {private static Logger log = LoggerFactory.getLogger( RequestParamInterceptor.class );@AutowiredObjectMapper objectMapper;@Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {Map paramMap = new HashMap<>();String method = request.getMethod();//获取请求方式log.info( "请求方式是: " + method );String url = request.getRequestURI();//获取请求路径log.info( "请求URL: "+url );ServletInputStream servletInputStream = request.getInputStream();/** @author pg* @date 2019-11-21 13:56* 无论是 post 还是 get请求统一获取参数封装成 map发给control 让controller获取参数更加的方便
*/if ("POST".equals( method ) || "PUT".equals( method )) {String jsonStr = inputStreamToString( servletInputStream );//json字符串if (!isJson( jsonStr ) || jsonStr.length() < 1) {//判断是否是jsonif (!isJson( jsonStr ) || jsonStr.length() < 1) {//判断是否是jsonRestUtil.response( response, SystemCode.ParameterValidError.getCode(), SystemCode.ParameterValidError.getMessage() + "不是正常的json参数" );return false;}}paramMap = CommontMethod.stringToJson( jsonStr );//传入的参数log.info( "POST: paraMap: " + paramMap );} else if ("GET".equals( method )) {Enumeration enu = request.getParameterNames();while (enu.hasMoreElements()) {String paraName = (String) enu.nextElement();paramMap.put( paraName, request.getParameter( paraName ) );}log.info( "GET: paraMap: " + paramMap );}request.setAttribute( "param_json", paramMap );return true;}/*** 判断是否是json结构*/private boolean isJson(String jsonInString) {try {final ObjectMapper mapper = new ObjectMapper();mapper.readTree( jsonInString );return true;} catch (IOException e) {return false;}}private String inputStreamToString(InputStream is) {ByteArrayOutputStream result = new ByteArrayOutputStream();byte[] buffer = new byte[1024];int length;String str = "";try {while ((length = is.read( buffer )) != -1) {result.write( buffer, 0, length );}str = result.toString( StandardCharsets.UTF_8.name() );return str;} catch (IOException e) {e.printStackTrace();}return str;}
}
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
