DEV Community

Zar Li Hnin for Rey Tech Inc.

Posted on • Updated on

Form submitting and show results with Spring Boot

Overview

This tutorial is how to create and submit form with Spring Boot Application.

Necessary Environments

Let's start by the following steps.

  1. Create project with Spring Starter Project by using your IDE

  2. Add Dependencies

Thymeleaf is a Java library that is able to apply a set of transformations to template files in order to display data and/or text produced by your applications.
Spring Boot DevTools pick up the changes and restart the application.
Alt Text

  1. Project Structure

Alt Text

Let's start!

FormRegistrationApplication.java

package com.demo.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class FormRegistrationApplication {

    public static void main(String[] args) {
        SpringApplication.run(FormRegistrationApplication.class, args);
    }

}

pom.xml

Dependencies are look like this.
<?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>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.21.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.demo</groupId>
    <artifactId>form_registration</artifactId>
    <version>1.0</version>
    <name>form_registration</name>
    <description>Spring MVC tutorial</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</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>

Configuration.java

Constants data are expressed using list which are days,months,years.
package com.demo.example;

import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.List;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@org.springframework.context.annotation.Configuration
public class Configuration extends WebMvcConfigurerAdapter {


    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("home");
    }
    @Bean
    @Qualifier("subjects")
    public List<String> subjects(){
        return Arrays.asList("Burmese","English","Maths","Chemistry","Physics","Biology");
    }
    @Bean
    @Qualifier("days")
    public List<String> days(){
        return Arrays.asList("1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20","21","22","23","24","25","26","27","28","29","30","31");
    }
    @Bean
    @Qualifier("months")
    public List<String> months(){
        return Arrays.asList("1","2","3","4","5","6","7","8","9","10","11","12");
    }
    @Bean
    @Qualifier("years")
    public List<String> years(){
        return Arrays.asList("1998","1999","2000","2001","2002","2003");
    }

}

Student.java

The Student object in the following code contains fields such as grade,subjects,name,email,city,township,day,month and year that correspond to the form fields in the student result view and are used to capture the information from the form:
package com.demo.example.model;

import java.util.List;

public class Student {

    private Grade grade;
    private List<String> subjects;
    private String name;
    private String email;
    private String city;
    private String township;
    private List<String> day;
    private List<String> month;
    private List<String> year;

    public List<String> getSubjects() {
        return subjects;
    }
    public void setSubjects(List<String> subjects) {
        this.subjects = subjects;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public String getCity() {
        return city;
    }
    public void setCity(String city) {
        this.city = city;
    }
    public String getTownship() {
        return township;
    }
    public void setTownship(String township) {
        this.township = township;
    }
    public List<String> getDay() {
        return day;
    }
    public void setDay(List<String> day) {
        this.day = day;
    }
    public List<String> getMonth() {
        return month;
    }
    public void setMonth(List<String> month) {
        this.month = month;
    }
    public List<String> getYear() {
        return year;
    }
    public void setYear(List<String> year) {
        this.year = year;
    }
    public Grade getGrade() {
        return grade;
    }
    public void setGrade(Grade grade) {
        this.grade = grade;
    }
}

Grade.java

package com.demo.example.model;

public enum Grade {
   A,B,C,D,E
}

HomeController.java

Controller sends student information and show results.
package com.demo.example.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import com.demo.example.model.Grade;
import com.demo.example.model.Student;

@Controller
@RequestMapping("/form")
public class HomeController {
      @Autowired
      @Qualifier("subjects")
      private List<String> subjects;

      @Autowired
      @Qualifier("days")
      private List<String> days;

      @Autowired
      @Qualifier("months")
      private List<String> months;

      @Autowired
      @Qualifier("years")
      private List<String> years;

      @GetMapping
      public String get(ModelMap model){
          Student student=new Student();
          model.addAttribute("student", student);
          return "form";

      }
      @PostMapping
      public String post(Student dto, ModelMap map){
          map.put("result", dto);
          return "form";
      }

      @ModelAttribute("subjects")
      public List<String> subjects(){
          return subjects;
      }
      @ModelAttribute("days")
      public List<String> days(){
          return days;
      }
      @ModelAttribute("months")
      public List<String> months(){
          return months;
      }
      @ModelAttribute("years")
      public List<String> years(){
          return years;
      }
      @ModelAttribute("grades")
      public Grade [] grades(){
          return Grade.values();
      }

}

home.html

This is main page.If you click Please Register,form.html is viewed.
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8" />
<title>Form_Registration</title>
</head>
<body>
   <a th:href="@{/form}">Please Register</a>
</body>
</html>

form.html

th:action="@{/form}" is to post the data which is registered by user.
th:object="${student}" means student object and th:field="*{}" means defined object.
th:text="${}" get you registered student's data.
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8" />
<title>Form_Registration</title>
</head>
<body>
    <h1>Form Registration</h1>

    <form th:action="@{/form}" th:object="${student}" method="post">

        <div>
            <label>Student Name</label> 
            <input type="text" th:field="*{name}" />
        </div>
        <div>
            <label>Email</label> 
            <input type="text" th:field="*{email}" />
        </div>
        <div>
            <label>Day:</label>
            <select th:field="*{day}">
                <option th:each="d : ${days}" th:value="${d}" th:text="${d}"></option>
            </select> 
            <label>Month:</label> 
            <select th:field="*{month}">
                <option th:each="m : ${months}" th:value="${m}" th:text="${m}"></option>
            </select> 
            <label>Year:</label> 
            <select th:field="*{year}">
                <option th:each="y : ${years}" th:value="${y}" th:text="${y}"></option>
            </select>
        </div>
        <div>
            <label>City</label> 
            <input type="text" th:field="*{city}" />
        </div>

        <div>
            <label>Township</label> 
            <input type="text" th:field="*{township}" />

        </div>
        <div>
            <span th:each="grd: ${grades}"> 
               <input type="radio" th:field="*{grade}" th:value="${grd}" /> 
               <label th:for="${#ids.prev('grade')}" th:text="${grd}">Gender</label>
            </span>
        </div>
        <br/> 
        <br/> 
        <input type="submit" value="Send" />
    </form>

    <div th:if="${result != null}">
        <h1>Result</h1>
        <div>
            <h3>Student Name</h3>
            <ul>
                <li th:text="${result.name}">Name</li>
            </ul>
        </div>
        <div>
            <h3>Email</h3>
            <ul>
                <li th:text="${result.email}">Email</li>
            </ul>
        </div>
        <div>
            <h3>Date of Birth</h3>
            <p th:text="${result.day}"></p>
            <p th:text="${result.month}"></p>
            <p th:text="${result.year}"></p>

        </div>
        <div>
            <h3>City</h3>
            <ul>
                <li th:text="${result.city}">City</li>
            </ul>
        </div>
        <div>
            <h3>Township</h3>
            <ul>
                <li th:text="${result.township}">Township</li>
            </ul>
        </div>
        <div>
            <h3>Grades</h3>
            <ul>
                <li th:text="${result.grade}">Grades</li>
            </ul>
        </div>


    </div>
</body>
</html>

4.Run Server
Just run the server and navigate to http://localhost:8080/

You can see this on your browser!
Alt Text
If you click Please Register ,you can see that.
Alt Text
If you submit,you can view your result.
Alt Text
Alt Text

Top comments (0)