0

I was going through a simple form submission using Spring MVC with Thymeleaf. I am not able to understand this part of code correctly (model.addAttribute("greeting", new Greeting());)

is "greeting" is this greeting a object of Greeting class or something else .. Does model object means a view of form submission ?

Am i correct : on loading submission form , a greeting object is instantiated using @GetMapping by calling greetingForm method and on clicking submit button ,it just load attribute value stored in textbox to object and stored in server and display the result on result page.
@Controller public class GreetingController {

  @GetMapping("/greeting")
  public String greetingForm(Model model) {
    model.addAttribute("greeting", new Greeting());
    return "greeting";
  }

  @PostMapping("/greeting")
  public String greetingSubmit(@ModelAttribute Greeting greeting) {
    return "result";
  }

// result page

<body>
    <h1>Result</h1>
    <p th:text="'id: ' + ${greeting.id}" />
    <p th:text="'content: ' + ${greeting.content}" />
</body>

// form submission

<body>
    <h1>Form</h1>
    <form action="#" th:action="@{/greeting}" th:object="${greeting}" method="post">
        <p>Id: <input type="text" th:field="*{id}" /></p>
        <p>Message: <input type="text" th:field="*{content}" /></p>
        <p><input type="submit" value="Submit" /> <input type="reset" value="Reset" /></p>
    </form>

1 Answer 1

0

Model object here represents the form-backing object. Data in the form has to be collected and wrapped into an object. So, before rendering the form to the user, we are letting Spring MVC to use this empty Greeting object.

In case, you have set the model object as follows, these values would have pre populated in the form.

model.addAttribute("greeting", new Greeting(1,"This is the content"));
2
  • so "greeting" inside this double code is an empty object in my code and it can be any another name as well . And i have to use this name to get the attribute value as ....something like from my result page as -- greeting.id to get the id value .
    – tomtom
    Sep 20, 2020 at 16:21
  • Yes, very similar to java object names.
    – Niyas
    Sep 21, 2020 at 6:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.