For binding data on a jsp page to a form, one of the easiest ways is using spring form tag.
To store data of these tags, we need only the attribute with String type.
To generate a text box, we use this syntax:
This command will generate a text box with name and id is name
To generate a text area, we use this syntax:
This command will generate a text area with name and id is about
To generate a hidden field, we use this syntax:
This command will generate a hidden field with name and id is hidden
Only one thing need to make attention is the annotation @ModelAttribute("user"), it means that the form bean is named "user"
References:
In this article, I will show you how to bind form data by using:
- <form:input> for a text box
- <form:textarea> for a text area
- <form:hidden> for a hidden field
1. Form Bean
First let have a look to beanpublic class User { // a text box private String name; // textarea private String about; // hidden private String hidden;.... }
To store data of these tags, we need only the attribute with String type.
2. Form Tags
To create a form, we use this syntax:<form:form action="/textbox/modifyUser" method="POST" commandName="user">
action="/textbox/modifyUser" means that this form submit data to action with request mapping is "modifyUser"
mothod="POST" means this form for posting data
commandName="user" means the form bean is named "user", the default is "command"
mothod="POST" means this form for posting data
commandName="user" means the form bean is named "user", the default is "command"
To generate a text box, we use this syntax:
<form:input path="name" />
This command will generate a text box with name and id is name
To generate a text area, we use this syntax:
<form:textarea path="about" cols="15" rows="4"/>
This command will generate a text area with name and id is about
To generate a hidden field, we use this syntax:
<form:hidden path="hidden"/>
This command will generate a hidden field with name and id is hidden
3. In Controller
@RequestMapping(value = "/modifyUser", method = RequestMethod.GET) public ModelAndView modifyUser(@ModelAttribute("user") User user) { // do some thing here, e.g: update database, ... return new ModelAndView("viewUser", "user", user); }
Only one thing need to make attention is the annotation @ModelAttribute("user"), it means that the form bean is named "user"
References:
Source code:
- For the demonstration, please download source code from HERE
- My repository on Github, download ALL SOURCE code in this blog
No comments:
Post a Comment