我想验证请求参数。我已经浏览了许多博客并回答并做了同样的事情。 在控制器类上添加了@Validated。
控制器中的方法:
public ResponseEntity<Employee> getHistory(
@Valid @Pattern(regexp = "^[A-Z]{2}[0-9]{6}[A-Z]{0,1}$", message = "Invalid
emp") @NotNull(message = "input cannot be null") @RequestParam(name = "emp")
String emp) { method body..........}
控制器建议
@ExceptionHandler(value = {ConstraintViolationException.class})
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
public String handleValidationFailure(ConstraintViolationException ex) {
StringBuilder messages = new StringBuilder();
for (ConstraintViolation<?> violation : ex.getConstraintViolations()) {
messages.append(violation.getMessage() + "\n");
}
return messages.toString();
}
配置:
@Bean
public MethodValidationPostProcessor methodValidationPostProcessor() {
return new MethodValidationPostProcessor();
}
完成所有这些后,我收到404错误。 “status”:404,“error”:“Not Found”,“message”:“没有可用消息”
答案 0 :(得分:1)
您在控制器建议中的方法上缺少@ResponseBody注释。它会导致错误,因为Spring正在尝试找到名称从此方法返回为String
的模板,因此在REST调用期间,您会得到如下内容:
{
"error": "Not Found",
"exception": "javax.validation.ConstraintViolationException",
"message": "No message available",
"path": "/history",
"status": 404,
"timestamp": 1502293311543
}
向@ResponseBody
方法添加handleValidationFailure(ConstraintViolationException ex)
注释意味着当您返回String时,它不是模板名称,而是响应对象本身。
或者,您可以在建议方法中使用ResponseEntity<String>
作为返回类型,例如
@ExceptionHandler(value = {ConstraintViolationException.class})
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
public ResponseEntity<String> handleValidationFailure(ConstraintViolationException ex) {
StringBuilder messages = new StringBuilder();
for (ConstraintViolation<?> violation : ex.getConstraintViolations()) {
messages.append(violation.getMessage());
}
return ResponseEntity.badRequest().body(messages.toString());
}
因此您不必使用@ResponseBody
注释方法,而Spring现在将您的响应不是视图名称而是响应正文本身。我希望它有所帮助。
我假设您正在调用不正确的端点。我创建了一个小的Spring Boot应用程序,它使用提供的信息复制您的问题:
随意克隆并运行它。运行后,您可以尝试使用:
调用/history
端点
curl "localhost:8080/history?emp=AZ000001A"
它将显示为:
{"id":"AZ000001A","name":"Joe Doe"}%
如果您使用违反验证规则的emp
来调用此终结点:
curl "localhost:8080/history?emp=sd"
您将得到以下回复:
{"message":"Your request contains errors","errors":[{"getHistory.arg0":"Invalid emp"}]}
我的假设是,在您的情况下,您正在错误地调用您的端点。使用@RestController
注释时存在流行的误解。我看到人们像@RestController("/someRootPath")
一样使用它,然后他们希望有像
localhost:8080/someRootPath/...
这是不正确的。传递给@RestController
注释的值只不过是:
该值可能表示对逻辑组件名称的建议,如果是自动检测组件,则将其转换为Spring bean。
您始终可以查看控制台日志以查看控制器的最终映射,例如
2017-08-09 20:40:45.663 INFO 1340 --- [ main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@6385cb26: startup date [Wed Aug 09 20:40:44 CEST 2017]; root of context hierarchy
2017-08-09 20:40:45.696 INFO 1340 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/history],methods=[GET]}" onto public org.springframework.http.ResponseEntity<com.github.wololock.restvalidationdemo.Employee> com.github.wololock.restvalidationdemo.EmployeeController.getHistory(java.lang.String)
2017-08-09 20:40:45.698 INFO 1340 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2017-08-09 20:40:45.698 INFO 1340 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2017-08-09 20:40:45.708 INFO 1340 --- [ main] o.s.w.s.h.BeanNameUrlHandlerMapping : Mapped URL path [/employee] onto handler '/employee'
2017-08-09 20:40:45.714 INFO 1340 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-08-09 20:40:45.714 INFO 1340 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
我希望它有所帮助。