Spring Boot 如何从请求头中获取user_id,而不是将其作为请求参数传递,然后通过头将其发回

dgtucam1  于 2023-01-25  发布在  Spring
关注(0)|答案(2)|浏览(328)

对于各种REST API端点,user_id将到达后端,需要进一步处理,然后作为响应发送回前端。
我有一种感觉,我可以通过头部来完成这项工作,而不是每次都将其作为路径参数传递,只是我似乎还找不到相关的信息。
目前我以ResponseEntity的形式发送响应。如果可能的话,我希望保留此选项。
我正在使用Java和Sping Boot 。

z31licg0

z31licg01#

示例基于
https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/http/ResponseEntity.html
编辑以添加请求中的readign标题

@RequestMapping("/handle")
public ResponseEntity<String> handle(HttpServletRequest httpRequest) {
  String userId= httpRequest.getHeader("user_id");
  HttpHeaders responseHeaders = new HttpHeaders();
  responseHeaders.set("user_id", userId);
  return new ResponseEntity<String>("Hello World", responseHeaders, HttpStatus.CREATED);
}
zfycwa2u

zfycwa2u2#

对于我的场景,我只需要获取用户ID,然后用它进行响应,我认为最好的方法是使用@RequestHeader(“userId”)Long userId注解。
让我们看看我最初是如何配置端点的:

@PostMapping(path = "/add-follower/{userIdForFollowing}/{currentUserId}")
public ResponseEntity<String> addFollower(@PathVariable ("userIdForFollowing") Long userIdForFollowing, @PathVariable Long currentUserId)
{
    Follow newFollow = followService.returnNewFollow(userIdForFollowing, currentUserId);
    
    newFollow = followService.saveFollowToDb(newFollow);

    return new ResponseEntity<>("Follow saved successfully", HttpStatus.OK);
}

现在,让我们看看我是如何重构端点以从头部获取id并在响应中返回它们的:

@PostMapping(path = "/add-follower")
public ResponseEntity<String> addFollower(@RequestHeader("userIdForFollowing") Long userIdForFollowing, @RequestHeader("currentUserId") Long currentUserId)
{

    Follow newFollow = followService.returnNewFollow(userIdForFollowing, currentUserId);
    newFollow = followService.saveFollowToDb(newFollow);

    //here I will add more code which should replace the String in the ResponseEntity.
    return new ResponseEntity<>("Follow saved successfully", HttpStatus.OK);
}

相关问题