Java 验证spring rest控制器中的请求参数日期
我想将日期验证为请求参数 我的端点url类似于 控制器:Java 验证spring rest控制器中的请求参数日期,java,date,spring-mvc,spring-restcontroller,jackson2,Java,Date,Spring Mvc,Spring Restcontroller,Jackson2,我想将日期验证为请求参数 我的端点url类似于 控制器: @RequestMapping(value = "/getCurrencyRate", produces={"application/json"}, method = RequestMethod.GET) public CurrenctRate getCurrencyrate(@RequestHeader ("Authorization") String authorization, @RequestParam(value="dat
@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 {
对于上述输入(2017年2月20日),服务工作正常。我想验证请求参数,并向用户发送适当的响应。我该怎么做呢
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>
错误代码**400**
JBWEB000069:说明
JBWEB000120:
-客户端发送的请求在语法上不正确。
请给出建议。我能想到的最佳解决方案是为所有类型的日期格式提供方法,但不包括路径,或者使用路径参数,如下所示:
//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调用相匹配。您必须使用
@ControllerAdvice
,为MethodArgumentTypeMismatchException
异常类型创建异常处理程序,并为您需要作为响应发送给客户端的适当异常类创建类。比如说,
我有@ControllerAdvice
类RestErrorHandler
,其中包含httpmessageradableexception
异常的以下异常处理程序
@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);
}
@ExceptionHandler(httpmessagegenoteradableexception.class)
@ResponseStatus(HttpStatus.BAD_请求)
@应答器
公共响应性流程ValidationIllegaError(HttpMessageEndableException ex,
HandlerMethod HandlerMethod,WebRequest WebRequest){
Throwable-Throwable=例如getmostsspecificcause();
ValidationErrorDTO errorDTO=新建ValidationErrorDTO();
if(EnumValidationException的可丢弃实例){
EnumValidationException异常=(EnumValidationException)例如GetMostSpecificCase();
errorDTO.setEnumName(exception.getEnumName());
errorDTO.setEnumValue(exception.getEnumValue());
errorDTO.setErrorMessage(exception.getEnumValue()+”是无效的“+exception.getEnumName());
}
返回新的响应状态(errorDTO,HttpStatus.BAD_请求);
}
ValidationErrorTo
是一个具有少量setter/getter的类,当发生HttpMessageNodeEnableException
异常时,在响应中发送ValidationErrorTo
,并发送我希望客户端看到的消息。我创建了自定义异常处理程序,用@控制员建议。我在哪里超越
HandleTypeMitch(TypeMitchException 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());
}
@覆盖
受保护的ResponseEntity HandletTypeMitch(TypeMitchException ex、HttpHeaders标头、HttpStatus状态、WebRequest请求){
字符引号=“”;
字符串错误=“无效日期”+引号+ex.getValue()+引号+”。请以MM/dd/YYYY格式输入日期。“;
错误;
CustomException customExcepton=新的CustomException(HttpStatus.BAD_请求,“101”,例如getLocalizedMessage(),错误);
返回新的ResponseEntity(customExcepton,new HttpHeaders(),customExcepton.getStatus());
}
我的CustomException类是:
@JsonInclude(Include.NON_NULL)
公共类CustomException实现可序列化{
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);
}
private static final long serialVersionUID=-6839345326601547899L;
私有http状态;
私有字符串例外代码;
私有字符串例外消息;
私有列表错误=null;
公共自定义例外(){
//违约
}
公共自定义异常(HttpStatus状态、字符串异常代码、字符串异常消息、字符串错误){
超级();
这个状态=状态;
this.exceptionCode=exceptionCode;
this.exceptionMessage=exceptionMessage;
this.errors=Arrays.asList(错误);
}
//getter和setters您是否尝试将请求记录到控制台?这很明显。您的日期模式与您的日期请求不匹配,因此它将返回HTTP 400状态码。我想发送除MM dd yyyy和无效日期之外的其他日期格式的自定义响应。我如何做到这一点..我在日志中遇到的异常是invalid日期格式为“MethodArgumentTypeMismatchException”。