life-notes/src/note/Java/Spring/向session共享数据.md

12 KiB
Raw Blame History

向session共享数据

在 Spring MVC 中,Session 是用于存储用户会话期间的数据的一种机制。每个用户访问的应用程序都将拥有一个唯一的会话。通过 HttpSession,可以在用户的会话中存储一些数据,直到用户关闭浏览器或会话过期。

Spring MVC 提供了多种方式来与 <font style="color:rgb(0, 0, 0);">HttpSession</font> 进行交互,下面详细介绍如何通过 <font style="color:rgb(0, 0, 0);">HttpSession</font> 向 Session 共享数据。

1. 通过 <font style="color:rgb(0, 0, 0);">HttpSession</font> 操作 Session 数据

在 Spring MVC 控制器中,您可以通过 <font style="color:rgb(0, 0, 0);">HttpSession</font> 对象来存储和读取会话数据。

示例:将数据添加到 Session

@Controller
public class SessionController {

    @RequestMapping("/setSessionData")
    public String setSessionData(HttpSession session) {
        // 将数据存储到 Session 中
        session.setAttribute("username", "JohnDoe");
        session.setAttribute("age", 30);
        return "sessionSet";  // 返回视图名
    }

    @RequestMapping("/getSessionData")
    public String getSessionData(HttpSession session, Model model) {
        // 从 Session 中获取数据
        String username = (String) session.getAttribute("username");
        Integer age = (Integer) session.getAttribute("age");
        model.addAttribute("username", username);
        model.addAttribute("age", age);
        return "sessionData";  // 返回视图名
    }
}

URL 请求:

  • <font style="color:rgb(0, 0, 0);">GET /setSessionData</font> 会将数据 <font style="color:rgb(0, 0, 0);">"username": "JohnDoe"</font><font style="color:rgb(0, 0, 0);">"age": 30</font> 存储到 Session 中。
  • <font style="color:rgb(0, 0, 0);">GET /getSessionData</font> 会从 Session 中获取并显示存储的值。

2. 使用 <font style="color:rgb(0, 0, 0);">@SessionAttributes</font> 注解

<font style="color:rgb(0, 0, 0);">@SessionAttributes</font> 注解用于将控制器中的某些模型属性放入 Session 中。这种方式比直接操作 <font style="color:rgb(0, 0, 0);">HttpSession</font> 更为方便和简洁,特别是当需要共享多个模型属性时。

示例:使用 <font style="color:rgb(0, 0, 0);">@SessionAttributes</font>

@Controller
@SessionAttributes("user")
public class UserController {

    // 在模型中添加用户对象
    @RequestMapping("/setUser")
    public String setUser(Model model) {
        User user = new User("John", 30);
        model.addAttribute("user", user);
        return "userSet";
    }

    // 从 Session 中获取用户对象
    @RequestMapping("/getUser")
    public String getUser(@ModelAttribute("user") User user, Model model) {
        model.addAttribute("user", user);
        return "userDetails";
    }
}

URL 请求:

  • <font style="color:rgb(0, 0, 0);">GET /setUser</font> 会将 <font style="color:rgb(0, 0, 0);">user</font> 对象放入 Session 中。
  • <font style="color:rgb(0, 0, 0);">GET /getUser</font> 会从 Session 中获取 <font style="color:rgb(0, 0, 0);">user</font> 对象。

<font style="color:rgb(0, 0, 0);">@SessionAttributes</font> 注解不仅可以放入 Session 中,还可以与 <font style="color:rgb(0, 0, 0);">@ModelAttribute</font> 注解结合使用,确保模型数据保持在 Session 中。

3. 使用 <font style="color:rgb(0, 0, 0);">@ModelAttribute</font> 注解

<font style="color:rgb(0, 0, 0);">@ModelAttribute</font> 注解允许将数据放入模型中,并且在方法调用前通过 <font style="color:rgb(0, 0, 0);">Model</font> 传递给视图。如果和 <font style="color:rgb(0, 0, 0);">@SessionAttributes</font> 一起使用,它可以将属性直接添加到 <font style="color:rgb(0, 0, 0);">HttpSession</font>

示例:使用 <font style="color:rgb(0, 0, 0);">@ModelAttribute</font><font style="color:rgb(0, 0, 0);">@SessionAttributes</font>

@Controller
@SessionAttributes("cart")
public class CartController {

    // 在模型中创建并存储购物车
    @ModelAttribute("cart")
    public Cart createCart() {
        return new Cart();  // 创建一个空的购物车对象
    }

    // 添加商品到购物车
    @RequestMapping("/addToCart")
    public String addToCart(@ModelAttribute("cart") Cart cart, @RequestParam("item") String item) {
        cart.addItem(item);  // 将商品添加到购物车
        return "cartUpdated";
    }

    // 显示购物车内容
    @RequestMapping("/viewCart")
    public String viewCart(@ModelAttribute("cart") Cart cart, Model model) {
        model.addAttribute("cart", cart);
        return "viewCart";
    }
}

URL 请求:

  • <font style="color:rgb(0, 0, 0);">GET /addToCart?item=Apple</font> 会将 <font style="color:rgb(0, 0, 0);">Apple</font> 添加到 <font style="color:rgb(0, 0, 0);">cart</font> 中。
  • <font style="color:rgb(0, 0, 0);">GET /viewCart</font> 会显示购物车中的内容。

4. 通过 <font style="color:rgb(0, 0, 0);">@RequestParam</font><font style="color:rgb(0, 0, 0);">@PathVariable</font> 获取 Session 数据

如果在请求中需要通过路径变量或请求参数传递数据并存储到 Session 中,可以结合 <font style="color:rgb(0, 0, 0);">@RequestParam</font><font style="color:rgb(0, 0, 0);">@PathVariable</font> 来实现。

示例:使用 <font style="color:rgb(0, 0, 0);">@RequestParam</font> 存储 Session 数据

@Controller
public class SessionController {

    @RequestMapping("/setSession/{username}")
    public String setSessionData(@PathVariable("username") String username, HttpSession session) {
        session.setAttribute("username", username);
        return "sessionSet";
    }

    @RequestMapping("/getSession")
    public String getSessionData(HttpSession session, Model model) {
        String username = (String) session.getAttribute("username");
        model.addAttribute("username", username);
        return "sessionData";
    }
}

URL 请求:

  • <font style="color:rgb(0, 0, 0);">GET /setSession/JohnDoe</font> 会将 <font style="color:rgb(0, 0, 0);">"username": "JohnDoe"</font> 存储到 Session 中。
  • <font style="color:rgb(0, 0, 0);">GET /getSession</font> 会从 Session 中获取并显示 <font style="color:rgb(0, 0, 0);">username</font>

5. 删除 Session 数据

如果希望在某个操作后清除 Session 中的某些数据,可以使用 <font style="color:rgb(0, 0, 0);">HttpSession</font> 提供的 <font style="color:rgb(0, 0, 0);">removeAttribute</font> 方法。

示例:删除 Session 数据

@Controller
public class SessionController {

    @RequestMapping("/removeSessionData")
    public String removeSessionData(HttpSession session) {
        session.removeAttribute("username");  // 删除指定的属性
        return "sessionRemoved";
    }
}

URL 请求:

  • <font style="color:rgb(0, 0, 0);">GET /removeSessionData</font> 会从 Session 中删除 <font style="color:rgb(0, 0, 0);">"username"</font> 属性。

6. Session 过期与清理

默认情况下Spring MVC 的 <font style="color:rgb(0, 0, 0);">HttpSession</font> 会话会在用户关闭浏览器后过期或者会话超时默认30分钟。可以在 <font style="color:rgb(0, 0, 0);">web.xml</font> 或应用的配置类中设置会话超时:

示例:设置 Session 超时

<session-config>
    <session-timeout>30</session-timeout> <!-- 设置会话超时为30分钟 -->
</session-config>

7. 通过 Spring 配置 Session

通过 Spring 配置文件或 Java 配置类,还可以控制 Session 的相关行为如会话过期时间、session 的持久化等)。

示例Java 配置类

@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new SessionInterceptor()).addPathPatterns("/**");
    }
}

<font style="color:rgb(0, 0, 0);">SessionInterceptor</font> 可以用于监控和管理 Session 数据。

在 Spring MVC 中,向 Session 共享数据主要有以下几种方式:

  • <font style="color:rgb(0, 0, 0);">HttpSession</font>:通过 <font style="color:rgb(0, 0, 0);">HttpSession</font> 对象存储和读取 Session 数据。
  • <font style="color:rgb(0, 0, 0);">@SessionAttributes</font>:通过 <font style="color:rgb(0, 0, 0);">@SessionAttributes</font> 注解将模型属性添加到 Session 中。
  • <font style="color:rgb(0, 0, 0);">@ModelAttribute</font>:结合 <font style="color:rgb(0, 0, 0);">@SessionAttributes</font> 使用,将模型数据持久化到 Session 中。
  • <font style="color:rgb(0, 0, 0);">@RequestParam</font>** 和 **<font style="color:rgb(0, 0, 0);">@PathVariable</font>:将请求参数或路径变量存储到 Session 中。
  • Session 过期与清理:可以通过配置控制会话超时,或手动清除 Session 数据。