弹簧静止误差处理@ControllerAdvice/@Valid
我在使用@ControllerAdvice时遇到问题,并在REST控制器中一起@Valid注释。
我有一个休息控制器声明如下:
@Controller
public class RestExample {
...
/**
* <XmlRequestUser><username>user1</username><password>password</password><name>Name</name><surname>Surname</surname></XmlRequestUser>
* curl -d "@restAddRequest.xml" -H "Content-Type:text/xml" http://localhost:8080/SpringExamples/servlets/rest/add
*/
@RequestMapping(value="rest/add", method=RequestMethod.POST)
public @ResponseBody String add(@Valid @RequestBody XmlRequestUser xmlUser) {
User user = new User();
user.setUsername(xmlUser.getUsername());
user.setPassword(xmlUser.getPassword());
user.setName(xmlUser.getName());
user.setSurname(xmlUser.getSurname());
// add user to the database
StaticData.users.put(xmlUser.getUsername(), user);
LOG.info("added user " + xmlUser.getUsername());
return "added user " + user.getUsername();
}
}
和一个 ErrorHandler 类:
@ControllerAdvice
public class RestErrorHandler extends ResponseEntityExceptionHandler {
private static Logger LOG = Logger.getLogger(RestErrorHandler.class);
@ExceptionHandler(RuntimeException.class)
public ResponseEntity<Object> handleException(final RuntimeException e, WebRequest request) {
LOG.error(e);
String bodyOfResponse = e.getMessage();
return handleExceptionInternal(e, bodyOfResponse, new HttpHeaders(), HttpStatus.CONFLICT, request);
}
}
问题是,如果我在 RestExample.add 方法中添加一个“throw new RuntimeException”,那么 RestErrorHandler 类会正确处理该异常。
但是,当向控制器提交无效请求时,RestErrorHandler 不会捕获验证程序引发的异常,并且我收到 400 BadRequest 响应。(对于无效请求,我指的是未指定用户名的xml请求)
请注意,XmlRequestUser 类是由插件 maven-jaxb2-plugin + krasa-jaxb-tools (pom.xml) 自动生成的:
<plugin>
<groupId>org.jvnet.jaxb2.maven2</groupId>
<artifactId>maven-jaxb2-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>generate</goal>
</goals>
</execution>
</executions>
<configuration>
<schemaDirectory>src/main/xsd</schemaDirectory>
<schemaIncludes>
<include>*.xsd</include>
</schemaIncludes>
<args>
<arg>-XJsr303Annotations</arg>
<arg>-XJsr303Annotations:targetNamespace=http://www.foo.com/bar</arg>
</args>
<plugins>
<plugin>
<groupId>com.github.krasa</groupId>
<artifactId>krasa-jaxb-tools</artifactId>
<version>${krasa-jaxb-tools.version}</version>
</plugin>
</plugins>
</configuration>
</plugin>
生成的类在“用户名”和“密码”字段上正确@NotNull注释。
我的上下文.xml非常简单,只包含一个控制器扫描仪,并启用mvc:注释驱动
<context:component-scan base-package="com.aa.rest" />
<mvc:annotation-driven />
有没有人知道如何在REST控制器中制作工作@ControllerAdvice和@Valid注释?
提前致谢。安东尼奥