【问题标题】:How to pass innerHTML content to th:field in thymeleaf?如何将 innerHTML 内容传递给 th: thymeleaf 中的字段?
【发布时间】:2019-08-17 11:09:58
【问题描述】:

我正在创建一个 Spring Boot 电子商务网站,并且我有一个 span 标签,其中包含到目前为止在购物车中的总价格,并在后台使用 JavaScript 进行更新:

<form method="POST" th:object="${chargeRequest}">
    <span class="total">
        Total: <span class="total-price">$0</span>
    </span>
</form>

我将模型属性model.addAttribute("chargeRequest", new ChargeRequest());传递给这个页面,ChargeRequest类定义为:

public class ChargeRequest {
    private int amount;

    // constructor, setter/getter
    // ...
}

问题是:如何更新chargeRequest中的amount,并使用Thymeleaf将其传回控制器?

th:field只对&lt;input&gt;&lt;select&gt;&lt;textarea&gt;有效,不能直接放到&lt;span&gt;标签上

我尝试传递 2 个属性:

model.addAttribute("amount", new String("$0"));
model.addAttribute("chargeRequest", new ChargeRequest());
<span class="total">
    Total: <span class="total-price" th:text="${amount}">$0</span>
    <input type="hidden" th:value="${amount}, id="amount", name="amount">
</span>

但我不知道如何更新${amount} 以便chargeReqeust 中的amount 可以自动更新?

【问题讨论】:

    标签: spring spring-boot spring-mvc thymeleaf


    【解决方案1】:

    不幸的是,您无法使用简单的控制器来做到这一点。您将需要一个 @ControllerAdvice 作为全局控制器,以便在有人将产品添加到他们的购物车或从他们的购物车中删除产品时更新购物车。

    换句话说,您需要一个GLOBAL CONTROLLER。此全局控制器应检查 SESSION 属性,以允许您更改总购物车的数量并在每次发生更改时更新它。例如,请在下面查看。

    @ControllerAdvice
    public class GlobalCartController{
        @Autowired
        private HttpSession session;
        @ModelAttribute("cartModel")
        public CartModel getCartTotal(){
            if(session.getAttribute("cart")==null){
               //Here you create cart attribute for the session 
               // then
               session.setAttribute("cartModel", cartObjectWithUpdatedTotal);
         }
         return (CartObjectWithUpdatedTotal) session.getAttribute("cartModel");
    

    }

    请注意,全局控制器将始终在所有路由处检查,并且不需要路由,这允许您使用 HttpSession 自动装配类,该类允许您

    通过多页请求识别用户或访问网站并存储有关该用户的信息。

    干杯

    【讨论】:

      猜你喜欢
      • 2020-12-31
      • 1970-01-01
      • 2017-05-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-20
      • 1970-01-01
      • 2020-05-13
      相关资源
      最近更新 更多