Showing posts with label Spring Form Tag. Show all posts
Showing posts with label Spring Form Tag. Show all posts

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:

Monday, February 18, 2013

SpringMVC Form Tag Lib Checkbox + Checkboxs

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:checkbox>
  • <form:checkboxes>

1. Form Bean


public class User {

 // a check box
 private boolean married;

 // checkboxs
 private String[] hobbies;
....
}

To store status of multi checkbox, we must use a array of String.

2. Form Tags


To generate a checkbox, we use this syntax:
<form:label path="married">Married</form:label>
<form:checkbox path="married" /> 

  • form:label path="married" means generate a label for user.married
  • form:checkbox path="married" generated the checkbox

To generate a list of checkbox button, we use this syntax:
<form:checkboxes 
 path="hobbies" 
 items="${lstHobby}" 
/>

  • path="hobbies" means the selected checkbox values bind to hobbies attribute
  • items="${lstHobby}" means the check value and checkbox label are stored in lstHobby

4. In Controller

We initialize the item list in GET method
@RequestMapping(value = "/modifyUser", method = RequestMethod.GET)
public ModelAndView modifyUser() {

  Map<String, String> lstHobby = new HashMap<String, String>();
 lstHobby.put("1", "Music");
 lstHobby.put("2", "Game");
 lstHobby.put("3", "Reading");

 ModelAndView modelView = new ModelAndView("modifyUser");
 modelView.addObject("lstHobby", lstHobby);
 modelView.addObject("user", this.user);
  
 return modelView;
} 

As you see, the lstHobby is a Map, the key of Map is checkbox value and the value of Map is checkbox label

Note
The order of items is not guaranteed in JSP

References:
Source code:
  • For the demonstration, please download source code from HERE
  • My repository on Github

SpringMVC Form Tag Lib Radio + Radios

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:radiobutton>
  • <form:radiobuttons>

1. Form Bean


public class User {

     // a radio
 private String sex;
 
 // radios
 private String skin;
....
}

2. Form Tags


To generate a radio button, we use this syntax:
<form:radiobutton 
 path="sex" 
 value="M"
/> 

  • path="sex" means the selected radio value binds to sex attribute
  • value="M" the label of this radio

To generate a list of radio button, we use this syntax:
<form:radiobuttons 
    path="skin"
    items="${lstSkin}"
/>

  • path="skin" means the selected radio value binds to sex attribute
  • items="${lstSkin}" means the radio value and radio lable are stored in lstSkin

4. In Controller

We initialize the item list in GET method
@RequestMapping(value = "/modifyUser", method = RequestMethod.GET)
public ModelAndView modifyUser() {

 Map<String, String> lstSkin = new HashMap<String, String>();
 lstSkin.put("1", "White");
 lstSkin.put("2", "Black");
 lstSkin.put("3", "Brown");
 lstSkin.put("4", "Orange");
  
 ModelAndView modelView = new ModelAndView("modifyUser");
 modelView.addObject("lstSkin", lstSkin);
 modelView.addObject("user", this.user);
  
 return modelView;
} 

As you see, the lstSkin is a Map, the key of Map is radio value and the value of Map is radio label

Note
The order of items is not guaranteed in JSP

References:
Source code:
  • For the demonstration, please download source code from HERE
  • My repository on Github

SpringMVC Form Tag Lib Select + Option

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:select>
  • <form:option>
  • <form:options>

1. Option object

This object contain a pair value of each item in combo box or list box. It composes of item value and item label.

public class Option {

    private String  itemValue;

    private String  itemLabel;
...
}

2. Form Bean


public class User {

    // for a dropdown by using select tag
    private String skill1;

    // for a dropdown by using select, option and options tag
    private String skill2;

    // for multi select list box
    private String[] skills;
....
}

As above code, the attribute skills is used in binding a multi select list box.

3. Form Tags


To generate a dropdown box, we use this syntax:
<form:select 
    path="skill1" 
    items="${lstSkill}" 
    itemValue="itemValue" 
    itemLabel="itemLabel" 
/> 

  • path="skill1" means the selected value binds to skill1 attribute
  • items="${lstSkill}" means the items displayed in dropdown is stored in lstSkill
  • itemValue="itemValue" means the value of each item comes from field itemValue of Option object
  • itemLabel="itemLabel" means the label of each item is stored in field itemLabel of Option object

Another way to generate a combo box:
<form:select path="skill2">
    <form:option value="-" label="--Please Select"/>
    <form:options path="skill2" items="${lstSkill}" itemValue="itemValue" itemLabel="itemLabel" />
</form:select>


To generate a multi select list box, we use this syntax:
<form:select 
    path="skills"     
    multiple="true" 
    items="${lstSkill}" 
    itemValue="itemValue" 
    itemLabel="itemLabel" 
/>

  • path="skills", here the skills is an array of string
  • multiple="true"

4. In Controller

We initialize the item list in GET method
@RequestMapping(value = "/modifyUser", method = RequestMethod.GET)
public ModelAndView modifyUser() {

        /* We use a list of Option instead of Map */
        List<Option> lstSkill = new ArrayList<Option>();
 
        lstSkill.add(new Option("1", "Java"));
        lstSkill.add(new Option("2", "C#"));
        lstSkill.add(new Option("3", "PHP"));
        lstSkill.add(new Option("4", "C++"));
  
        ModelAndView modelView = new ModelAndView("modifyUser");
        modelView.addObject("lstSkill", lstSkill);
        modelView.addObject("user", this.user);
        return modelView;
} 

References:
Source code:
  • For the demonstration, please download source code from HERE
  • My repository on Github

Sunday, February 17, 2013

SpringMVC Form Errors Tag and Validator Interface

In this article, we will discuss about <form:errors> tag and the Spring's Validator Interface

1. Create a new validator

Spring provides us a Validator interface that we can use to validate objects

For example, we implement a new validator to validate this User object
public class User {

    private String firstName;
    
    private String lastName;
    
    private String password;
    
    private String repassword;

....

}

The implementation of a validator looks like that

public class UserValidator implements Validator {

    @Override
    public boolean supports(Class<?> clazz) {
        return User.class.isAssignableFrom(clazz);
    }

    @Override
    public void validate(Object obj, Errors errors) {
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "firstName", "required.firstName", "Firstname is required.");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "lastName", "required.lastName", "LastName is required.");
        
        User user = (User) obj;
        if (!user.getPassword().equals(user.getRepassword())) {
            errors.rejectValue("password", "notmatch.password");
        }
    }
}
Tip: To reject a field value, we can do like that:
errors.rejectValue("password", "notmatch.password");
The first argument is the field name, the second is the message.

2. Configure validator in controller


We need only 2 steps to enable the validation feature in controller:
  • Implement the function initBinder, this function will be invoked by framework when it binds data.
  • Add a binding result attribute to the action which you want to apply the validation, the <form:errors> tag looks at this attribute when it renders the error messages on form
In my controller:
@Autowired
@Qualifier("userValidator")
private UserValidator validator;

@InitBinder
protected void initBinder(WebDataBinder binder) {
    binder.setValidator(this.validator);
}

@RequestMapping(value = "/modifyUser", method = RequestMethod.POST)
public ModelAndView updateUser(@ModelAttribute("user") User user, BindingResult bindingResult) {
    validator.validate(user, bindingResult);
    if (bindingResult.hasErrors()) {
        // show errors
        return new ModelAndView("modifyUser", "user", user);
    } else {
        // success
        return new ModelAndView("viewUser", "user", user);
    }    
}

  • The Spring version used in this example is 3.x
  • The validator will be passed to controller automatically through @Autowired annotation
  • In initBinder function, we tell to Spring that to validate data of this controller, please use the UserValidator
  • At line 11, we have a new attribute with type BindingResult, this attribute will contain our binding result, and used by form:errors tag

3. Prepare the JSP

To show the errors of a field, we use this structure: <form:errors path="firstName"/>

To show the errors of all field, we set the value of path to * <form:errors path="*" />

For example:
<tr>
    <td><form:label path="firstname=">First Name<td>
    <td>
        <form:input path="firstName" />
        <form:errors path="firstName" class="errors" />
    </td>
</tr> 

References:
Source code:
  • For the demonstration, please download source code from HERE
  • My repository on Github