【问题标题】:Spring boot - HttpSession is null between two different requestSpring boot - 两个不同请求之间的 HttpSession 为空
【发布时间】:2020-02-17 03:24:26
【问题描述】:

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

【问题讨论】:

  • 你调用端点的方式完全一样吗?

标签: java rest spring-boot api httpsession


【解决方案1】:

首先,您在/fetch/event/ 中使用httpServletRequest.getSession(false),如果没有当前会话,它将不会创建会话。如果没有当前会话,请将其更改为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() 中创建的会话

【讨论】:

    猜你喜欢
    • 2018-11-04
    • 2019-01-26
    • 2014-04-21
    • 2013-08-17
    • 2022-01-22
    • 2018-02-23
    • 2019-07-05
    • 1970-01-01
    相关资源
    最近更新 更多