【问题标题】:Validate request parameter Date in spring rest controller在spring rest控制器中验证请求参数日期
【发布时间】:2018-03-23 08:35:38
【问题描述】:

我想验证日期作为请求参数。

我的端点网址是这样的

http://localhost:8080/api/get/getCurrencyRate?date=02-20-2017

控制器:

@RequestMapping(value = "/getCurrencyRate", produces={"application/json"}, 
method = RequestMethod.GET)
public CurrenctRate getCurrencyrate(@RequestHeader ("Authorization") String 
authorization, @RequestParam(value="date") @DateTimeFormat(pattern="MM-dd-
yyyy") @Valid Date date) throws Exception {

对于上述输入 (02-20-2017),服务工作正常。我想验证请求参数向用户发送适当的响应。我该怎么做。

例如 如果请求是这样的

http://localhost:8080/api/get/getCurrencyRate?date=02/20/2017

回复应为“请以“MM-DD-YYYY”格式输入日期”

而现在我得到了

Error code **400**
<b>JBWEB000069: description</b>
        <u>JBWEB000120: 

 - The request sent by the client was syntactically incorrect.

</u>

请指教。

【问题讨论】:

  • 您是否尝试将请求记录到控制台?
  • 这很明显。您的日期模式与您的日期请求不匹配,因此它将返回 HTTP 400 状态代码。

标签: java date spring-mvc spring-restcontroller jackson2


【解决方案1】:

我能想到的最佳解决方案是为所有类型的日期格式提供方法,但形成路径,或使用路径参数,如下所示:

//Using Path
@RequestMapping(value = "/getCurrencyRate/{date}", produces={"application/json"}, method = RequestMethod.GET)
public CurrenctRate getCurrencyRateOfDate(@RequestHeader ("Authorization") String authorization, @PathVariable("date") @DateTimeFormat(pattern="MM/dd/yyyy") @Valid Date date) throws Exception {

或者,带有请求参数

//Using Request Parameter
@RequestMapping(value = "/getCurrencyRate", produces={"application/json"}, method = RequestMethod.GET)
public CurrenctRate getCurrencyrate(@RequestHeader ("Authorization") String authorization, @RequestParam(value="date") @DateTimeFormat(pattern="MM/dd/yyyy") @Valid Date date) throws Exception {

这样,Spring REST 可以将您的请求与您的 API 调用相匹配。

【讨论】:

  • 我想为除 MM-dd-yyyy 和无效日期之外的其他日期格式发送自定义响应。我该怎么做.. 我在日志中输入无效日期格式的异常是“MethodArgumentTypeMismatchException”。
【解决方案2】:

您必须使用@ControllerAdvice,为MethodArgumentTypeMismatchException 异常类型创建异常处理程序,并为您需要作为响应发送给客户端的正确异常类创建类。例如,

我有 @ControllerAdviceRestErrorHandler 和下面的异常处理程序 HttpMessageNotReadableException 异常。

@ExceptionHandler(HttpMessageNotReadableException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ResponseBody
    public ResponseEntity<ValidationErrorDTO> processValidationIllegalError(HttpMessageNotReadableException ex,
            HandlerMethod handlerMethod, WebRequest webRequest) {

        Throwable throwable = ex.getMostSpecificCause();
        ValidationErrorDTO errorDTO = new ValidationErrorDTO();
        if (throwable instanceof EnumValidationException) {

            EnumValidationException exception = (EnumValidationException) ex.getMostSpecificCause();

            errorDTO.setEnumName(exception.getEnumName());
            errorDTO.setEnumValue(exception.getEnumValue());
            errorDTO.setErrorMessage(exception.getEnumValue() + " is an invalid " + exception.getEnumName());
        }

        return new ResponseEntity<ValidationErrorDTO>(errorDTO, HttpStatus.BAD_REQUEST);
    }

【讨论】:

    【解决方案3】:

    我创建了自定义异常处理程序,使用 @ControllerAdvice 扩展了 ResponseEntityExceptionHandler。我覆盖的地方 handleTypeMismatch(TypeMismatchException ex,HttpHeaders 标头,HttpStatus 状态,WebRequest 请求)。通过这种方式,我创建了处理异常并创建了自己的响应。

    请参考以下:

    @Override
    protected ResponseEntity<Object> handleTypeMismatch(TypeMismatchException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
        char quotes='"';
        String error ="Invalid date "+ quotes+ ex.getValue()+quotes +".. Please enter date in  MM/dd/YYYY.";
        err (error);
        CustomException customExcepton = new CustomException (HttpStatus.BAD_REQUEST, "101", ex.getLocalizedMessage(), error);
        return new ResponseEntity <Object> (customExcepton, new HttpHeaders(), customExcepton.getStatus());
    
    }
    

    我的 CustomException 类是:

    @JsonInclude(Include.NON_NULL) 公共类 CustomException 实现 Serializable {

    private static final long serialVersionUID = -6839345326601547899L;
    
    private HttpStatus status;
    
    private String exceptionCode;
    
    private String exceptionMessage;
    
    private List <String> errors = null;
    
    public CustomException() {
        // Default
    }
    public CustomException (HttpStatus status, String exceptionCode, String exceptionMessage, String error) {
        super();
        this.status = status;
        this.exceptionCode = exceptionCode;
        this.exceptionMessage = exceptionMessage;
        this.errors = Arrays.asList (error);
    }
    

    //getter 和 setter

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-26
      • 2020-11-16
      • 1970-01-01
      • 2016-10-24
      • 2013-02-16
      • 2015-06-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多