【问题标题】:How to update a session attribute in Spring MVC web app如何在 Spring MVC Web 应用程序中更新会话属性
【发布时间】:2014-07-19 16:54:32
【问题描述】:

我在结帐过程中通过 org.springframework.web.bind.annotation.SessionAttributes 将购物车实例存储在会话变量中:

@SessionAttributes({"shoppingCart"})
public class CheckoutController { ... }

但是,当结帐过程完成后,我想在会话中存储一个新的 ShoppingCart 实例。

我需要类似的东西:

sessionAttributes.set("shoppingCart", new ShoppingCart());

我可以使用哪种方法来完成这项任务?

【问题讨论】:

    标签: java spring session spring-mvc


    【解决方案1】:

    如果你可以访问HttpServletRequest,试试这个

    request.getSession().setAttribute("shoppingCart", new ShoppingCart());
    

    【讨论】:

    • @SergeBallesta 我 100% 确定我的答案方式在我当前的实时应用程序中有效,而无需使用和设置为 model attribute。你以为只能作为spring的model属性来做吗?
    • @SergeBallesta 你知道我们一直在学习,但我很抱歉你之前对Your answers adds a new attribute in the HttpSession but does not modify the model attribute.的评论
    • @SergeBallesta 感谢您的研究,实际上我只是保持我的工作方式。再次感谢您的分享!
    【解决方案2】:

    您可以简单地使用Model 来覆盖它:

    public String method(Model model) {
        model.addAttribute("shoppingCart", new ShoppingCart());
        ....
    }
    

    另一个选项是将SessionStatus 接口添加到方法参数中。它有清理会话属性的方法:

    public String method(SessionStatus sessionStatus) {
        sessionStatus.setComplete();
        ....
    }
    

    【讨论】:

    • 是的。谢谢。我就是做这个的。请参阅上面的答案(应该在您的帖子之后添加...)。
    【解决方案3】:

    感谢您的回答。 最后我通过以下方式解决了这个问题: 我有一个基本控制器,用于在创建新会话时填充购物车的所有结帐相关控制器:

    @SessionAttributes({"shoppingCart"})
    public class CheckoutController {
    
      @ModelAttribute("shoppingCart")
      public ShoppingCart populateSessionShoppingCart() {
        // populates the cart for the first time if its null
        return new ShoppingCart();
      }
    }
    

    在完成结帐过程的控制器中,我使用以下方法:

    @Controller
    public class PaymentController extends CheckoutController {
    
      @RequestMapping(value = "/final_page", method = RequestMethod.GET)
      public String finalPage(Map<String, Object> model) {
        model.put("shoppingCart", new ShoppingCart());
        return "final_page";
      }
    }
    

    行:model.put("shoppingCart", new ShoppingCart());在会话中重置购物车。

    注意:这种方法只使用了 spring 会话处理,当然它也以某种方式使用了底层的 HttpSession。 spring 如何在内部处理 session 处理,是一个内部 spring 实现细节,与上面的代码无关。

    【讨论】:

      猜你喜欢
      • 2017-07-08
      • 1970-01-01
      • 2017-12-18
      • 1970-01-01
      • 2014-04-18
      • 2013-08-15
      • 1970-01-01
      • 2012-05-14
      • 2021-08-31
      相关资源
      最近更新 更多