如何将响应变量建模为来自后端的响应

时间:2019-07-13 19:41:23

标签: java spring spring-boot spring-annotations

在以下示例中,我正在尝试发帖和获取请求。 POST请求已正确执行。对于GET请求,我期望得到2121。 但实际上,我什么也没得到,这意味着“ this.str”未设置为2121

有什么方法可以将变量建模为json吗?通常,如果响应是一个对象,它将被建模为json并因此建模为模型类。 在下面的情况下,响应是变量

有什么理由将一个可变对象建模为json对象

Controller1

@Controller
@ResponseBody
@RequestMapping("/call1")
public class Call1 {

public String str = "inti";

@RequestMapping(value = "/initparam1", method = RequestMethod.POST)
public void initparam1(@RequestBody(required = false) String val) {
    this.str = val;
}

@RequestMapping("/getparam1")
public String getParam1() {
    return this.str;
}
}

post_request_postman

http://localhost:8085/call1/initparam1?val=2121
executed correctly

get_request_postman

http://localhost:8085/call1/getparam1   
result:does not return the value set to str which is 2121

4 个答案:

答案 0 :(得分:0)

您尝试过吗:

render this.str;

而不是:

return this.str;

还用@ResponseBody注释您的方法

答案 1 :(得分:0)

第一步错了。

POST至http://localhost:8085/call1/initparam1?val=2121的意思是“将正文发送到url initparam1?val = 2121”-就是和url,就像initparam1_val_2121一样。

我想,您向该url发送了一个空的正文-因此将空字符串设置为this.str,此字符串随后从GET中返回。

或通过curl检查POST:

# correct
curl -d "val=2121" -X POST http://localhost:8085/call1/initparam1

# your case, incorrect
curl -d "" -X POST http://localhost:8085/call1/initparam1?val=2121

答案 2 :(得分:0)

您做错了两件事。

1。首先,发布请求(/ initparam1)接受“ val”作为json主体,但是您将其作为查询参数传递,您可能想解决这个问题。

  1. 第二,REST是无状态的,因此“ str”变量的值无法通过第二个请求进行检索,除非将其保留在某个地方以供以后检索。

答案 3 :(得分:0)

您错过了控制器是线程安全的想法,即每个请求都绑定到一个线程,该线程具有自己的控制器类数据副本 因此,当您在另一线程上进行/post str更新时,在进行/get时,您将获得str的新副本,因为您将使用新线程。

更多详细信息,请参见此答案 https://stackoverflow.com/a/16795572/1460591