Search code examples
javarestspring-bootapihttpsession

Spring boot - HttpSession is null between two different request


First, when I call the API "/fetch/event/1221", I am able to set the session attribute, But I am getting httpSession as null when I call the "fetch/partcipant" API. How can I fix this?

@RequestMapping(value = "/fetch/event/{eventId}", method = RequestMethod.GET)
        public SuccessResponse<Event> fetchEvent(@PathVariable("eventId") String eventId, HttpServletRequest httpServletRequest) throws ExecutionException, InterruptedException {
            Event event = eventService.getEventById(eventId);
            HttpSession httpSession = httpServletRequest.getSession(false);
            httpSession.setAttribute("event", event);
            return new SuccessResponse<Event>(event);
        }


 @RequestMapping(value = "/fetch/participant", method = RequestMethod.GET)
    public SuccessResponse<List<Participant>> getListOfActiveParticipants(HttpServletRequest httpServletRequest) throws ExecutionException, InterruptedException {
        HttpSession httpSession = httpServletRequest.getSession(false);
        Event event = (Event) httpSession.getAttribute("event");
        System.out.println((Event) httpSession.getAttribute("event"));
        return new SuccessResponse<>(participantService.getParticipants("ALL", event.getId()));
    }

Solution

  • First of all , you are using httpServletRequest.getSession(false) in /fetch/event/ , it will not create a session if there is no current session. Change it to true to force it create a new one if there are no current session:

     HttpSession httpSession = httpServletRequest.getSession(true);
    

    Once the session is created , it will return the session id through cookie in the response header :

    < HTTP/1.1 200
    < Set-Cookie: JSESSIONID=6AD698B82966D43FF395E54F5BFCEF65; Path=/; HttpOnly
    

    To tell the server to use a particular session , the subsequent request should include this session id through cookie. In case of , you can do :

    $ curl -v --cookie "JSESSIONID=6AD698B82966D43FF395E54F5BFCEF65" http://127.0.0.1:8080/fetch/partcipant
    

    which will add the following HTTP request header :

    > GET /fetch/participant HTTP/1.1
    > Host: 127.0.0.1:8080
    > Cookie: JSESSIONID=6AD698B82966D43FF395E54F5BFCEF65
    

    Then in getListOfActiveParticipants() , you should get the session that is created in fetchEvent()