【发布时间】:2021-04-21 08:51:36
【问题描述】:
我有一个需要三段数据的应用程序。
例子:
public class RequestForm {
private final String a;
private final String b;
private final String c;
}
我想一一获取对该对象的字段的请求,并在将其存储在会话中后立即初始化该对象。
一个有点乱的例子:
@PostMapping(URL+"/1")
public ResponseEntity<String> enteredA(@RequestBody String a, HttpSession httpSession) {
httpSession.setAttribute("a", a);
return new ResponseEntity<>(HttpStatus.OK);
}
@PostMapping(URL+"/2")
public ResponseEntity<String> enteredB(@RequestBody Stirng b, HttpSession httpSession) {
log.info("b : {} ", b);
httpSession.setAttribute("b", b);
return new ResponseEntity<>(HttpStatus.OK);
}
@PostMapping(URL+"/3")
public ResponseEntity<String> enteredC(@RequestBody String c, HttpSession httpSession) {
log.info("c : {} ", c);
httpSession.setAttribute("c", c);
String a = (String) httpSession.getAttribute("a");
String b = (String) httpSession.getAttribute("a");
String c = (String) httpSession.getAttribute("a");
save(new RequestForm(a, b, c);
return new ResponseEntity<>(HttpStatus.OK);
}
但是,有一种强烈的感觉,你不应该这样做。
听说你可以使用@SessionAttributes 之类的东西。
顺便说一句,许多示例为每个请求初始化一个对象并将其存储在会话中。
有没有办法为多个请求初始化一个对象? 我正在使用 Spring Boot 2.4 进行开发。
请。谢谢。????
【问题讨论】:
-
你能详细说明你为什么需要这个吗?可以通过多种方式为多个请求初始化一个对象。选择正确的方式取决于目的。如果对象是特定于用户的,那么 Session 是最好的方法。如果所有用户的对象都相同,那么我们应该自动装配或创建单例对象。
-
不适用于`@RequestBody
, you can with@ModelAttribute. But if you are sending JSON (judging from the@RequestBody)@ModelAttribute` 将无法工作。此外,如果您要发送 JSON,您不应该在客户端处理多个步骤并一次性发送一个包含所有内容的正文吗?看起来您正在尝试处理您将在服务器上的客户端中/上处理的东西。
标签: java spring spring-boot session spring-session