编辑 1
我们在 Jersey 2.3 中引入了新的注释 @ErrorTemplate,涵盖了这个用例。 Handling JAX-RS and Bean Validation Errors with MVC 更深入地描述了它并展示了如何使用它。
使用 Jersey,您可以按照以下步骤操作:
- 添加以下依赖项:
jersey-bean-validation 和 jersey-mvc-jsp
- 为ConstraintViolationException 创建一个ExceptionMapper
- 注册您的提供商
依赖关系
如果您使用 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>
否则,请参阅模块依赖页面以获取所需库的列表(jersey-mvc-jsp 和 jersey-bean-validation)。
异常映射器
当验证实体(或 JAX-RS 资源)期间出现问题时,Bean 验证运行时会引发 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,您将处理所有抛出的 ConstraintViolationExceptions,最终响应将具有 HTTP 400 响应状态。传递给响应的实体(Viewable)将由来自jersey-mvc 模块的 MessageBodyWriter 处理,它基本上会输出一个处理后的 JSP 页面。 Viewable 类的第一个参数是 JSP 页面的路径(可以使用相对路径或绝对路径),第二个参数是 JSP 将用于呈现的模型(该模型可通过 JSP 中的${it} 属性访问)。有关此主题的更多信息,请参阅 Jersey 用户指南中有关 MVC 的部分。
注册提供者
您需要做的最后一步是将您的提供程序注册到您的Application(我将向您展示一个使用来自 Jersey 的 ResourceConfig 扩展 Application 类的示例):
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);