Form Handling in Spring MVC Framework

This project will demonstrate how to use Form Handling in Spring MVC Framework

  • SpringMVCFramework
    • src/main/java
      • com.demo
        • SpringMVCFramework.java
      • com.demo.controllers
        • AccountController.java
      • com.demo.entities
        • Account.java
        • Language.java
        • Role.java
    • src/main/resources
      • static
      • templates
      • application.properties
    • src
      • main
        • webapp
          • WEB-INF
            • views
              • account
                • index.jsp
                • success.jsp
    • pom.xml
package com.demo;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    @SpringBootApplication
    public class SpringMVCFramework {
    
        public static void main(String[] args) {
            SpringApplication.run(SpringMVCFramework.class, args);
        }
    }
package com.demo.controllers;

import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.demo.entities.Account;
import com.demo.entities.Language;
import com.demo.entities.Role;

@Controller
@RequestMapping(value = "account")
public class AccountController {

    @RequestMapping(method = RequestMethod.GET)
    public String index(ModelMap modelMap) {

        List<Language> languages = new ArrayList<Language>();
        languages.add(new Language("lang1", "Language 1"));
        languages.add(new Language("lang2", "Language 2"));
        languages.add(new Language("lang3", "Language 3"));
        languages.add(new Language("lang4", "Language 4"));
        modelMap.put("languages", languages);

        List<Role> roles = new ArrayList<Role>();
        roles.add(new Role("r1", "Role 1"));
        roles.add(new Role("r2", "Role 2"));
        roles.add(new Role("r3", "Role 3"));
        roles.add(new Role("r4", "Role 4"));
        modelMap.put("roles", roles);

        Account account = new Account();
        account.setId("acc1");
        account.setGender("male");
        account.setStatus(true);
        account.setLanguages(new String[] { "lang2", "lang4" });
        modelMap.put("account", account);
        return "account/index";
    }

    @RequestMapping(value = "save", method = RequestMethod.POST)
    public String save(@ModelAttribute(value = "account") Account account, ModelMap modelMap) {
        modelMap.put("account", account);
        return "account/success";
    }

}
package com.demo.entities;

public class Account {

    private String id;
    private String username;
    private String password;
    private String description;
    private boolean status;
    private String[] languages;
    private String gender;
    private String role;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public boolean isStatus() {
        return status;
    }

    public void setStatus(boolean status) {
        this.status = status;
    }

    public String[] getLanguages() {
        return languages;
    }

    public void setLanguages(String[] languages) {
        this.languages = languages;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public String getRole() {
        return role;
    }

    public void setRole(String role) {
        this.role = role;
    }

}
package com.demo.entities;

public class Language {

    private String id;
    private String name;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Language(String id, String name) {
        this.id = id;
        this.name = name;
    }

    public Language() {
    }

}
package com.demo.entities;

public class Role {

    private String id;
    private String name;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Role(String id, String name) {
        this.id = id;
        this.name = name;
    }

    public Role() {
    }

}
spring.mvc.view.prefix = /WEB-INF/views/
spring.mvc.view.suffix = .jsp
spring.mvc.static-path-pattern=/resources/**

server.port=9596
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="s" uri="http://www.springframework.org/tags/form" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Register Account</title>
</head>
<body>

    <h3>Register Account</h3>
    <s:form method="post" commandName="account"
        action="${pageContext.request.contextPath}/account/save">
        <table>
            <tr>
                <td>Username</td>
                <td>
                    <s:input path="username"/>
                </td>
            </tr>
            <tr>
                <td>Password</td>
                <td>
                    <s:password path="password"/>
                </td>
            </tr>
            <tr>
                <td valign="top">Description</td>
                <td>
                    <s:textarea path="description" cols="20" rows="5"/>
                </td>
            </tr>
            <tr>
                <td valign="top">Gender</td>
                <td>
                    <s:radiobutton path="gender" value="male"/> Male
                    <br>
                    <s:radiobutton path="gender" value="female"/> Female
                </td>
            </tr>
            <tr>
                <td>Status</td>
                <td>
                    <s:checkbox path="status"/>
                </td>
            </tr>
            <tr>
                <td>Languages</td>
                <td>
                    <s:checkboxes path="languages"
                                    items="${languages }"
                                    itemLabel="name"
                                    itemValue="id" />
                </td>
            </tr>
            <tr>
                <td>Role</td>
                <td>
                    <s:select path="role"
                                items="${roles }"
                                itemLabel="name"
                                itemValue="id"></s:select>
                </td>
            </tr>
            <tr>
                <td>&nbsp;</td>
                <td>
                    <input type="submit" value="Save">
                    <s:hidden path="id"/>
                </td>
            </tr>
        </table>
    </s:form>

</body>
</html>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Success View</title>
</head>
<body>

    <h3>Account Information</h3>
    <table cellpadding="2" cellspacing="2" border="1">
        <tr>
            <td>Id</td>
            <td>${account.id }</td>
        </tr>
        <tr>
            <td>Username</td>
            <td>${account.username }</td>
        </tr>
        <tr>
            <td>Password</td>
            <td>${account.password }</td>
        </tr>
        <tr>
            <td valign="top">Description</td>
            <td>${account.description }</td>
        </tr>
        <tr>
            <td valign="top">Gender</td>
            <td>${account.gender }</td>
        </tr>
        <tr>
            <td>Status</td>
            <td>${account.status }</td>
        </tr>
        <tr>
            <td>Languages</td>
            <td>
                <c:forEach var="language" items="${account.languages }">
                    ${language }
                    <br>
                </c:forEach>
            </td>
        </tr>
        <tr>
            <td>Role</td>
            <td>${account.role }</td>
        </tr>
    </table>

</body>
</html>
<?xml version="1.0" encoding="UTF-8"?>
<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>com.demo</groupId>
    <artifactId>LearnSpringMVCWithRealApps</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>LearnSpringMVCWithRealApps</name>
    <description>Learn Spring MVC with Real Apps</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.2.RELEASE</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>

        <!-- Spring MVC  -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!-- JSTL tag lib -->
        <dependency>
            <groupId>javax.servlet.jsp.jstl</groupId>
            <artifactId>javax.servlet.jsp.jstl-api</artifactId>
            <version>1.2.1</version>
        </dependency>

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

        <!-- Tomcat for JSP rendering -->
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

Screenshots