Reputation: 4691
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?
Upvotes: 6
Views: 11049
Reputation: 976
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.
Upvotes: 10
Reputation: 4366
Use JSp as suggested in the comment section above. First you must add the following depency to your pom (or its equivalent for gradle)
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.4</version>
<scope>provided</scope>
</dependency>
Also, your jsp's should be placed inside your web-inf folder. Your application.properties should look like this:
spring.mvc.view.prefix: /WEB-INF/jsp/
spring.mvc.view.suffix: .jsp
Upvotes: 0