【问题标题】:Jersey Bean Validation interpreting application/x-www-form-urlencoded as a beanJersey Bean Validation 将 application/x-www-form-urlencoded 解释为 bean
【发布时间】:2015-12-13 14:15:36
【问题描述】:

我正在使用 Jersey RESTful Web 服务框架开发 REST 服务。

需要使用 url 编码的表单内容类型并将其解释/验证为 bean。

@POST @Path("put")
@Consumes("application/x-www-form-urlencoded")
@NotNull (message="Couldn't put this bean in the can, sorry")
public Response putABean( @Valid final MrBean bean ){ ... }

@XmlRootElement
public class MrBean {

@DecimalMin(value = "18" , message= "value must be at least 18")
@DecimalMax(value = "99" , message= "value must at most be 99")
@NotNull(message = "{null.generic}")
private Long age;

@NotNull(message = "{null.name.first}")
private String firstName;

@NotNull(message = "{null.name.last}")
private String lastName;

@Pattern(regexp="[0-9]{3,9}", message="{invalid.phone}")
@NotNull(message = "{null.generic}")
private String phone;

...

}

当资源使用 application/json 或 application/xml 时,这是可能的,但在 application/x-www-form-urlencoded 的情况下,我会收到“415 - Unsupported Media Type”响应。

我的理解是,这不受开箱即用的支持,并且需要注册一个类似于此处完成方式的功能: https://jersey.java.net/documentation/latest/media.html

【问题讨论】:

    标签: java rest jersey javabeans


    【解决方案1】:

    此错误与 bean 验证无关。首先application/x-www-form-urlencoded 不是MessageBodyReader 用于像MyBean 这样的任意类型。读取可以处理的唯一类型是FormMultivaluedMap。所以只有这两种类型可以作为 body 参数。

    但还有另一种选择。 @BeanParam 注释允许您创建一个 bean 来组合任意 @XxxParam 注释元素,例如 @FormParam@PathParam@QueryParam@HeaderParam 等。所以如果您知道提交表单中的预期键,你可以做类似的事情

    public class MrBean {
    
        // validation annotations
        @FormParam("key1")
        private String value1;
    
        // validation annotations
        @FormParam("key2")
        private String value2;
    
        // getters setters
    }
    

    那你就可以了

    public Response putABean( @Valid @BeanParam MrBean bean ){ ... }
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-09-11
    • 1970-01-01
    • 2019-12-04
    • 2019-10-26
    • 1970-01-01
    • 1970-01-01
    • 2016-04-13
    相关资源
    最近更新 更多