使用 JAX-RS 进行表单输入验证
我想使用 JAX-RS REST 服务作为由浏览器直接使用的 Web 应用程序的后端。由于人类有时会犯错误,因此我想验证表单输入,并在输入错误时重新显示带有验证消息的表单。默认情况下,如果未发送所有值或发送了错误的值,JAX-RS 会发送 400 或 404 状态代码。
例如,假设用户在表单字段“count”中输入了“xyz”:
@POST
public void create(@FormParam("count") int count) {
...
}
JAX-RS 无法将“xyz”转换为 int
并返回“400 Bad Request”。
我如何告诉用户他在“计数”字段中输入了非法值?还有什么比到处使用字符串并手动进行对话更方便的吗?
I want to use JAX-RS REST services as a back-end for a web application used directly by humans with browsers. 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.
Say for example the user entered a "xyz" in the form field "count":
@POST
public void create(@FormParam("count") int count) {
...
}
JAX-RS could not convert "xyz" to int
and returns "400 Bad Request".
How can I tell the user that he entered an illegal value into the field "count"? Is there something more convenient than using Strings everywhere and perform conversation by hand?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
例如,我建议使用 AOP、JSR-303 和 JAX-RS 异常映射器:
然后,定义一个 JAX-RS 异常映射器来捕获所有
ValidationException
-s 并将用户重定向到正确的位置。我在 s3auth.com 表单验证中使用类似的 JAX-RS:https://github.com/yegor256/s3auth /blob/master/s3auth-rest/src/main/java/com/s3auth/rest/IndexRs.java
I would recommend to use AOP, JSR-303, and JAX-RS exception mappers for example:
Then, define a JAX-RS exception mapper that will catch all
ValidationException
-s and redirect users to the right location.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
使用
整数计数。
@FormParam("count")有效的
Use
@FormParam("count") Integer count
that will work.