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 - Capture and Display the Data from the Registration Form

Spring MVC (Model-View-Controller) is a framework for building web applications in Java. It follows the MVC architectural pattern and builds on the Java Servlet API. In this example, we'll go over how to create a simple registration form using Spring MVC, capture the data, and display it.

Directory Structure

src/main
├── java
│   └── com
│       └── example
│           └── demo
│               └── controller
│                   └── RegistrationController.java
├── resources
│   └── application.properties
└── webapp
    ├── WEB-INF
    │   ├── views
    │   │   └── registrationForm.jsp
    │   └── web.xml
    └── index.jsp

1. Maven Dependencies (pom.xml)

Add the following dependencies to your Maven pom.xml file.

<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>5.3.10</version>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>4.0.1</version>
    </dependency>
</dependencies>

2. The Model

Create a simple Java class to hold the user data.

public class User {
    private String username;
    private String password;
    private String email;

    // Getters and setters
}

3. The Controller (RegistrationController.java)

package com.example.demo.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class RegistrationController {

    @RequestMapping(value = "/register", method = RequestMethod.GET)
    public String showRegistrationForm(Model model) {
        model.addAttribute("user", new User());
        return "registrationForm";
    }

    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public String submitRegistration(@ModelAttribute("user") User user, Model model) {
        model.addAttribute("user", user);
        return "registrationSuccess";
    }
}

4. The View (registrationForm.jsp)

Create a JSP page to display the registration form.

<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<body>
    <form:form modelAttribute="user" action="register" method="post">
        Username: <form:input path="username" />
        Password: <form:password path="password" />
        Email: <form:input path="email" />
        <input type="submit" value="Register" />
    </form:form>
</body>
</html>

5. Display the Data (registrationSuccess.jsp)

Create another JSP page to display the user data after successful registration.

<html>
<body>
    Registration successful!
    <br/>
    Username: ${user.username}
    <br/>
    Email: ${user.email}
</body>
</html>

6. Configure Spring MVC (web.xml and servlet-context.xml)

Add Spring MVC configuration to web.xml and create a servlet-context.xml.

<!-- web.xml -->
<web-app>
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/servlet-context.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>
<!-- servlet-context.xml -->
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="...">
    <context:component-scan base-package="com.example.demo.controller" />
    <mvc:annotation-driven />

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/" />
        <property name="suffix" value=".jsp" />
    </bean>
</beans>

Run your application and go to http://localhost:8080/register to see the registration form. Fill it out, and upon submission, you should be redirected to the "Registration successful" page displaying the data you've entered.

  1. Spring MVC registration form example:

    In a Spring MVC registration form example, you would typically have a JSP page for the form and a controller to handle form submissions. Here's a simple example:

    <!-- registration-form.jsp -->
    <form action="register" method="post">
        Username: <input type="text" name="username" /><br />
        Password: <input type="password" name="password" /><br />
        <input type="submit" value="Register" />
    </form>
    
    // RegistrationController.java
    @Controller
    public class RegistrationController {
    
        @RequestMapping(value = "/register", method = RequestMethod.POST)
        public String registerUser(@RequestParam String username, @RequestParam String password) {
            // Process registration logic
            return "registration-success"; // return success view name
        }
    }
    
  2. Display form data in Spring MVC view:

    To display form data in a Spring MVC view, you can use JSTL or Thymeleaf tags to access and display the submitted data.

    <!-- registration-success.jsp -->
    <p>Registration successful for ${username}!</p>
    
  3. Spring MVC form validation and submission:

    Form validation in Spring MVC involves using validation annotations and checking for validation errors in the controller. Here's a brief example:

    // RegistrationController.java
    @Controller
    public class RegistrationController {
    
        @PostMapping("/register")
        public String registerUser(@Valid @ModelAttribute RegistrationForm form, BindingResult result, Model model) {
            if (result.hasErrors()) {
                return "registration-form";
            }
    
            // Process registration logic
            model.addAttribute("username", form.getUsername());
            return "registration-success";
        }
    

    In this example, @Valid triggers validation based on the RegistrationForm class.

  4. Binding form data in Spring MVC:

    Form data can be bound to a command object in Spring MVC using the @ModelAttribute annotation. For example:

    public class RegistrationForm {
        private String username;
        private String password;
    
        // getters and setters
    }
    
    // RegistrationController.java
    @Controller
    public class RegistrationController {
    
        @PostMapping("/register")
        public String registerUser(@ModelAttribute RegistrationForm form) {
            // Process registration logic
            return "registration-success";
        }
    
  5. Spring MVC model attribute registration form:

    You can use the @ModelAttribute annotation to specify a model attribute in the controller method. This attribute will be automatically added to the model.

    @PostMapping("/register")
    public String registerUser(@ModelAttribute("registrationForm") RegistrationForm form) {
        // Process registration logic
        return "registration-success";
    
  6. Displaying user input in Spring MVC registration form:

    Displaying user input involves using JSTL or Thymeleaf tags to show the submitted data in the registration form after a submission attempt.

    <!-- registration-form.jsp -->
    <form action="register" method="post">
        Username: <input type="text" name="username" value="${param.username}" /><br />
        Password: <input type="password" name="password" /><br />
        <input type="submit" value="Register" />
    </form>
    

    This example uses ${param.username} to display the submitted username in the form.