简体   繁体   English

使用JAX-RS进行表单输入验证

[英]Form input validation with JAX-RS

I want to use JAX-RS REST services as a back-end for a web application used directly by humans with browsers. 我想使用JAX-RS REST服务作为人类使用浏览器直接使用的Web应用程序的后端。 Since humans make mistakes from time to time I want to validate the form input and redisplay the form with validation message, if something wrong was entered. 由于人类不时会犯错误,我想验证表单输入并使用验证消息重新显示表单,如果输入错误。 By default JAX-RS sends a 400 or 404 status code if not all or wrong values were send. 默认情况下,如果未发送全部或错误的值,JAX-RS将发送400或404状态代码。

Say for example the user entered a "xyz" in the form field "count": 例如,用户在表单字段“count”中输入了“xyz”:

@POST
public void create(@FormParam("count") int count) {
  ...
}

JAX-RS could not convert "xyz" to int and returns "400 Bad Request". JAX-RS无法将“xyz”转换为int并返回“400 Bad Request”。

How can I tell the user that he entered an illegal value into the field "count"? 如何告诉用户他在字段“count”中输入了非法值? Is there something more convenient than using Strings everywhere and perform conversation by hand? 有什么比在任何地方使用字符串更方便,并手动进行对话?

I would recommend to use AOP, JSR-303, and JAX-RS exception mappers for example: 我建议使用AOP,JSR-303和JAX-RS异常映射器,例如:

import javax.validation.constraints.Pattern;
@POST
public void create(@FormParam("count") @Pattern("\\d+") String arg) {
  int count = Integer.parseInt(arg);
}

Then, define a JAX-RS exception mapper that will catch all ValidationException -s and redirect users to the right location. 然后,定义一个JAX-RS异常映射器,它将捕获所有ValidationException -s并将用户重定向到正确的位置。

I'm using something similar in s3auth.com form validation with JAX-RS: https://github.com/yegor256/s3auth/blob/master/s3auth-rest/src/main/java/com/s3auth/rest/IndexRs.java 我在使用JAX-RS的s3auth.com表单验证中使用类似的东西: https//github.com/yegor256/s3auth/blob/master/s3auth-rest/src/main/java/com/s3auth/rest/IndexRs的.java

Use @FormParam("count") Integer count 使用@FormParam(“count”)整数计数

that will work. 那可行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM