SpringMVC参数统一处理

项目中遇到有些用户不小心输入空格,导致校验时,出现校验失败的现场,为此,写一个拦截器统一处理下入参。

/**
 * 去掉前后空格和特殊字符
 *
 * @author yupeng
 */
@Slf4j
@ControllerAdvice
public class OAuth2RequestBodyAdvice implements RequestBodyAdvice {
    @Override
    public boolean supports(MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
        return true;
    }

    @Override
    public Object handleEmptyBody(Object body, HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
        return body;
    }

    @Override
    public HttpInputMessage beforeBodyRead(HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) throws IOException {
        return new CustomHttpInputMessage(httpInputMessage);
    }

    @Override
    public Object afterBodyRead(Object body, HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
        return body;
    }

    class CustomHttpInputMessage implements HttpInputMessage {
        private HttpInputMessage origin;

        public CustomHttpInputMessage(HttpInputMessage httpInputMessage) {
            this.origin = httpInputMessage;
        }

        @Override
        public InputStream getBody() throws IOException {
            HttpHeaders headers = origin.getHeaders();
            InputStream body = origin.getBody();

            // 空参,get 请求,流为空,非 application/json 请求,不处理参数
            MediaType contentType = headers.getContentType();
            if (contentType == null) {
                return body;
            }
            if (!contentType.isCompatibleWith(MediaType.APPLICATION_JSON)) {
                return body;
            }
            if (body == null) {
                return body;
            }
            String params = IOUtils.toString(body, "utf-8");
            if (StringUtils.isBlank(params)) {
                return body;
            }

            // 正式过滤 json 参数
            Object parse = JSON.parse(params);
            if (parse instanceof JSONArray) {
                JSONArray jsonArray = (JSONArray) parse;
                trimJsonArray(jsonArray);
            } else if (parse instanceof JSONObject) {
                trimJsonObject((JSONObject) parse);
            } else {
                log.error("参数不支持去空格:" + parse + " contentType:" + contentType);
            }
            return IOUtils.toInputStream(JSON.toJSONString(parse, SerializerFeature.WriteMapNullValue), "UTF-8");
        }

        private void trimJsonObject(JSONObject jsonObject) {
            Iterator<Map.Entry<String, Object>> iterator = jsonObject.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry<String, Object> next = iterator.next();
                String key = next.getKey();
                Object value = next.getValue();
                if (value instanceof JSONArray) {
                    trimJsonArray((JSONArray) value);
                } else if (value instanceof JSONObject) {
                    trimJsonObject((JSONObject) value);
                } else if (value instanceof String) {
                    String trimValue = StringUtils.trim(ObjectUtils.toString(value));
                    next.setValue(trimValue);
                }
            }
        }

        private void trimJsonArray(JSONArray jsonArray) {
            for (int i = 0; i < jsonArray.size(); i++) {
                Object object = jsonArray.get(i);
                if (object instanceof JSONObject) {
                    JSONObject jsonObject = jsonArray.getJSONObject(i);
                    trimJsonObject(jsonObject);
                } else if (object instanceof String) {
                    String trimValue = StringUtils.trim(ObjectUtils.toString(object));
                    jsonArray.set(i, trimValue);
                }

            }
        }

        @Override
        public HttpHeaders getHeaders() {
            return origin.getHeaders();
        }

    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring MVC 中,我们可以通过实现一个异常处理器来统一处理控制器抛出的异常。具体步骤如下: 1. 实现一个异常处理器类,并添加 @ControllerAdvice 注解。 2. 在异常处理器类中定义处理不同类型异常的方法,并使用 @ExceptionHandler 注解标记。 3. 在方法中编写异常处理逻辑,例如将异常信息记录到日志中、返回错误信息等。 4. 如果需要返回 JSON 格式的错误信息,可以使用 @ResponseBody 注解。 以下是一个简单的示例: ```java @ControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(Exception.class) @ResponseBody public Map<String, Object> handleException(Exception e) { Map<String, Object> errorMap = new HashMap<>(); errorMap.put("code", "500"); errorMap.put("message", e.getMessage()); return errorMap; } @ExceptionHandler(MethodArgumentNotValidException.class) @ResponseBody public Map<String, Object> handleValidationException(MethodArgumentNotValidException e) { Map<String, Object> errorMap = new HashMap<>(); errorMap.put("code", "400"); errorMap.put("message", "参数校验失败"); List<String> errors = e.getBindingResult() .getFieldErrors() .stream() .map(FieldError::getDefaultMessage) .collect(Collectors.toList()); errorMap.put("errors", errors); return errorMap; } } ``` 在上述示例中,我们定义了两个处理异常的方法:handleException 和 handleValidationException。handleException 方法处理所有未被其他方法处理的异常,返回一个包含错误码和错误信息的 Map 对象;handleValidationException 方法处理参数校验失败的异常,并将校验失败的所有错误信息返回。 最后,需要注意的是,如果同时存在多个异常处理方法,Spring MVC 会按照异常类型匹配最合适的处理方法。如果没有找到合适的处理方法,则会将异常抛给 Servlet 容器进行处理

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值