Java Spring REST 调用参数

标签 java spring

假设有一个以下 Java 文件 Foo.java:

public class Foo {
     private String first;
     private String second;
     private String third;

     public Foo(){
     }
     public Foo(String first, String second, String third){
          this.first = first;
          this.second = second;
          this.third = third;
     }
     public String getFirst(){
          return first;
     }
     public String getSecond(){
          return second;
     }
     public String getThird(){
          return third;
     }
     public void setFirst(String first){
          this.first = first;
     }
     public void setSecond(String second){
          this.second = second;
     }
     public void setThird(String third){
          this.third = third;
     }
}

然后还有另一个文件,RESTcontroller.java:

import Bar;
import Foo;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/rest")
public class RESTController {
    @RequestMapping(path = "/getFoo", method = RequestMethod.GET)
    public void getFoo(Foo foo, HttpServletResponse response) {
        Bar bar = Bar.getBar(foo)
        ...
    }
}

然后在第三个文件 http.js 中调用“getFoo”端点:

class Http {
    getFoo(url, first, third) {
        return `${url}getFoo?first=${first}&third=${third}`;
    }
}

那么,问题是,当 Foo 构造函数中缺少第二个参数时,如何使用查询参数来构造 Foo 参数?在什么时候使用这两个构造函数中的哪一个?这和Spring框架有关系吗?这里的示例代码是已经被证明可以正常工作的代码版本。

最佳答案

这一切都与Spring有关(或更准确地说Spring隐藏的配置魔法)。

org.springframework.web.method.support.HandlerMethodArgumentResolver解析的运行时实现是负责将请求参数转换为对象的组件,这个过程称为参数映射。

在所描述的示例中,解析器将使用无参数构造函数以及setter> 保存接收到的参数名称,即 setFirst 和 setThird

永远不会调用 3 个参数的构造函数,您的 POJO 需要实现的只是一个标准的无参构造函数以及实例变量的 setter 和 getter。

关于Java Spring REST 调用参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58284102/

相关文章:

JavaFx:如何实现动态 Gridpane?

java - 如何保持指定的 HTML 标签

java - 如何在设备旋转时旋转背景图像?

java - Java中final字段的继承?

java - 如何在 mapstruct 中使用来自不同类的另一个映射

java - 如何从旧版本的 spring mvc 3.0.5 使用/集成 spring security

java - Spring MVC注解@ModelAttribute

Spring、JPA 事务仅在 JUnit 测试中有效,但在应用程序中无效

spring - 使用 oauth2 范围而不是角色来保护 spring 执行器管理端点

java - 无法导入 springframework.security.extensions 并找到 saml() 方法