java - 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()));
}
解决方案
首先,您使用的是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的情况下,您可以执行以下操作:
$ 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()
推荐阅读
- javascript - 为什么根变量最终会保留在 while 循环中生成的整个树的结果?
- c++ - 为什么我的动态数组可以在不调整大小的情况下工作?
- python - 通过 for 循环连接 DataFrame
- python-2.7 - 使用 tkinter python 2.7 将数据从 excel 加载到 json 文件时显示加载 gif
- json - 在 SNOWFALKE 中从 JSON 中提取和转换 Datetime 字段
- javascript - 有没有办法在不硬编码的情况下获取键盘键列表及其各自的键码?
- javascript - 在 JSON API 调用中调用特定数组
- python - 没有标签元素的 xpath
- c# - IsUnique 验证属性不适用于数据库中的其他条目
- python - Pandas 将一列元组旋转/扩展为命名列