【问题标题】:Design a restful url to validate the object设计一个restful url来验证对象
【发布时间】:2015-10-14 09:07:52
【问题描述】:

是否可以从restful URL填充spring MVC中的java对象。

为了澄清,我可以做一个像这样的网址吗 本地主机:8080/user/email/a@a.com/password/aaa 哪个将填充用户对象的电子邮件和密码字段并返回给我用户?

@RequestMapping(value = "user/email/{email}/password/{password}", method = RequestMethod.POST)
    public ResponseEntity<Users> createNewUserRegistration(@Valid User user) {

}

【问题讨论】:

  • 可能不会,但您始终可以手动完成

标签: java validation spring-mvc restful-url


【解决方案1】:
public ResponseEntity<Users> createNewUserRegistration(@PathVariable("email")String email,@PathVariable("password")String password) {
User user = new User(email,password);
//do validation etc
return user;
}

【讨论】:

  • 有很多手动的方法来做验证,我问的是使用@valid的Spring MVC验证。有几种方法,比如通过 rest api 发布 json,我一直在避免。
  • 对我来说,使用电子邮件作为路径参数不是一个好习惯。您可以在方法中的任何地方使用@Valid。您可以与@RequestBody@RequestParam 等一起使用
【解决方案2】:

好的,最后它对我有用。您需要将其添加到您的 pom.xml 中

<dependency>
    <groupId>org.codehaus.jackson</groupId>
    <artifactId>jackson-mapper-asl</artifactId>
    <version>1.9.12</version>
</dependency>

@RequestMapping(value = "user", method = RequestMethod.POST)
    public ResponseEntity<Users> createNewUserRegistration(@RequestBody @Valid User user) {

}

并在请求正文中传递 json

{
    "emailAddress":"email",
    "password":"password"
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-18
    • 1970-01-01
    • 2014-11-15
    • 1970-01-01
    • 2018-02-11
    • 1970-01-01
    • 1970-01-01
    • 2012-06-04
    相关资源
    最近更新 更多