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

发布于 2024-09-01 16:34:53 字数 396 浏览 3 评论 0原文

我想使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

赴月观长安 2024-09-08 16:34:53

例如,我建议使用 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);
}

然后,定义一个 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:

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.

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

尹雨沫 2024-09-08 16:34:53

使用
整数计数。

@FormParam("count")有效的

Use
@FormParam("count") Integer count

that will work.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文