【问题标题】:Get and set value of session获取和设置会话值
【发布时间】:2019-05-11 08:42:46
【问题描述】:

在 java 中,尤其是 spring boot 中,如何通过使用 RestTemplate 调用 Api 从域 B 获取或设置域 A 的会话值?

域 B 中的示例我使用 RestTemplate postForObject 从域 demo2.com 调用 Api:

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);
}

在 demo2.com,这是我的 Api。但是当我打印 demo2.com 的会话属性 userIdaccess-token 的值时,它总是显示为空。

@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);
}

【问题讨论】:

    标签: java spring spring-boot servlets resttemplate


    【解决方案1】:

    虽然我从未在 RestTemplate 中使用过 postForObject 方法,但我可以在他们的文档 (https://www.baeldung.com/rest-template) 中看到您必须将 Post 参数包装在 HttpEntity 对象中。

    因此,在你的位置上,我会按照他们的建议尝试,

    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);
    

    但是,postForObject 用于创建一个 Resource,然后将其返回。如果您想提交带有您将根据需要指定和命名的 Post 参数的表单,那么您必须按照我上面粘贴的链接中的 4.4,

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

    这样,如果你为 userId 包含一个键值对,你就可以在 demo2.com 中获取它

    【讨论】:

      猜你喜欢
      • 2020-04-01
      • 1970-01-01
      • 2014-07-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-21
      • 1970-01-01
      相关资源
      最近更新 更多