hhrzc
hhrzc

Reputation: 2059

How to send object or data to controller from html file?

I get the "explorer" object in the html file and can analyze it:

<body>
<form th:action="@{/parsing}" method="post">
    <div class="w3-container">

        <table class="w3-table-all w3-card-4">
            <tr>
                <th>Id</th>
                <th>Query</th>
                <th></th>
            </tr>
            <tr>
                <td th:text="${explorer.getId()}"></td>
                <td th:text="${explorer.getQuery()}"></td>
                <td>
                    <input class="w3-button w3-blue w3-right" type="submit" value="Enter"/>
                </td>
            </tr>
        </table>

    </div>
</form>
</body>
</html>

Now I want to send it in post method but when I submit, I get null in "result".

Method, who get query from submit action:

@PostMapping("/parsing")
public ModelAndView parsing(
    @ModelAttribute Explorer explorer
    ){
    System.out.println("explorerId = " + explorer.getId());
    System.out.println("explorerId = " + explorer.getQuery());
    return new ModelAndView("result");
}

(It does not throw any exceptions, but prints only null data in the console)

How to send any object in this situation for post-method?

Upvotes: 1

Views: 711

Answers (1)

Dorado
Dorado

Reputation: 431

You're close. Your form is missing a commanding object attribute.

I would suggest adding th:object="${explorer}" to your form tag.

In your GET method, double check the function to create the explorer object from controller and then add the object in request attribute for the form to command an object before a POST action can be successfully submit the object.

This Thymeleaf docs has more answers than I could combine in this thread.

Upvotes: 1

Related Questions