Tuesday, February 19, 2013

SpringMVC Form Tag Lib Input + Textarea

For binding data on a jsp page to a form, one of the easiest ways is using spring form tag.
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 bean

public 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"

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:

No comments:

Post a Comment