首页 > 解决方案 > Spring boot - 两个不同请求之间的 HttpSession 为空

问题描述

首先,当我调用 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()));
    }

标签: javarestspring-bootapihttpsession

解决方案


首先,您使用的是httpServletRequest.getSession(false)in /fetch/event/,如果没有当前会话,它将不会创建会话。true如果没有当前会话,请将其更改为强制创建一个新会话:

 HttpSession httpSession = httpServletRequest.getSession(true);

创建会话后,它将通过响应标头中的 cookie 返回会话 ID:

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

为了告诉服务器使用特定的会话,后续的请求应该通过 cookie 包含这个会话 id。在的情况下,您可以执行以下操作:

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

这将添加以下 HTTP 请求标头:

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

然后在 中getListOfActiveParticipants(),您应该获得在中创建的会话fetchEvent()


推荐阅读