HelloKoding

Practical coding guides

Spring Boot Form Data Binding and Validation Example with FreeMarker

This tutorial will walk you through the steps of creating a Form Data Binding and Validation Example with Spring Boot and FreeMarker

What you’ll build

Spring Boot Form Binding and Validation

Spring Boot Form Binding and Validation

What you’ll need

  • JDK 1.7+
  • Maven 3+

Stack

  • Java
  • Spring Boot
  • FreeMarker
  • HTML, CSS

Init project structure and dependencies

Project structure

├── src
│   └── main
│       ├── java
│       │   └── com
│       │       └── hellokoding
│       │           └── springboot
│       │               ├── FormController.java
│       │               ├── User.java
│       │               └── WebApplication.java
│       └── resources
│           ├── static
│           │   ├── css
│           │   │   └── main.css
│           │   └── js
│           │       └── main.js
│           ├── templates
│           │   └── form.ftl
│           └── application.properties
└── pom.xml

Project dependencies

pom.xml

<?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.hellokoding.springboot</groupId>
    <artifactId>freemarker.form.validation</artifactId>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.4.RELEASE</version>
    </parent>

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

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-freemarker</artifactId>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

Define DTO, Controller and View Template

Data transfer object (DTO)

User.java

package com.hellokoding.springboot;

import javax.validation.constraints.Email;
import javax.validation.constraints.NotEmpty;

public class User {
    @NotEmpty
    private String firstName;

    @NotEmpty
    private String lastName;

    @NotEmpty
    @Email
    private String email;

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
}

Controller

FormController.java

package com.hellokoding.springboot;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import javax.validation.Valid;

@Controller
public class FormController {
    @GetMapping("/")
    public String index() {
        return "redirect:/form";
    }

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

    @PostMapping("/form")
    public String formPost(@Valid User user, BindingResult bindingResult, Model model) {
        if (!bindingResult.hasErrors()) {
            model.addAttribute("noErrors", true);
        }
        model.addAttribute("user", user);
        return "form";
    }
}

View template

form.ftl

<#import "/spring.ftl" as spring />

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Form Data Binding and Validation</title>
        <link href="/css/main.css" rel="stylesheet">
    </head>
    <body>
        <h2>Form Data Binding and Validation</h2>

        <@spring.bind "user"/>
        <#if user?? && noErrors??>
            Your submitted data<br>
            First name: ${user.firstName}<br>
            Last name: ${user.lastName}<br>
            Email: ${user.email}<br>
        <#else>
            <form action="/form" method="post">
                First name:<br>
                <@spring.formInput "user.firstName"/>
                <@spring.showErrors "<br>"/>
                <br><br>
                Last name:<br>
                <@spring.formInput "user.lastName"/>
                <@spring.showErrors "<br>"/>
                <br><br>
                Email:<br>
                <@spring.formInput "user.email"/>
                <@spring.showErrors "<br>"/>
                <br><br>
                <input type="submit" value="Submit">
            </form>
        </#if>

        <script src="/js/main.js"></script>
    </body>
</html>

Config and Run

Application Configuration

WebApplication.java

package com.hellokoding.springboot;

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

@SpringBootApplication
public class WebApplication {
    public static void main(String[] args) throws Exception {
        SpringApplication.run(WebApplication.class, args);
    }
}

application.properties

spring.freemarker.template-loader-path: classpath:/templates
spring.freemarker.suffix: .ftl

Run the application

Type the following Maven command on your terminal console at the project root directory

mvn clean spring-boot:run

Source code

https://github.com/hellokoding/hellokoding-courses/tree/master/springboot-examples/springboot-freemarker-form-validation

Follow HelloKoding