Spring MVC Form Submit Example

This example will show you how to implement spring mvc form elements and how to process form submit action. It use spring form:radiobutton to implement html radio button, form:checkbox to implement html checkbox, form:select to implement html drop down list.

1. Spring MVC Form Submit Example.

First let us look at the form submit example page. There are two input textbox, one radiobutton group, one checkbox group and one dropdown list in the employee info submit form page. When user click the Add Employee button, it will submit the form data to spring mvc controller and then display user input in the result page.

spring mvc form submit example

2. Spring MVC Form Submit Example Source Code.

spring mvc form submit example source files

2.1 Spring Project Context Configuration Java Class.

This java class is used to configure spring project context beans, such as MessageResource bean to get project i18n messages, ResourceBundleResolver bean to render jsp pages to client browser.

ContextConfig.java

package com.dev2qa.mvc.submitform.config;

import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.ResourceBundleViewResolver;

@EnableWebMvc
@Configuration
@ComponentScan(basePackages="com.dev2qa.mvc")
public class ContextConfig extends WebMvcConfigurerAdapter {

    /* Create a MessageSource bean to get message from message files, for i18n purpose. */
    @Bean(name = "messageSource")
    public MessageSource getMessageSource() {
        ReloadableResourceBundleMessageSource ret = new ReloadableResourceBundleMessageSource();

        // Set the base name for the messages properties file. All the messages.perperties file are saved in src/main/resources/config folder.
        ret.setBasename("classpath:config/messages");

        ret.setCacheSeconds(1);

        ret.setUseCodeAsDefaultMessage(true);

        ret.setDefaultEncoding("utf-8");

        return ret;
    }

    /* Create a ResourceBundleViewResolver object, this object will use the view class and jsp page mapping configuration saved in src/main/resources/config/views.properties file. */
    @Bean(name="bundleViewResolver")
    public ResourceBundleViewResolver getBundleViewResolver() {

        ResourceBundleViewResolver ret = new ResourceBundleViewResolver();

        ret.setBasename("config.views");

        ret.setOrder(0);

        return ret;
    }
}

2.2 Spring Project Dispatcher Servlet Java Class.

ContextDispatcherServlet.java

package com.dev2qa.mvc.submitform.config;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

@Configuration
public class ContextDispatcherServlet implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {

        AnnotationConfigWebApplicationContext dispatcherServletContext = new AnnotationConfigWebApplicationContext();

        dispatcherServletContext.register(ContextConfig.class);

        DispatcherServlet dispatcherServlet = new DispatcherServlet(dispatcherServletContext);

        // Create a servlet dynamically.
        ServletRegistration.Dynamic dispatcher = servletContext.addServlet("DispatcherServlet", dispatcherServlet);

        dispatcher.setLoadOnStartup(1);

        // Add servlet mapping url. All url end with .html will be processed by this servlet.
        dispatcher.addMapping("*.html");
    }
}

2.3 Spring Submit Form Example Controller Java Class.

EmployeeFormController.java

package com.dev2qa.mvc.submitform.controller;

import java.util.ArrayList;
import java.util.List;

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;

import com.dev2qa.mvc.submitform.dto.EmployeeInfoDTO;

/* When request http://localhost:8080/SpringMVCSubmitForm/employee.html will invoke this controller's methods. */
@Controller
@RequestMapping("/employee.html")
public class EmployeeFormController {

    /* Model attribute name. "employeeInfo" attribute save submit form data. 
       "departmentList" attribute save department dropdown list. */
    public static final String EMPLOYEE_INFO = "employeeInfo";
    public static final String DEPARTMENT_LIST = "departmentList";

    // Save department values in list.
    public static List<String> departmentList = new ArrayList<String>();
    static {
        departmentList.add("Development");
        departmentList.add("Quality Assurance");
        departmentList.add("Sales");
        departmentList.add("Market");
        departmentList.add("Human Resource");
    }

    /* When request the url in GET method. */
    @RequestMapping(method=RequestMethod.GET)
    public String displayEmployeeInfoInput(Model model) {

        EmployeeInfoDTO employeeInfoDto = new EmployeeInfoDTO();

        model.addAttribute(EMPLOYEE_INFO, employeeInfoDto);
        model.addAttribute(DEPARTMENT_LIST, departmentList);

        return "employee_info_input";
    }

    /* When request the url in POST method. Please note @ModelAttribute name should be same with the <form:form modelAttribute value in jsp file.*/
    @RequestMapping(method=RequestMethod.POST)
    public String displayEmployeeInfo(Model model, @ModelAttribute(EMPLOYEE_INFO) EmployeeInfoDTO employeeInfo) {

        model.addAttribute(EMPLOYEE_INFO, employeeInfo);

        return "employee_info_display";
    }
}

2.4 Data Transfer Object Java File.

The DTO ( Data Transfer Object ) is used to transfer data between client and server. It will pass submitted employee data to backend spring controller, it also can be saved as model’s attribute to render data in view ( jsp ) pages.

READ :   Spring Boot Hello World Example In STS

EmployeeInfoDTO.java

package com.dev2qa.mvc.submitform.dto;

public class EmployeeInfoDTO {

    private String employeeName = "";

    private String employeeEmail = "";

    private String employeeSex = "";

    private String employeeHobby = "";

    private String employeeDepartment = "";

    public String getEmployeeName() {
        return employeeName;
    }

    public void setEmployeeName(String employeeName) {
        this.employeeName = employeeName;
    }

    public String getEmployeeEmail() {
        return employeeEmail;
    }

    public void setEmployeeEmail(String employeeEmail) {
        this.employeeEmail = employeeEmail;
    }

    public String getEmployeeSex() {
        return employeeSex;
    }

    public void setEmployeeSex(String employeeSex) {
        this.employeeSex = employeeSex;
    }

    public String getEmployeeHobby() {
        return employeeHobby;
    }

    public void setEmployeeHobby(String employeeHobby) {
        this.employeeHobby = employeeHobby;
    }

    public String getEmployeeDepartment() {
        return employeeDepartment;
    }

    public void setEmployeeDepartment(String employeeDepartment) {
        this.employeeDepartment = employeeDepartment;
    }
}

2.5 Message Properties Files.

Message properties files are used to save internationalization messages, this example only use english to demo, so only contains messages.properties.

messages.properties

employee_info_form_title=Employee Info Input Page
employee_info_form_desc=Input employee info in below form and click add button to submit.

employee_info_display_title=Employee Info Display Page
employee_info_display_desc=Below are the employee's information you just input.

employee_info_name=User Name:
employee_info_email=Email:
employee_info_sex=Sex:
employee_info_hobby=Hobby:
employee_info_department=Department:

2.6 JSP View Resolve Configuration File.

This file contains view name and jsp page file path mappings. When you return a view name in spring controller request mapping method. Spring framework will resolve the view name to the related jsp page and render the page to client.

# View definition for spring submit form example.
employee_info_input.(class)=org.springframework.web.servlet.view.JstlView
employee_info_input.url=/pages/employee_info_input.jsp

employee_info_display.(class)=org.springframework.web.servlet.view.JstlView
employee_info_display.url=/pages/employee_info_display.jsp

2.7 Employee Info Input Form Page.

employee_info_input.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title><spring:message code="employee_info_form_title" /></title>
</head>
<body>
    <h3><spring:message code="employee_info_form_desc" /></h3>

    <form:form action="${pageContext.request.contextPath}/employee.html" modelAttribute="employeeInfo" method="post">

        <spring:message code="employee_info_name" />&nbsp;<form:input path="employeeName"/><br/><br/>
        <spring:message code="employee_info_email" />&nbsp;<form:input path="employeeEmail"/><br/><br/>
        <spring:message code="employee_info_sex" />&nbsp;<form:radiobutton path="employeeSex" value="Male"/>Male<form:radiobutton path="employeeSex" value="Female"/>Female<br/><br/>
        <spring:message code="employee_info_hobby" />&nbsp;<form:checkbox path="employeeHobby" value="Coding"/>Coding<form:checkbox path="employeeHobby" value="Film"/>Film<form:checkbox path="employeeHobby" value="Football"/>Football<br/><br/>
        <spring:message code="employee_info_department" />&nbsp;<form:select path="employeeDepartment" items="${departmentList}" /><br/><br/>
        <input type="submit" value="Add Employee"/>

    </form:form>

</body>
</html>

2.8 Employee Info Display Page.

employee_info_display.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title><spring:message code="employee_info_display_title" /></title>
</head>
<body>
<h3><spring:message code="employee_info_display_desc" /></h3>

<spring:message code="employee_info_name" />&nbsp;${employeeInfo.employeeName}<br/><br/>
<spring:message code="employee_info_email" />&nbsp;${employeeInfo.employeeEmail}<br/><br/>
<spring:message code="employee_info_sex" />&nbsp;${employeeInfo.employeeSex}<br/><br/>
<spring:message code="employee_info_hobby" />&nbsp;${employeeInfo.employeeHobby}<br/><br/>
<spring:message code="employee_info_department" />&nbsp;${employeeInfo.employeeDepartment}<br/><br/>

</html>

2.9 pom.xml.

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>org.springframework.samples.service.service</groupId>
    <artifactId>SpringMVCSubmitForm</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>

    <!-- Spring framework used constants variable  -->
    <properties>
        <spring.version>5.0.0.BUILD-SNAPSHOT</spring.version>
        <servlet.api.version>3.1.0</servlet.api.version>
    </properties>


    <repositories>
        <!-- This repository is where the spring framework dependencies jar file download. -->
        <repository>
            <id>spring-snapshots</id>
            <name>Spring Snapshots</name>
            <url>https://repo.spring.io/libs-snapshot</url>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </repository>
    </repositories>

    <dependencies>
        <!-- Below are the basic spring container dependencies library. -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <!-- Below dependency is used for spring mvc framework. -->
        <!-- 
        <dependency>
             <groupId>org.springframework</groupId>
             <artifactId>spring-web</artifactId>
             <version>${spring.version}</version>
          </dependency>
          -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <!-- Below dependency is used for servlet and jsp. -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>${servlet.api.version}</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>javax.servlet.jsp-api</artifactId>
            <version>2.3.1</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>

        <dependency>
            <groupId>taglibs</groupId>
            <artifactId>standard</artifactId>
            <version>1.1.2</version>
        </dependency>

    </dependencies>

    <build>
        <finalName>spring-mvc-example</finalName>
        <plugins>
            <!-- Because this project do not use web.xml so need below settings. -->
            <plugin>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.3</version>
                <configuration>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.apache.tomcat.maven</groupId>
                <artifactId>tomcat7-maven-plugin</artifactId>
                <version>2.2</version>
                <configuration>
                    <username>tomcat</username>
                    <password>tomcat</password>
                    <!-- update true will override the existing deployed war file in tomcat -->
                    <update>true</update>
                </configuration>
            </plugin>

        </plugins>
    </build>
</project>

Reference

  1. Spring MVC Full Java Based Configuration Example
  2. Spring MVC i18n Java Config Example

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.