I am trying to create an HTML Form in Spring Boot which takes values entered in the form and inserts it into a database For this I am using Spring Data JPA to create a repository and save it.
So , getting to the question , I tried actually searching for the answer here and tried one solution but it didn't work.
I basically told me to remove th:field="*{}" from the input tag and just replace it with field="{}" , it did load the page but the I couldn't POST the values.
I am sharing my code below :
Student Model :
package com.example.demo.Student;
import jakarta.persistence.*;
import lombok.*;
@Entity
@Table(name="student")
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
public class Student {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private int studentId;
@Column(name="name")
private String studentName;
@Column(name="password")
private String studentPassword;
}
Student Controller
package com.example.demo.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
public class StudentController{
@Autowired
StudentRepository studentRepository;
@PostMapping("/registrationPage/registration/add")
public String addStudent(@ModelAttribute("Student") Student student){
studentRepository.save(student);
return "Added Successfully";
}
}
maincontroller
package com.example.demo;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
public class MainController {
@GetMapping("/")
public String index(
@RequestParam(name="name",required=false,defaultValue="World") String name,
Model model
){
model.addAttribute("name",name);
return "index";
}
@GetMapping("/registrationPage/registration.html")
public String registration(){
return "/registrationPage/registration";
}
}
index.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8"/>
<title>Welcome to Student Registration Page</title>
</head>
<body>
<h1 th:text="|Hello,${name}!|"></h1>
<a th:href="@{/registrationPage/registration.html}">Register Here</a><br>
<a th:href="@{/signInPage/signin.html}">Sign In</a>
</body>
</html>
registration.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8"/>
<title>Register Student</title>
</head>
<body>
<form action="#" th:action="@{/add}" th:object="${Student}" method="post">
<label>Enter Student Name : </label>
<input type="text" th:field="*{studentName}"/><br/><br/>
<label>Enter Student Password :</label>
<input type="password" th:field="*{studentPassword}"/><br/><br/>
<button type="submit">Register User</button>
</form>
</body>
</html>