0

in the below example, i am trying make post and get requests. the POST request was executed correctly. For the GET request, i exepected to get 2121. but actually, i get nothing which means "this.str" was not set to 2121

is there any way to model a variable to json? normally if the response is an object it will be modelled to json and consequently to the model class. int he below case, the response is a varibale

is there any why to model a vraible as json object

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
Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Amrmsmb
  • 1
  • 27
  • 104
  • 226

4 Answers4

0

Have you tried:

render this.str;

instead of:

return this.str;

?

Also annotate your method with @ResponseBody

SaltyTeemooo
  • 113
  • 1
  • 7
  • thanyks for the answer.render is not recognized and i added the @ResponseBody but still nothing work – Amrmsmb Jul 13 '19 at 19:50
0

You are wrong at first step.

POST to http://localhost:8085/call1/initparam1?val=2121 means 'send body to url initparam1?val=2121' - it's just and url, the same like initparam1_val_2121.

I guess, to this url you send an empty body - so empty string is set to this.str, which later is returned from GET.

Or check POST by curl:

# 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
Bor Laze
  • 2,458
  • 12
  • 20
  • thx i dont know how to use curl, i am using postman and it does not use curt. can u please coorect my request http://localhost:8085/call1/initparam1?val=2121 – Amrmsmb Jul 14 '19 at 05:02
0

You are doing two things wrongly.

1.Firstly the post request (/initparam1) accepts "val" as a json body but u are passing it as a query parameter u may want to fix that.

  1. Secondly, REST is stateless therefore the value of "str" variable cannot be retrieve via a second request unless it is persisted somewhere for retrieval later.
morrisng
  • 127
  • 7
0

You miss the idea that controllers are thread safe means each request is bound to a thread which has his own data copy of the controller class So when you do /post str was updated on a different thread, when doing /get you will have a fresh copy of str since you are taking to a new thread.

more details see this answer https://stackoverflow.com/a/16795572/1460591

Youans
  • 4,801
  • 1
  • 31
  • 57