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

标签 spring session spring-boot

我正在寻找有关如何比下面的实现更优雅地处理 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 - 如何在 Spring 中最好地处理 RestController 中的 session ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24697803/

相关文章:

java - 将系统属性从 Gradle 传递到 Spring Boot

java - 请求之间的 session 不持久

java - Spring session 中带有 HeaderHttpSessionStrategy 的 Null HttpSessionManager

java - 当我在springboot API上使用@OneToMany和@ManyToOne时出现错误消息

spring - 找不到适合类型 [简单类型,类 java.time.LocalDateTime] 的构造函数

java - Spring Data JPA 无法找到具有给定名称的属性

java - Hibernate,持久化ManyToMany

spring - 在父类(super class)中为@Repository bean注入(inject)没有@Autowired的派生属性

java - Tomcat服务器启动完成回调

asp.net - ASP.NET State Service 版本有问题;状态服务是1.1,网站是3.5