如何在Spring中最好地处理RestController中的会话?
我正在寻找关于如何比下面的实现更优雅地处理会话的建议 基本上,我已经编写了一个如何在Spring中最好地处理RestController中的会话?,spring,session,spring-boot,Spring,Session,Spring Boot,我正在寻找关于如何比下面的实现更优雅地处理会话的建议 基本上,我已经编写了一个BaseController,它有一个handleSession()例程,用于从会话数据进行初始创建和后续读取。这个会话数据是存储各种安全信息所必需的,出于明显的性能原因,我不希望每次点击都读取这些信息。我也不想将这些信息存储在客户机上,或者我只需要创建一个新的请求来将信息拉回到数据库 CustomerController在每个请求中实现此handleSession()调用。这意味着我必须把它放在任何地方 有没有更优雅
BaseController
,它有一个handleSession()
例程,用于从会话数据进行初始创建和后续读取。这个会话数据是存储各种安全信息所必需的,出于明显的性能原因,我不希望每次点击都读取这些信息。我也不想将这些信息存储在客户机上,或者我只需要创建一个新的请求来将信息拉回到数据库
CustomerController
在每个请求中实现此handleSession()
调用。这意味着我必须把它放在任何地方
有没有更优雅的方式来处理这个问题
BaseController.java
CustomerController.java
@RestController
@请求映射(“/data/customer”)
公共类CustomerController扩展BaseController{
@自动连线
私人客户存储客户存储;
@请求映射(“”)
列出客户(HttpSession会话){
handleSession(会议);
返回customerRepository.getCustomers();
}
@请求映射(“/{company}/{customer}/{division}”)
客户客户(@PathVariable String company,
@PathVariable字符串客户,@PathVariable字符串分部,
HttpSession(会话){
handleSession(会议);
返回customerRepository.getCustomer(公司、客户、部门);
}
}
我并没有完全按照您的特定需求进行操作。但通常会话初始化是一个交叉问题,交叉问题通常最好作为servlet过滤器处理,而不是在每个控制器方法中处理。也许您可以在控制器中使用@Autowired获取HttpSession信息。如果您将会话信息作为参数传递,则有可能找到应用程序的安全漏洞
为此,请使用以下方法:
@RestController
@RequestMapping("/data/customer")
public class CustomerController extends BaseController {
@Autowired
private CustomerRepository customerRepository;
@Autowired
private HttpSession httpSession;
您可以从所有请求映射方法中删除HttpSession参数。什么类型的会话数据?一般来说,REST客户端将忽略您的会话cookie并发出单独的请求。我对spring和web stufs有点陌生,但如果我自动连接HttpSession,这会导致所有控制器之间共享sessionAttributes吗???@MohammedHousseynTaleb,不完全是控制器,而是用户会话。每个用户会话都与所有控制器共享,但具有不同用户的同一控制器将具有具有不同属性的不同会话,但对于该用户会话是持久的。
@RestController
@RequestMapping("/data/customer")
public class CustomerController extends BaseController {
@Autowired
private CustomerRepository customerRepository;
@RequestMapping("")
List<Customer> customers(HttpSession session) {
handleSession(session);
return customerRepository.getCustomers();
}
@RequestMapping("/{company}/{customer}/{division}")
Customer customer(@PathVariable String company,
@PathVariable String customer, @PathVariable String division,
HttpSession session) {
handleSession(session);
return customerRepository.getCustomer(company, customer, division);
}
}
@RestController
@RequestMapping("/data/customer")
public class CustomerController extends BaseController {
@Autowired
private CustomerRepository customerRepository;
@Autowired
private HttpSession httpSession;