繁体   English   中英

使用Spring将数据从Thymeleaf传递到控制器

[英]Pass data from Thymeleaf to the controller using Spring

嗨,我是Spring和Thymeleaf开发的新手,我试图了解如何在Thymeleaf和控制器之间传递数据。 我知道如何以其他方式传递数据。 使用我从控制器传递到视图的数据,我正在构建一个表,其中有两列(一列是用于选择服务的按钮,另一列是服务名称),并且与该行一样多的行我有。 我想要做的就是获取所选服务的ID(当按下添加按钮时,我只能按一次单个按钮,但是我可以按所有其他按钮),并使用它进行一些后端处理(现在)我只是想打印值)。 另一件事是,一旦单击该按钮,它会将我重定向到索引页面,但在URL的末尾添加/ addService,而我不希望这样做(我想保留在具有相同URL的同一页面中)。 我怎么解决这个问题?

index.html

<table id="html-table" class="table table-hover table-clean table">
    <thead>
        <tr>
            <th>Select</th>
            <th>Service</th>
        </tr>
    </thead>
    <tbody>
        <tr th:each="serviceOffered : ${servicesOffered}">
            <td>
            <form action="#" th:value="${serviceOffered.id}" th:object="${serviceOffered}" th:action="@{/addService}" method="POST">
                <button type="submit" class="btn" name="${serviceOffered.id}">
                    <i class="fas fa-plus"></i>
                </button>
                </form>
            </td>
            <td th:value="${serviceOffered.name}" th:text="${serviceOffered.name}"></td>
        </tr>
    </tbody>
</table>

控制者

@RequestMapping(value="/addService", method = RequestMethod.POST)
public ModelAndView addService(@Valid ServiceOffered serviceOffered, BindingResult bindingResult){
    ModelAndView modelAndView = new ModelAndView();

    System.out.println("VALUE " + serviceOffered.getId());

    modelAndView.setViewName("/index");
    return modelAndView;
}

您的表单具有一个类型为submit的按钮。 当您按下按钮时,它会提交表单。 在控制器中,您重定向到index页面。 如果您想单击按钮并仅发送服务的值而不重新加载页面,则需要使用use jquery的ajax调用。 docs这是ajax调用的示例代码。

$.ajax({
url: '/your url',
method: 'post',
data: 'your data'
}).then(function(response){
// do what ever you want with your response.
})

记住:您需要在控制器类的方法上添加@Responsebody批注。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM