Spring MVC Tutorial

Core Spring MVC

Spring MVC - Annotation

Spring MVC - Form Handling

Spring MVC with JSTL

Spring MVC with REST API

Spring MVC with Database

Spring MVC - Form Text Field

In Spring MVC, the text field is one of the basic form components used to capture user input. The Spring Form tag library provides a convenient way to create and bind text fields to model attributes.

Here's how you can work with text fields using Spring MVC:

1. Model:

Let's say you have a simple User model with a username field:

public class User {
    private String username;

    // Getters and setters...
}

2. Controller:

Create a controller to handle the form:

@Controller
@RequestMapping("/user")
public class UserController {

    @GetMapping("/register")
    public String showForm(Model model) {
        model.addAttribute("user", new User());
        return "registerForm";
    }

    @PostMapping("/register")
    public String submitForm(@ModelAttribute User user, Model model) {
        // Process the form...
        model.addAttribute("user", user);
        return "registrationSuccess";
    }
}

3. JSP View:

In the JSP view (registerForm.jsp), you can use the form:input tag to create a text field:

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>

<form:form method="POST" modelAttribute="user">
    Username: <form:input path="username" />
    <br>
    <input type="submit" value="Register" />
</form:form>

Here:

  • The form:input tag is used to generate an HTML input field of type text.
  • The path attribute specifies the property of the model attribute (user in this case) to which this input field should be bound. When the form is submitted, the entered value in the text field will be bound to the username property of the User object.

4. Displaying the Result:

After form submission, you can display the submitted value in a result JSP (registrationSuccess.jsp):

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<h1>Registration Success</h1>
<p>Welcome, <c:out value="${user.username}" />!</p>

5. Validation:

It's crucial to validate user inputs. For instance, if you want to ensure that the username is not empty, you can:

  • Use Bean Validation annotations in your model:
public class User {
    @NotEmpty(message = "Username is required.")
    private String username;

    // Getters and setters...
}
  • Adjust your controller to handle validation:
@PostMapping("/register")
public String submitForm(@Valid @ModelAttribute User user, BindingResult result, Model model) {
    if (result.hasErrors()) {
        return "registerForm";
    }
    model.addAttribute("user", user);
    return "registrationSuccess";
}
  • Display validation errors in registerForm.jsp:
<form:errors path="username" cssClass="error" />

By using the Spring Form tag library, creating and processing text fields becomes efficient and streamlined, ensuring easy binding, validation, and error handling.

  1. Spring MVC Form Text Field Example:

    • Description: This is a basic example illustrating the use of text fields in a Spring MVC form. It involves creating a form with <input> elements of type text and processing the form data on the server.

    • Code Snippet: (HTML Form with Text Field)

      <!-- textFieldForm.jsp -->
      <form action="/submitForm" method="post">
          <label for="username">Username:</label>
          <input type="text" id="username" name="username" />
          <button type="submit">Submit</button>
      </form>
      
  2. Handling Text Fields in Spring MVC Forms:

    • Description: This example expands on the basic text field example by providing a Spring MVC controller method to handle the submitted form data.

    • Code Snippet: (Controller Method)

      @Controller
      public class FormController {
          @PostMapping("/submitForm")
          public String processForm(@RequestParam("username") String username) {
              // Process text field value
              return "formResult";
          }
      }
      
  3. Text Field Binding in Spring MVC:

    • Description: This example demonstrates how to use data binding to bind the entered text field value directly to a model attribute in Spring MVC.

    • Code Snippet: (Model Attribute and Controller Method)

      public class UserForm {
          private String username;
      
          // Getter and Setter
      }
      
      @Controller
      public class BindingController {
          @PostMapping("/submitForm")
          public String submitForm(@ModelAttribute("userForm") UserForm userForm) {
              // Access userForm.getUsername() for text field value
              return "formResult";
          }
      }
      
  4. Populating Text Fields in Spring MVC:

    • Description: This example involves dynamically populating the value of a text field in a Spring MVC form.

    • Code Snippet: (Controller Method with Model Attribute)

      @Controller
      public class TextFieldsController {
          @ModelAttribute("defaultUsername")
          public String getDefaultUsername() {
              // Logic to fetch default username from a data source
              return "defaultUser";
          }
      
          @GetMapping("/showForm")
          public String showForm(Model model) {
              model.addAttribute("userForm", new UserForm());
              return "textFieldForm";
          }
      
          @PostMapping("/submitForm")
          public String submitForm(@ModelAttribute("userForm") UserForm userForm) {
              // Access userForm.getUsername() for entered text field value
              return "formResult";
          }
      }
      
  5. Spring MVC Text Field Validation:

    • Description: This example includes validation for the text field value in the Spring MVC form.

    • Code Snippet: (Model Attribute with Validation)

      public class UserForm {
          @NotBlank(message = "Username is required")
          @Size(max = 20, message = "Username must be less than 20 characters")
          private String username;
      
          // Getter and Setter
      }
      
  6. Text Field with Thymeleaf in Spring MVC:

    • Description: This example demonstrates how to use Thymeleaf to render and handle text fields in a Spring MVC application.

    • Code Snippet: (Thymeleaf Text Field)

      <!-- textFieldForm.html -->
      <form action="/submitForm" method="post" th:object="${userForm}">
          <label for="username">Username:</label>
          <input type="text" id="username" name="username" th:field="*{username}" />
          <button type="submit">Submit</button>
      </form>
      
  7. Dynamic Text Fields in Spring MVC:

    • Description: This example goes a step further by dynamically updating the value of a text field based on user interactions.

    • Code Snippet: (Controller Method with Dynamic Value)

      @Controller
      public class DynamicTextFieldsController {
          @GetMapping("/getDynamicValue")
          @ResponseBody
          public String getDynamicValue(@RequestParam("category") String category) {
              // Logic to fetch dynamic value based on the selected category
              return "dynamicValue";
          }
      }
      
  8. Spring MVC Text Field Size and Maxlength:

    • Description: This example illustrates how to set the size and maxlength attributes for a text field in a Spring MVC form.

    • Code Snippet: (Text Field Attributes)

      <!-- Set size and maxlength for the text field -->
      <input type="text" id="username" name="username" size="30" maxlength="50" />
      
  9. Selecting Default Value in Spring MVC Text Field:

    • Description: This example shows how to pre-fill a default value for a text field in a Spring MVC form.

    • Code Snippet: (Pre-filled Text Field)

      <!-- Pre-filled text field -->
      <input type="text" id="username" name="username" value="defaultUser" />
      
  10. Processing Text Field Values in Spring MVC Controller:

    • Description: This example includes a Spring MVC controller method that processes the submitted form data, including the entered text field value.

    • Code Snippet: (Controller Method)

      @Controller
      public class FormController {
          @PostMapping("/submitForm")
          public String processForm(@RequestParam("username") String username) {
              // Process entered text field value
              return "formResult";
          }
      }