Not able to POST values from HTML to Java Class in Spring Boot

Viewed 48

I am developing an Enote app. I decided to check a few functionalities first by checking whether I can get the values from the HTML page to the Java class variable and then print them on the console. When I submit the form the values of my HTML form do not come into the Java class variable neither it print. Whereas the tutorial I am following follows the same code and can easily print the values on the console.

So in short below is my following problems:

  1. Not able to print the values on the console when I submit the form.
  2. Even when I am using the @Data annotation of Lombok, the object hash is getting printed on the console. That is why I have to write toString() explicitly to check the values of the object.

Below is the file structure.

[enter image description here][1]

SbtEnotesApplication.java

package com.enotes;

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

@SpringBootApplication
public class SbtEnotesApplication {

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

}

HomeController.java

package com.enotes.controller;

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

import com.enotes.entity.UserDtls;

@Controller
public class HomeController {
    
    @GetMapping("/")
    public String home() {
        return "home";
    }
    
    @GetMapping("/login")
    public String login() {
        return "login";
    }
    
    @GetMapping("/signup")
    public String signup() {
        return "signup";
    }
    
    @PostMapping("/saveUser")
    public String saveUser( @ModelAttribute UserDtls user, Model m) {
        System.out.println(user);
        return "redirect:/signup";
    }
}

UserDtls.java

package com.enotes.entity;

import lombok.Data;

@Data
public class UserDtls {

    private int id;  // these variable name must be same as defined inside the HTML's tags under the name attribute. eg <a href="" name="id">
    private String name;
    private String email;
    private String password;
    private String about;

    @Override
    public String toString() {
        return "UserDtls [id=" + id + ", name=" + name + ", email=" + email + ", password=" + password + ", about="
                + about + "]";
    }

    public UserDtls() {
        
    }
}

base.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.com"
    th:fragment="layout(content)">
<head>
<meta charset="ISO-8859-1">
<title>Base page</title>
<link
    href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css"
    rel="stylesheet"
    integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC"
    crossorigin="anonymous">

<link rel="stylesheet"
    href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css"
    integrity="sha512-Fo3rlrZj/k7ujTnHg4CGR2D7kSs0v4LLanw2qksYuRlEzO+tcaEPQogQ0KaoGN26/zrn20ImR1DfuLWnOo7aBA=="
    crossorigin="anonymous" referrerpolicy="no-referrer" />

<link rel="stylesheet" th:href="@{/css/style.css}">
<style type="text/css">
.paint-card {
    box-shadow: 0 0 8px 0 rgba(0, 0, 0, 0.3);
}
</style>

</head>
<body>
    <nav class="navbar navbar-expand-lg navbar-dark bg-success">
        <div class="container-fluid">
            <a class="navbar-brand" th:href="@{/}"><i class="fas fa-book"></i>Enotes</a>
            <button class="navbar-toggler" type="button"
                data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent"
                aria-controls="navbarSupportedContent" aria-expanded="false"
                aria-label="Toggle navigation">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarSupportedContent">
                <ul class="navbar-nav me-auto mb-2 mb-lg-0">
                    <li class="nav-item"><a class="nav-link active"
                        aria-current="page" th:href="@{/}"><i class="fas fa-home"></i>Home</a></li>
                </ul>
                <form class="d-flex">
                    <a th:href="@{/login}" class="btn btn-light"><i
                        class="fas fa-sign-in-alt"></i>Login</a> <a th:href="@{/signup}"
                        class="btn btn-light ms-2"><i class="fas fa-user-plus"></i>Sign
                        up</a>
                </form>
            </div>
        </div>
    </nav>
    <div th:replace="${content}"></div>
    <script
        src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/js/bootstrap.bundle.min.js"
        integrity="sha384-JEW9xMcG8R+pH31jmWH6WWP0WintQrMb4s7ZOdauHnUtxwoG2vI5DkLtS3qm9Ekf"
        crossorigin="anonymous"></script>
</body>
</html>

signup.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org"
    th:replace="base::layout(~{::section})">
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
    <section>
        <div class="container">
            <div class="row">
                <div class="col-md-6 offset-md-3">
                    <div class="card mt-2 paint-card">
                        <h1 class="text-center">Register Here</h1>

                        <!--alert message  -->
                        <div th:if="${session.msg}" class="text-center">

                            <h4 class="text-success" th:text="${session.msg}"></h4>
                            <th:block th:text="${#session.removeAttribute('msg')}"></th:block>
                        </div>

                        <!--alert message  -->

                        <div class="card-body">
                            <form th:action="@{/saveUser}" method="post">

                                <div class="form-group mt-2">
                                    <label>Enter Name</label> <input type="text" name="name"
                                        class="form-control" required="required">

                                </div>

                                <div class="form-group mt-2">
                                    <label>Enter Email</label> <input type="email" name="email"
                                        class="form-control" required="required">
                                </div>

                                <div class="form-group mt-2">
                                    <label>Enter Password</label> <input type="password"
                                        name="password" class="form-control" required="required">
                                </div>

                                <div class="form-group mt-2">
                                    <textarea rows="3" cols="" class="form-control" name="about"
                                        placeholder="Enter About"></textarea>
                                </div>



                                <div class="text-center mt-3">
                                    <button class="btn bg-primary text-white">Submit</button>
                                    <button type="reset" class="btn btn-primary text-white">Reset</button>
                                </div>




                            </form>
                        </div>
                    </div>

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

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 https://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>2.6.3</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.enotes</groupId>
    <artifactId>SBT-Enotes</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>SBT-Enotes</name>
    <description>Enotes Spring boot Project</description>
    <properties>
        <java.version>11</java.version>
    </properties>
    <dependencies>
<!--         <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency> -->
<!--         <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>   -->  
        <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.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-springsecurity5</artifactId>
        </dependency> -->

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
<!--        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency> -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-test</artifactId>
            <scope>test</scope>
        </dependency>  
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

Cosnsole

[enter image description here]1

1 Answers

You need to use th:object and th:field to have the binding working.

Change your HTML like this:

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

     <div class="form-group mt-2">
       <label>Enter Name</label>
       <input type="text" th:field="*{name}"
              class="form-control" required="required">

     </div>

    ...
</form>

See Form handling with Thymeleaf for more info.

Related