简体   繁体   中英

How can I get the user_id from the request header instead of passing it as a request parameter? And then send it back through the header

For various REST api endpoints, the user_id will reach the backend, needed for further processing and then, sent back as a response to the front end.

I have a feeling I can do this through the header instead of passing it as a path parameter each time, except I can't seem to find the relevant information yet.

At the moment I send the response as a ResponseEntity. I would like, if possible, to keep this option.

I am using Java and Spring Boot.

example based on

https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/http/ResponseEntity.html

edited to add readign header from request

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

I have decided that the best approach for my scenario, where I only need to fetch the user id and then respond back with it, is to use the @RequestHeader("userId") Long userId annotation.

Let's have a look at how I had configured the enpoint initially:

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

Now, let's look at how I refactored the endpoint to fetch the id's from the header and return them in the response:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM