我们可以使用 bean 验证轻松验证 JAX-RS 资源类字段或方法参数,如下所示:
@Size(min = 18, max = 80, message = "Age 必须在 {min} 和 {max} 之间。") String age;
将错误消息绑定(bind)到 JSP 页面的最简单方法是什么?
(比如说,我正在使用带有 Jersey 或 Resteasy 的 Java EE 7)
最佳答案
编辑 1
我们引入了新的注释 @ErrorTemplate在涵盖此用例的 Jersey 2.3 中。 Handling JAX-RS and Bean Validation Errors with MVC更深入地描述它并展示如何使用它。
使用 Jersey ,您可以按照以下步骤操作:
jersey-bean-validation
和 jersey-mvc-jsp
依赖项
如果您使用 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}
属性访问)。有关此主题的更多信息,请参阅有关 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);
关于jakarta-ee - 将 JAX-RS bean 验证错误消息绑定(bind)到 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18015630/