【问题标题】:SpringBoot MVC - Post ThymeLeaf ObjectSpring Boot MVC - 发布 ThymeLeaf 对象
【发布时间】:2018-06-15 06:09:17
【问题描述】:

我想知道是否可以使用 ThymeLeaf 和 SpringBoot 发布对象?

我在网上查过,但似乎没有很好的记录。

我知道下面的代码不起作用,但它显示了我想要实现的一般要点。

请假设有一个名为“part”的Part类型的对象传入视图。

控制器:

@Controller
@RequestMapping("/basket")
public class BasketController {
@RequestMapping(value = "/add", method = RequestMethod.POST)

public ModelAndView addToBasket(@ModelAttribute("part") Part part) {

 ModelAndView mv = new ModelAndView("basket/viewBasket");
 return mv;

}
}

还有观点:

<form method="POST" th:action="@{/basket/add}" th:object="${part}" modelAttribute="part">
                <input th:object="${part}"/>
                <input type="submit" class="btn btn-warning btn-block" th:value="#{basket.add}"/>
            </form>

谢谢!

【问题讨论】:

  • 请添加Controller级别映射,我们可以帮助您。
  • @MehrajMalik 完成。谢谢!
  • @MehrajMalik 这正是我最终需要做的。只需发布部件的 ID 并使用它来引用对象。谢谢

标签: spring-mvc object spring-boot post thymeleaf


【解决方案1】:

您发布的示例存在一些问题。我们可以将其简化/现代化为:

@Controller
public class BasketController {

    @GetMapping("/partPage") //or whatever page you're requesting
    public String getPartPage(Model model) {    
        model.addAttribute("part", new Part()); //make sure it's added to the model
        return "partPage";
    }

    //don't include blank lines after your annotations
    @PostMapping("/add")
    public String addToBasket(@ModelAttribute("part") Part part) {
        //do your validation or whatever    
        return "basket/viewBasket";
    }
}

还有观点:

<!-- just use th:object, don't need a model attribute -->
<form method="POST" th:action="@{/add}" th:object="${part}">
    <!-- remove the line about the input th:object here. doesn't make sense -->
    <!-- alternate way to show the button.  Good to include a default value for the button so you can see what the page looks like by just opening it in a browser without a server -->
    <button type="submit" class="btn btn-primary btn-block" th:text="#{basket.add}">Add</button>
</form>

【讨论】:

    【解决方案2】:

    最后我创建了一些隐藏字段并发布了相关信息。

    然后在服务器端重新创建对象。

    感谢您的帮助!

    【讨论】:

      猜你喜欢
      • 2019-06-28
      • 1970-01-01
      • 2015-02-19
      • 2020-10-19
      • 1970-01-01
      • 2018-09-24
      • 1970-01-01
      • 2017-10-20
      • 2017-09-12
      相关资源
      最近更新 更多