Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Controller Not receiving value from span in HTML using Spring boot and Thymeleaf

I have the following content in my HTML which is using 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>

And I have the following in my Controller which is using Sprint Boot

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

I'm hoping I'd get value of domain from the HTML in the Controller but it's always null. DInputBean has getters and setters for "domain" field.

like image 878
Damien-Amen Avatar asked May 10 '26 23:05

Damien-Amen


2 Answers

The th:field attribute can be used on <input>, <select>, or, <textarea>.

A solution you could possibly replacing you second <span> with a hidden input element.

<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>

If you wanted to keep the second div, just place the <input type="hidden"> inside the second <span> and remove the th:field attribute from the second <span>.

Edit:

If you wanted to add the value of domain in a span.

<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

like image 123
Jason White Avatar answered May 14 '26 18:05

Jason White


An option is to use a read-only input field:

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

This both displays the value and sends it on submit.

like image 25
holmis83 Avatar answered May 14 '26 16:05

holmis83



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!