将 JAX-RS bean 验证错误消息绑定到视图 [英] Binding JAX-RS bean validation error messages to the view

查看:34
本文介绍了将 JAX-RS bean 验证错误消息绑定到视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们可以使用 bean 验证轻松验证 JAX-RS 资源类字段或方法参数,如下所示:

We can easily validate a JAX-RS resource class field or method parameter using bean validation something like the following:

@Size(min = 18, max = 80, message = "Age 必须在 {min} 和 {max} 之间.") String age;

@Size(min = 18, max = 80, message = "Age must be between {min} and {max}.") String age;

将错误消息绑定到 JSP 页面的最简单方法是什么?

What is the easiest way to bind the error message to a JSP page?

(比如说,我正在使用带有 Jersey 或 Resteasy 的 Java EE 7)

(Say, I am using Java EE 7 with Jersey or Resteasy)

推荐答案

EDIT 1

我们在 @ErrorTemplate 中引入了新注释涵盖此用例的 Jersey 2.3.处理 JAX-RS 和 Bean 验证错误MVC 更深入地描述了它并展示了如何使用它.

We introduced new annotation @ErrorTemplate in Jersey 2.3 that covers this use-case. Handling JAX-RS and Bean Validation Errors with MVC describes it deeper and shows how to use it.

使用 Jersey,您可以按照以下步骤操作:

With Jersey you can follow these steps:

  1. 添加以下依赖项:jersey-bean-validationjersey-mvc-jsp
  2. ExceptionMapper 创建一个 ExceptionMapperhttp://docs.jboss.org/hibernate/beanvalidation/spec/1.1/api/javax/validation/ConstraintViolationException.html">ConstraintViolationException
  3. 注册您的提供商
  1. add the following dependencies: jersey-bean-validation and jersey-mvc-jsp
  2. create an ExceptionMapper for ConstraintViolationException
  3. register your providers

依赖关系

如果您使用的是 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球衣豆验证).

otherwise refer to the modules dependency pages to get a list of required libraries (jersey-mvc-jsp and jersey-bean-validation).

当验证实体(或 JAX-RS 资源)期间出现问题时,Bean 验证运行时会引发 ConstraintViolationException.Jersey 2.x 提供了一个标准的 ExceptionMapper 来处理此类异常(准确地说是 ValidationException),因此如果您想以不同的方式处理它们,则需要编写自己的 ExceptionMapper:

Bean Validation runtime throws a ConstraintViolationException when something goes wrong during validation an entity (or JAX-RS resource). Jersey 2.x provides a standard ExceptionMapper to handle such exceptions (ValidationException to be precise) so if you want to handle them differently, you need to write an ExceptionMapper of your own:

@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 将用于渲染的模型(模型可以通过 ${it} 属性).有关此主题的更多信息,请参阅 Jersey 用户指南中有关 MVC 的部分.

With the ExceptionMapper above you'll be handling all thrown ConstraintViolationExceptions and the final response will have HTTP 400 response status. Entity passed (Viewable) to the response will be processed by MessageBodyWriter from jersey-mvc module and it will basically output a processed JSP page. The first parameter of the Viewable class is a path to a JSP page (you can use relative or absolute path), the second is the model the JSP will use for rendering (the model is accessible via ${it} attribute in JSP). For more on this topic, refer to the section about MVC in Jersey Users guide.

您需要做的最后一步是将您的提供程序注册到您的 应用程序(我将向您展示一个使用 ResourceConfig 的示例 来自 Jersey,它扩展了 Application 类):

The last step you need to make is to register your providers into your Application (I'll show you an example using ResourceConfig from Jersey which extends Application class):

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);

这篇关于将 JAX-RS bean 验证错误消息绑定到视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆