spring之如何在 Spring 中最好地处理 RestController 中的 session

zhujiabin 阅读:128 2025-02-15 21:57:57 评论:0

我正在寻找有关如何比下面的实现更优雅地处理 session 的建议。

基本上我写了一个 BaseController有一个 handleSession()从 session 数据中进行初始创建和后续读取的例程。出于明显的性能原因,需要此 session 数据来存储各种安全信息,我不想在每次点击时都读取这些信息。我也不想将它存储在客户端上,或者我只是创建一个新请求将信息拉回 Angular。
CustomerController实现这个 handleSession()在每个请求中调用。这意味着我必须把它放在任何地方。

有没有更优雅的方法来处理这个问题?

基础 Controller .java

public abstract class BaseController { 
 
    public Logger log = LoggerFactory.getLogger(getClass()); 
 
    public void handleSession(HttpSession session) { 
        if (session.isNew()) { 
            log.info("New session: " + session.getId()); 
            // TODO: write all session data here? 
            session.setAttribute("Parm", "Value"); 
        } else { 
            // TODO: read all session data here? 
            log.info("Reused session: " + session.getId() + " Parm is set to: " 
                    + session.getAttribute("Parm")); 
 
        } 
    } 
} 

客户 Controller .java
@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); 
    } 
} 

请您参考如下方法:

也许您可以在 Controller 中使用 @Autowired 获取 HttpSession 信息。如果您将 session 信息作为参数传递,您将有可能为您的应用程序找到安全漏洞。

为此,请使用以下方法:

@RestController 
@RequestMapping("/data/customer") 
public class CustomerController extends BaseController { 
    @Autowired 
    private CustomerRepository customerRepository; 
 
    @Autowired 
    private HttpSession httpSession; 

您可以从所有请求映射方法中删除 HttpSession 参数。


标签:Spring
声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

关注我们

一个IT知识分享的公众号