Controller不使用Spring启动和Thymeleaf从HTML中接收来自span的值

问题描述 投票:2回答:3

我在我的HTML中使用Thymeleaf有以下内容

<form action="#" th:action="@{/shutDown}" th:object="${ddata}" method="post">
        <span>Domain</span>
        <span th:text="${domain}" th:field="*{domain}">domain</span>
        <input type="Submit" value="close" />
</form>

我在使用ControllerSprint Boot中有以下内容

@RequestMapping(value = "/shutDown", method = RequestMethod.POST)
public ModelAndView shutDownPage(ModelAndView modelAndView, Authentication authentication,
        @ModelAttribute("ddata") DInputBean dInputBean) {
    String domain = dInputBean.getdomain();
    return modelAndView;
}

我希望我能从domain的HTML中获得Controller的价值,但它总是无效的。 DInputBean有“域”字段的getters and setters

spring spring-mvc spring-boot thymeleaf
3个回答
4
投票

th:field属性可用于<input><select><textarea>

你可以用一个隐藏的输入元素替换第二个<span>的解决方案。

<form action="#" th:action="@{/shutDown}" th:object="${ddata}" method="post">
    <span>Domain</span>
    <input type="hidden" th:field="*{domain}" th:value="${domain}" />
    <input type="Submit" value="close" />
</form>

如果你想保留第二个div,只需将<input type="hidden">放在第二个<span>中,然后从第二个th:field中删除<span>属性。

Edit:

如果你想在一个范围内添加domain的值。

<form action="#" th:action="@{/shutDown}" th:object="${ddata}" method="post">
    <span>Domain</span>
    <span th:text="${domain}">domain<span>
    <input type="hidden" th:field="*{domain}" th:value="${domain}" />
    <input type="Submit" value="close" />
</form>

http://www.thymeleaf.org/doc/tutorials/3.0/thymeleafspring.html#inputs


1
投票

一个选项是使用只读输入字段:

<input type="text" th:field="*{domain}" th:value="${domain}" readonly="readonly"/>

这两个都显示值并在提交时发送。


1
投票

关键是将domain变量的值添加到表单中:

@GetMapping("/shutDownPage") 
public String shutDownPage(Model model) {
    model.addAttribute("ddata" new Ddata()); //or however you create your bean
    String username = ... //however you get your username
    String domain = myRepositoryService.findDomainByUsername(username);
    model.addAttribute("domain", domain);
    return "shutDownPage";
}

action中包含一个HTML页面,这样当您在没有服务器/容器的浏览器中打开HTML页面时,该按钮仍然可以正常工作:

<form action="confirmationPage.html" th:action="@{/shutDown}" th:object="${ddata}" method="post">
     <!-- You can benefit from using a conditional expression -->
     <span th:text="${domain != null ? domain : 'No domain supplied'}">[domain]</span>
     <input type="hidden" th:field="*{domain}" th:value="${domain}"/>
     <input type="Submit" value="close"/>
</form>

而你的帖子方法:

@PostMapping("/shutDown")  //use shorthand
public String shutDownPagePost(@ModelAttribute("ddata") DInputBean dInputBean {
    String domain = dInputBean.getDomain();
    //do whatever with it
    return "confirmationPage";
}
© www.soinside.com 2019 - 2024. All rights reserved.