Spring 启动 - 两个不同请求之间的 HttpSession 为空

Spring boot - HttpSession is null between two different request

首先,当我调用API“/fetch/event/1221”时,我能够设置会话属性, 但是当我调用 "fetch/partcipant" API 时,我得到的 httpSession 为 null。 我该如何解决这个问题?

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

首先,你在/fetch/event/中使用httpServletRequest.getSession(false),如果没有当前session,它不会创建session。如果没有当前 session:

,将其更改为 true 以强制创建一个新的
 HttpSession httpSession = httpServletRequest.getSession(true);

创建 session 后,它将 return session id 通过 cookie 在响应中 header :

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

要告诉服务器使用特定的 session ,后续请求应通过 cookie 包含此 session id。如果是 ,你可以这样做:

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

这将添加以下 HTTP 请求 header :

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

然后在 getListOfActiveParticipants() 中,您应该得到在 fetchEvent()

中创建的 session