在弹簧支架控制器中验证请求参数日期

时间:2017-10-11 15:25:13

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

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

我的端点网址就像

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),服务正常。我想验证请求参数向用户发送适当的响应。我怎么能这样做。

e.g。 如果请求是

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>

请建议。

3 个答案:

答案 0 :(得分:0)

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

//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 {

OR,带有请求参数

//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调用相匹配。

答案 1 :(得分:0)

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

我有@ControllerAdvice个分类RestErrorHandler以及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);
    }

ValidationErrorDTO是几乎没有setter / getter的类,当发生HttpMessageNotReadableException异常时,请在响应中发送ValidationErrorDTO,并显示我希望客户端看到的消息。

答案 2 :(得分:0)

我创建了使用@ControllerAdvice扩展ResponseEntityExceptionHandler的自定义异常处理程序。在哪里我覆盖 handleTypeMismatch(TypeMismatchException ex,HttpHeaders headers,HttpStatus status,WebRequest request)。这种方式我创建了处理异常并创建了我自己的响应。

请参阅以下内容:

@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);
}

// getters and setters