Skip to content

Spring MVC form tags

  • form:form: form
  • form:input: input field
  • form:select: drop down list
  • form:option: Discrete values
  • form:options: LinkedHashMap
  • form:radiobutton: Discrete values
  • form:radiobuttons: LinkedHashMap
  • form:checkbox: multiple selection
  • form:errors: validation
<form:form action="processForm" modelAttribute="student"> <!-- Work with the "student" attribute -->
    First name:
    <form:input path="firstName" /> <!-- student.getFirstName() -->
    <br />

    Last name:
    <form:input path="lastName" /> <!-- student.getLastName() -->
    <form:errors path="lastName" cssClass="error" /> <!-- Display error message if the validation does not pass -->
    <br />

    Country:
    <form:select path="country">
        <!-- <form:option value="Brazil" label="Brazil"/> -->
        <!-- <form:option value="France" label="France"/> -->
        <!-- <form:option value="Germany" label="Germany"/> -->
        <!-- <form:option value="India" label="India"/> -->
        <form:options items="${student.countryOptions}" /> <!-- Get the countries from the linkedHashMap -->
    </form:select>
    <br />

    Favorite language:
    Java <form:radiobutton path="favoriteLanguage" value="Java" /> <!-- Calls student.setFavoriteLanguage("Java") -->
    C# <form:radiobutton path="favoriteLanguage" value="C#" />
    PHP <form:radiobutton path="favoriteLanguage" value="PHP" />
    Ruby <form:radiobutton path="favoriteLanguage" value="Ruby" />
    <br />

    Operating Systems:
    Linux: <form:checkbox path="operatingSystems" value="Linux" /> <!-- property must be an array! Multiple options can be selected -->
    MacOS: <form:checkbox path="operatingSystems" value="MacOS" />
    Windows: <form:checkbox path="operatingSystems" value="Windows" />

    <input type="submit" value="Submit" /> <!-- Calls: student.setFirstName() and student.setLastName() -->

</form:form>
@RequestMapping("/showForm")
public String showForm(Model theModel) {
    // create student object
    Student theStudent = new Student();

    // add student object to the Model
    theModel.addAttribute("student", theStudent); // student attribute is now an object instance

    return "student-form";
}

@RequestMapping("/processForm")
public String processForm(@ModelAttribute("student") Student theStudent) { // Populate the theStudent object with data from the request model
    System.out.println("Student: " + theStudent.getFirstName() + " " + theStudent.getLastName());
    return "student-confirmation";
}