Skip to content
>otpbuilt · run · measured
  • Languages

    • PyPython 198From basics to async, with runnable examples
    • JaJava 162Core Java, OOP, collections and concurrency
    • J8Java 8 36Streams, lambdas, Optional and the date API
    • CpC programming 59Pointers, memory and classic programs
    • PhPHP 22Server-side PHP with practical snippets
    • RuRust 2Ownership, borrowing and safe systems code

    Frameworks

    • SbSpring Boot 58REST APIs, data, security and testing
    • SpSpring 27Core container, MVC and dependency injection
    • HiHibernate 46ORM mappings, HQL and caching
    • FlFlask 9Lightweight Python web apps and APIs
    • DjDjango 4Full-stack Python web framework
    • JqjQuery 19DOM, events and AJAX the classic way

    Data & DevOps

    • JdJDBC 18Connect Java to any SQL database
    • MyMySQL 6Install, query and tune MySQL
    • NuNumPy 8Fast arrays and numeric computing
    • PaPandas 6DataFrames, cleaning and analysis
    • DoDocker 4Containers for local dev and deploys
    • AwAWS 16Core AWS services, hands-on
    FeaturedWintraLabs practice testsExam-style practice for AWS and cloud certifications, with a clear explanation for every answer.Start practising
    • JpJava programs 36Interview-style programs with full solutions
    • DsData structures 7Lists, trees, graphs and hashing
    • AlAlgorithms 5Sorting, searching and problem patterns
    • OcOOP concepts 8Classes, inheritance and polymorphism explained
    • AtAI tools 3Local models, assistants and practical AI workflows
    • BuBuildsStep-by-step projects you can run yourself
    • BeBenchmarksMeasured results on real hardware
    • CgCertification guidesExam outlines, study plans and tips
    • AwAWS 16Hands-on AWS for cloud exams
    • WpWintraLabs practice testsTimed practice exams with explanations
    View all Certifications
Practice tests
Practice tests

Press Esc to close

Learning path

Spring Boot

Lesson 32 of 52

  1. 1 Hello World
  2. 2 MVC Example
  3. 3 Change Context Path
  4. 4 Change Tomcat Port Number
  5. 5 Change Tomcat to Jetty Server
  6. 6 Tomcat session timeout
  7. 7 Enable Random Port
  8. 8 Properties File
  9. 9 Beans Lazy Loading
  10. 10 Set Favicon image
  11. 11 Set Custom Banner
  12. 12 Set Application TimeZone
  13. 13 Send Mail
  14. 14 FileUpload Ajax
  15. 15 Actuator
  16. 16 Actuator Database Health Check
  17. 17 Swagger
  18. 18 Enable CORS
  19. 19 External Apache ActiveMQ Setup
  20. 20 Inmemory Apache ActiveMq
  21. 21 Scheduler Job
  22. 22 Exception Handling
  23. 23 Hibernate CRUD
  24. 24 JPA Integration CRUD
  25. 25 JPA DataRest CRUD
  26. 26 JdbcTemplate CRUD
  27. 27 Multiple Data Sources Config
  28. 28 JNDI Configuration
  29. 29 H2 Database CRUD
  30. 30 MongoDB CRUD
  31. 31 Redis Data CRUD
  32. 32 MVC Login Form Validation
  33. 33 Custom Error Pages
  34. 34 iText PDF
  35. 35 Enable SSL (HTTPs)
  36. 36 Basic Authentication
  37. 37 In Memory Basic Authentication
  38. 38 Security MySQL Database Integration
  39. 39 Redis Cache – Redis Server
  40. 40 Hazelcast Cache
  41. 41 EhCache
  42. 42 Kafka Producer
  43. 43 Kafka Consumer
  44. 44 Kafka JSON Message to Kafka Topic
  45. 45 RabbitMQ Publisher
  46. 46 RabbitMQ Consumer
  47. 47 SOAP Consumer
  48. 48 Soap WebServices
  49. 49 Batch Csv to Database
  50. 50 Eureka Server
  51. 51 MockMvc JUnit
  52. 52 Docker Deployment
WWintraLabsOur product

Preparing for a Java certification?

Which Java 8 feature lets you pass behaviour as a value? ✓Lambda expressions
Start a free practice test
Home » Spring Boot Validation Login Form Example
Spring Boot

Spring Boot Validation Login Form Example

By chandrashekhar·Updated Jun 4, 2019·Published Dec 27, 2017·3 min read
On this page

    In this tutorial, I am going to show you how to work with Spring Boot Validation framework.

    Technologies :

    • SpringBoot_1.5.9.RELEASE
    • spring-boot-thymeleaf
    • Apache Tomcat Embed
    • Java 8

    Spring Boot Validation :

    I am going to create a simple Spring Boot Login form using a thymeleaf template and validate username and passwords.

    Advertisement

    Project Structure :

    Spring Boot Validation

    Project Dependencies :

    pom.xml

    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>com.onlinetutorialspoint.springbootvalidation</groupId>
        <artifactId>springbootvalidation</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>1.5.9.RELEASE</version>
        </parent>
        <properties>
            <java.version>1.8</java.version>
        </properties>
        <build>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                </plugin>
            </plugins>
        </build>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-thymeleaf</artifactId>
            </dependency>
            <dependency>
                <groupId>org.hibernate</groupId>
                <artifactId>hibernate-validator</artifactId>
            </dependency>
            <dependency>
                <groupId>org.apache.tomcat.embed</groupId>
                <artifactId>tomcat-embed-el</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
            </dependency>
        </dependencies>
        <repositories>
            <repository>
                <id>spring-releases</id>
                <name>Spring Releases</name>
                <url>https://repo.spring.io/libs-release</url>
            </repository>
        </repositories>
        <pluginRepositories>
            <pluginRepository>
                <id>spring-releases</id>
                <name>Spring Releases</name>
                <url>https://repo.spring.io/libs-release</url>
            </pluginRepository>
        </pluginRepositories>
    </project>

    Login Controller :

    LoginController.java
    package com.onlinetutorialspoint.login;
    
    import javax.validation.Valid;
    
    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 org.springframework.web.servlet.ModelAndView;
    import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
    
    @Controller
    public class LoginController extends WebMvcConfigurerAdapter {
        @Override
        public void addViewControllers(ViewControllerRegistry registry) {
            registry.addViewController("/home").setViewName("home");
        }
    
        @GetMapping("/")
        public String showForm(LoginForm loginForm) {
            return "login";
        }
    
        @PostMapping("/")
        public String validateLoginInfo(Model model, @Valid LoginForm loginForm, BindingResult bindingResult) {
            if (bindingResult.hasErrors()) {
                return "login";
            }
            model.addAttribute("user", loginForm.getuserName());
            return "home";
        }
    }

    LoginForm.java

    LoginForm.java
    package com.onlinetutorialspoint.login;
    
    import javax.validation.constraints.Min;
    import javax.validation.constraints.NotNull;
    import javax.validation.constraints.Size;
    
    public class LoginForm {
        @NotNull
        @Size(min = 2, max = 30)
        private String userName;
    
        @NotNull
        @Min(5)
        private String password;
    
        public String getuserName() {
            return this.userName;
        }
    
        public void setuserName(String userName) {
            this.userName = userName;
        }
    
        public String getPassword() {
            return password;
        }
    
        public void setPassword(String password) {
            this.password = password;
        }
    
        public String toString() {
            return "LoginForm(UserName: " + this.userName + ", Password: " + this.password + ")";
        }
    }

    Login.html

    Login.html
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Spring Boot Validation Login Form Example</title>
    <link rel="stylesheet"
        href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
    <link rel="stylesheet"
        href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" />
    <link rel="stylesheet" href="style.css" />
    </head>
    <body>
        <div class="login-form">
            <form action="#" th:action="@{/}" th:object="${loginForm}"
                method="post">
                <h2 class="text-center">Sign in</h2>
                <div class="form-group">
                    <div class="input-group">
                        <span class="input-group-addon"><i class="fa fa-user"></i></span> <input
                            type="text" class="form-control" th:field="*{userName}"
                            placeholder="Username" />
    
                    </div>
                    <span class="red" th:if="${#fields.hasErrors('userName')}"
                        th:errors="*{userName}"></span>
                </div>
                <div class="form-group">
                    <div class="input-group">
                        <span class="input-group-addon"><i class="fa fa-lock"></i></span> <input
                            type="password" class="form-control" th:field="*{password}"
                            placeholder="Password" />
    
                    </div>
                    <span class="red" th:if="${#fields.hasErrors('password')}"
                        th:errors="*{password}"></span>
                </div>
                <div class="form-group">
                    <button type="submit" class="btn btn-primary login-btn btn-block">Sign
                        in</button>
                </div>
            </form>
        </div>
    </body>
    </html>

    home.html

    home.html
    <html>
    <head>
    <meta charset="ISO-8859-1"/>
    <title>Spring Boot Validation Home</title>
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"/>
    </head>
    <body>
    <div class="alert alert-success">
      <strong>Success!</strong> Hello <span th:text="${user}" /> !
    </div>
    </body>
    
    </html>
    Application.java
    package com.onlinetutorialspoint.login;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    @SpringBootApplication
    public class Application {
        public static void main(String[] args) {
            SpringApplication.run(Application.class, args);
        }
    }

    Run Application :

    Terminal
    mvn spring-boot:run
    

    Access: http://localhost:8080/

    Spring Boot Validation Login 1

    Success :

    Spring Boot Validation Login

    Error Validation :

    Spring Boot Validation Login Error

    Happy Learning :)

    Download Example

    • zip springbootvalidation
      Spring Boot Validation Login Form
      File size: 56 KB Downloads: 3284

    Found a mistake or something out of date? Tell us →

    Written by

    chandrashekhar

    Founder of onlinetutorialspoint.com. Enterprise architect with 15+ years in healthcare technology, designing and running systems on AWS and Azure. Writes about building real things with AI, local AI hardware and cloud certifications.

    All articles About this site

    Advertisement
    Tags:spring bootSpring Login Form
    ← Previous lessonRedis Data CRUDNext lesson →Custom Error Pages

    Keep reading

    Spring Spring MVC Form Validation Example onlinetutorialspoint.com
    Spring January 21, 2018

    Spring MVC Form Validation Example

    Here I am going show a simple Spring MVC Form Validation Example. Technologies : Spring Framework 3.1.1.RELEASE Hibernate Validator 4.2.0.Final Jstl 1.2 Java 8 Spring MVC Form Validation…

    Spring Spring MVC Login Form Example Tutorials onlinetutorialspoint.com
    Spring April 21, 2015

    Spring MVC Login Form Example Tutorials

    Spring MVC Login Form is a basic example for all spring based applications. We can hardly imagine any web application without forms in it because forms have their…

    Spring Spring Form Custom Validation Example onlinetutorialspoint.com
    Spring January 26, 2018

    Spring Form Custom Validation Example

    In this tutorial, I am going to show you how to validate Spring Form with Custom validations. In the previous tutorial, we had a discussion about a simple…

    WWintraLabsOur product

    Preparing for a Java certification?

    Timed Java practice exams on WintraLabs, with an explanation for every answer and an AI Copilot.

    • Timed mock exams
    • Answer explanations
    • Free sample tests
    Start a free practice test No sign-up needed

    1 comment

    1. Zhengguan says:
      March 21, 2019 at 12:07 pm

      Thanks, really really helpful!!!

      Reply

    Ask a question or leave a comment Cancel reply

    Advertisement

    On this page

      WWintraLabsOur product

      Preparing for a Java certification?

      Which Java 8 feature lets you pass behaviour as a value? ✓Lambda expressions
      Start a free practice test
      >otp

      Practical AI and hardware projects for developers: built, tested, explained.

      Topics

      • Python
      • C Programming
      • Spring Boot
      • Hibernate
      • Java Programs
      • Java 8
      • Spring
      • PHP

      Explore

      • WintraLabs practice tests ↗
      • RSS feed

      Site

      • About
      • Authors
      • Contact
      • Privacy Policy
      • Terms of Use
      • Disclaimer
      © 2026 onlinetutorialspoint. All rights reserved. Back to top ↑