gpt4 book ai didi

java - Spring boot - 两个不同请求之间的 HttpSession 为 null

转载 作者:太空宇宙 更新时间:2023-11-04 09:05:49 24 4
gpt4 key购买 nike

首先,当我调用 API“/fetch/event/1221”时,我可以设置 session 属性,但是当我调用“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 以强制创建一个新 session :

 HttpSession httpSession = httpServletRequest.getSession(true);

session 创建后,会通过响应头中的cookie返回 session id:

< 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

关于java - Spring boot - 两个不同请求之间的 HttpSession 为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60246234/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com