Search code examples
javaspringspring-bootservletsresttemplate

Get and set value of session


In java, especially spring boot how can i get or set the value of session of domain A from domain B by call Api using RestTemplate?

Example in Domain B I used RestTemplate postForObject to call Api from domain demo2.com:

public ResponseEntity<String> doLogout(@RequestBody String userId){
    System.out.println("123" + userId);
    RestTemplate rest = new RestTemplate();
    for(String s : listUrl) {
        System.out.println("url: " + s);
        rest.postForObject("http://demo2.com"+"/doLogout", userId, String.class);
    }
    return new ResponseEntity<String>(HttpStatus.OK);
}

In demo2.com, here is my Api. But when i printed the value of session attribute userId and access-token of demo2.com it always show null.

@RequestMapping(value = "/doLogout", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<String> doLogout(HttpServletRequest request, @RequestBody String userId){
    System.out.println("abc" + SessionUtil.getAttribute(request, "access-token") + SessionUtil.getAttribute(request, "userId"));
    if(userId.equals(SessionUtil.getAttribute(request, "userId"))) {
        System.out.println("vao day");
        SessionUtil.setAtribute(request, "access-token", null);
    }
    return new ResponseEntity<String>(HttpStatus.OK);
}

Solution

  • Although I have never used postForObject method with the RestTemplate, I can see in their documentation (https://www.baeldung.com/rest-template) that you have to wrap your Post Parameter in a HttpEntity object.

    Therefore, in your place, I would try as they suggest,

    ClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
    RestTemplate restTemplate = new RestTemplate(requestFactory);
    
    HttpEntity<String> request = new HttpEntity<>(new String("<user_id_value>"));
    String userId = restTemplate.postForObject("http://demo2.com"+"/doLogout", request, String.class);
    System.out.println("User ID : " + userId);
    

    However, postForObject is used to create a Resource that will then be returned. If you want to submit a form with Post Parameters that you will specify and name as desired, then you have to follow 4.4 from the link I pasted above,

    https://www.baeldung.com/rest-template

    In this way, if you include a key-value pair for userId, you will be able to fetch it in demo2.com