EDIT 1
我们引入了新的注释@错误模板Jersey 2.3 中涵盖了这个用例。使用 MVC 处理 JAX-RS 和 Bean 验证错误更深入地描述它并展示如何使用它。
使用 Jersey,您可以按照以下步骤操作:
- 添加以下依赖项:
jersey-bean-validation
and jersey-mvc-jsp
- 创建一个异常映射器 for 约束违反异常
- 注册您的提供商
依赖关系
如果您使用 Maven,您只需将这些依赖项添加到您的pom.xml
<dependency>
<groupId>org.glassfish.jersey.ext</groupId>
<artifactId>jersey-mvc-jsp</artifactId>
<version>2.1</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.ext</groupId>
<artifactId>jersey-bean-validation</artifactId>
<version>2.1</version>
</dependency>
否则请参阅模块依赖项页面以获取所需库的列表(球衣-MVC-jsp and 泽西岛 bean 验证).
异常映射器
当验证实体(或 JAX-RS 资源)期间出现问题时,Bean Validation 运行时会抛出 ConstraintViolationException。 Jersey 2.x提供了一个标准的ExceptionMapper来处理此类异常(ValidationException
准确地说)所以如果你想以不同的方式处理它们,你需要编写自己的 ExceptionMapper:
@Provider
@Priority(Priorities.USER)
public class ConstraintViolationExceptionMapper implements ExceptionMapper<ConstraintViolationException> {
@Override
public Response toResponse(final ConstraintViolationException exception) {
return Response
// Define your own status.
.status(400)
// Put an instance of Viewable in the response so that jersey-mvc-jsp can handle it.
.entity(new Viewable("/error.jsp", exception))
.build();
}
}
使用上面的 ExceptionMapper,您将处理所有抛出的 ConstraintViolationException,最终响应将具有HTTP 400
响应状态。实体通过(Viewable) 的响应将由 MessageBodyWriter 处理jersey-mvc
模块,它基本上会输出一个处理过的 JSP 页面。 Viewable 类的第一个参数是 JSP 页面的路径(可以使用相对或绝对路径),第二个参数是 JSP 将用于渲染的模型(该模型可通过${it}
JSP 中的属性)。有关此主题的更多信息,请参阅有关MVC在泽西岛用户指南中。
注册提供商
您需要做的最后一步是将您的提供商注册到您的应用(我将向您展示一个使用的示例资源配置来自 Jersey,它扩展了应用程序类):
new ResourceConfig()
// Look for JAX-RS reosurces and providers.
.package("my.package")
// Register Jersey MVC JSP processor.
.register(JspMvcFeature.class)
// Register your custom ExceptionMapper.
.register(ConstraintViolationExceptionMapper.class)
// Register Bean Validation (this is optional as BV is automatically registered when jersey-bean-validation is on the classpath but it's good to know it's happening).
.register(ValidationFeature.class);