Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling a form with Spring MVC without using the Spring <form:form> tag?

Is it possible to handle a form using Spring annotation @ModelAttribute without using the Spring tag <form:form...>. I saw this way to do but it seems complex with using Thymeleaf (I don't know anything about it).

Spring is supposed to be a non-intrusive framework so is there an alternate solution to my problem?

like image 772
akuma8 Avatar asked Oct 14 '16 15:10

akuma8


1 Answers

If you build your form using Spring tags, it will be converted to HTML. Run your project and check the source code of your JSP site. Spring tags just make things a bit easier for a coder. For example

<form:form modelAttribute="newUser" action="/addUser" method="post">
   <form:input path="firstName" />
   <form:input path="lastName" />
   <button type="submit">Add</button>
</form:form>

will be converted to HTML

<form id="newUser" action="/addUser" method="post">
   <input id="firstName" name="firstName" type="text" value="" />
   <input id="lastName" name="lastName" type="text" value="" />
   <button type="submit">Add</button>
</form>

In Controller you add a data transfer object (DTO) to Model, for example

@RequestMapping(value = "/index", method = RequestMethod.GET)
public ModelAndView homePage() {
   ModelAndView model = new ModelAndView();
   model.addObject("newUser", new User());
   model.setViewName("index");
   return model;
}

and receive the form data

@RequestMapping(value = "/addUser", method = RequestMethod.POST)
public ModelAndView addUser(
        @ModelAttribute("newUser") User user) { ... }

Using Spring tags is totally optional as long as the naming of the form fields is exactly the same as in your bean object (here User class) and model.

like image 180
micaro Avatar answered Sep 19 '22 11:09

micaro