當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
2,Spring-mvc添加参数校验:避免参数格式不正确导致的400
生活随笔
收集整理的這篇文章主要介紹了
2,Spring-mvc添加参数校验:避免参数格式不正确导致的400
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
2019獨角獸企業重金招聘Python工程師標準>>>
?在有參數校驗的基礎上,新建異常處理類:(@ControllerAdvice("com.store.score.rpc.web")控制訪問提示信息范圍)
package com.store.score.util;import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletResponse; import javax.validation.UnexpectedTypeException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.http.converter.HttpMessageNotReadableException; import org.springframework.validation.BindingResult; import org.springframework.validation.FieldError; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; import com.store.score.model.response.MapResModel;@ResponseBody @ControllerAdvice("com.store.score.rpc.web") public class ApiExceptionHandler {private static final Logger LOGGER = LoggerFactory.getLogger(ApiExceptionHandler.class);/*** @param exception UnexpectedTypeException* @param response* @return*/@ResponseStatus(HttpStatus.BAD_REQUEST)@ExceptionHandler(UnexpectedTypeException.class)public MapResModel unexpectedType(UnexpectedTypeException exception, HttpServletResponse response){MapResModel mapResModel = new MapResModel();LOGGER.error("校驗方法太多,不確定合適的校驗方法。", exception);mapResModel.failure("校驗方法太多,不確定合適的校驗方法。");return mapResModel;}@ResponseStatus(HttpStatus.BAD_REQUEST)@ExceptionHandler(HttpMessageNotReadableException.class)public MapResModel messageNotReadable(HttpMessageNotReadableException exception, HttpServletResponse response){MapResModel mapResModel = new MapResModel();LOGGER.error("請求參數不匹配。", exception);mapResModel.failure("請求參數不匹配:"+exception.getMessage());return mapResModel;}@ResponseStatus(HttpStatus.BAD_REQUEST)@ExceptionHandler(Exception.class)public MapResModel ex(MethodArgumentNotValidException exception, HttpServletResponse response){MapResModel mapResModel = new MapResModel();LOGGER.error("請求參數不合法。", exception);Map<String, String> map = getErrors(exception.getBindingResult());mapResModel.setData(map);mapResModel.failure("請求參數不合法。");return mapResModel;}private Map<String, String> getErrors(BindingResult result) {Map<String, String> map = new HashMap<>();List<FieldError> list = result.getFieldErrors();for (FieldError error : list) {map.put(error.getField(), error.getDefaultMessage());}return map;} }?
轉載于:https://my.oschina.net/u/3768722/blog/1924956
總結
以上是生活随笔為你收集整理的2,Spring-mvc添加参数校验:避免参数格式不正确导致的400的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Vue开发规范1.0
- 下一篇: PHP安装zip拓展,以及libzip安