Java Spring REST调用参数
假设有一个Java文件Foo。爪哇:
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。爪哇:
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框架有关吗?这里的示例代码是一个已被证明有效的代码版本
# 1 楼答案
你把rest搞错了——使用GET-rest方法不是用来构造一个对象,而是简单地从服务/db中检索它
在这种情况下,可以使用的查询参数将决定返回哪些对象(通过其id或其他参数)。您不需要将foo对象传递给该方法,因为GET通常没有请求主体
所以get方法看起来像:
为了构造新对象,应该使用POST方法,最好将新对象作为json传递到请求体中。它将作为参数传递给控制器方法:
最后一件事,使用REST时的约定是使用相同的路径,即/foo,REST方法将确定它是创建(POST)、更新(PUT)还是获取(get)。您不需要调用path/getFoo
# 2 楼答案
我不太明白你的意思,但我知道RequestBody是默认的
同样的事情。 比如
# 3 楼答案
这一切都与Spring(或者更准确地说是Spring隐藏配置魔法)有关
由^{} 解析的运行时实现是负责将请求参数转换为对象的组件,这个过程称为参数映射
在所描述的示例中,解析程序将使用的是无参数构造函数,以及保存所接收参数名称的设置器,即设置第一和设置第三
3 arg构造函数永远不会被调用,而您的POJO需要实现的只是一个标准的无参数构造函数以及实例变量的setter和getter