From controller, data is not transforming to html view page - java

I am trying send the data through controller to html page but unable data transmission is getting failed. Control is redirecting to the desired page along with labels but form data is not reflecting in the view page.
***HomeController***
package com.example.demo.web;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.example.demo.domain.User;
#Controller
public class HomeController {
User user = new User();
#RequestMapping("/")
public String home(Model model) {
model.addAttribute("formData", user);
return "index";
}
#RequestMapping(value="/create", method=RequestMethod.POST)
public String processFormData(User user, RedirectAttributes attr) {
attr.addFlashAttribute("user",user);
return "redirect:display";
}
#RequestMapping(value="/display", method=RequestMethod.GET)
public String displayFormData(User user) {
return "result";
}
}
index.html
<!DOCTYPE html>
<html xmlns:th="http://thymeleaf.org">
<head>
<meta charset="UTF-8">
<title> Home Page </title>
</head>
<body>
<p> Enter Data Below </p>
<form action="/create" method="post" th:object="${formData}">
<p>Full Name:<input type="text" th:feild="${formData.fullName}"/></p>
<p>Age:<input type="text" th:feild="${formData.age}"/></p>
<p>Employed?<input type="checkbox" th:feild="${formData.employed}" th:value="true"/></p>
<p>Gender:</p>
<p>Male<input type="radio" th:feild="${formData.gender}" th:value="Male"/>
Female<input type="radio" th:feild="${formData.gender}" th:value="Female"/></p>
<p><input type="submit" value="Submit"/> <input type="reset" value="Reset"/></p>
</form>
</body>
</html>
result.html
<html xmlns:th="https://thymeleaf.org">
<table>
<tr>
<td><h4>User Name: </h4></td>
<td><h4 th:text="${user.fullName}"></h4></td>
</tr>
<tr>
<td><h4>Age: </h4></td>
<td><h4 th:text="${user.age}"></h4></td>
</tr>
</table>
</html>

The controller class sends and reads a form view. The User data is passed as a parameter to the processForm() handler. Spring tries to fill the bean with the request data. The data is also automatically available for the Thymeleaf result view. The #Controller annotation allows the implementation classes to be autodetected through the classpath scanning.
#Controller is typically used in combination with a #RequestMapping annotation used on request handling methods. I used the #GetMapping and ##PostMapping` as a shortcut to #RequestMapping(method = RequestMethod.POST)
#Controller
public class HomeController {
//This responds to localhost:8080/
#GetMapping("/")
public String sendForm(User user){
return "index";
}
//This responds to localhost:8080/
#PostMapping("/")
public String processForm(User user){
return "result";
}
User Class. This is the User class. It is automatically filled with data from the form request. The attributes must match the form fields. You should be able to see the matching attribute names in the template views below.
public class User {
private String fullName;
private int age;
private String occupation;
public String getFullName() {
return fullName;
}
public void setFullName(String name) {
this.fullName = name;
}
public String getOccupation() {
return occupation;
}
public void setOccupation(String occupation) {
this.occupation = occupation;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
index.html
The th:object refers to the user form bean. This is not a class name, but a Spring bean name; therefore it is in lowercase. With the *{} syntax, we refer to the defined object. In this case its the user object. I noticed that you misspelled th:field, this can also create bugs.
<!DOCTYPE html>
<html lang="en" xmlns:th="https://www.thymeleaf.org">
<head>
<meta charset="UTF-8"/>
<title></title>
</head>
<body>
<p> Enter Data Below </p>
<form th:action="#{/}" th:object="${user}" method="post">
<p>Full Name:<input type="text" th:field="*{fullName}" id="fullName" name="fullname" autofocus="autofocus"></p>
<p>Age:<input type="number" th:field="*{age}" id="age" name="age" autofocus="autofocus" /></p>
<p><input type="submit" value="Submit"/> <input type="reset" value="Reset"/></p>
</form>
</body>
</html>
result.html
We identify the form attributes with the ${} syntax.
<!DOCTYPE html>
<html lang="en" xmlns:th="https://www.thymeleaf.org">
<head>
<meta charset="UTF-8"/>
<title></title>
</head>
<body>
<table>
<tr>
<td><h4>User Name: </h4></td>
<td><h4 th:text="${user.fullName}"></h4></td>
</tr>
<tr>
<td><h4>Age: </h4></td>
<td><h4 th:text="${user.age}"></h4></td>
</tr>
</table>
</body>
</html>

Related

html form handling in thymeleaf and spring boot

I am new to springboot and thymeleaf and I'm trying to understand the form handling methods that interact with the code. Below you will find my html documents linked to a Users class. I am trying to change them to link to a customer class amongst other things, but anytime I change the th:object=${users} to match the new entity 'customerentity' it gives me the error below. What more do I have to do to get the bean(?) to register my new attribute? Any help or links to other answers is greatly appreciated.
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'customerentity' available as request attribute
Here is my entity class
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import org.springframework.lang.NonNull;
#Entity
public class Users {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
#NonNull
private String name;
#NonNull
private String email;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
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;
}
// standard constructors / setters / getters / toString
}
The controller class
#Controller
public class UserController {
//set up a UserRepositoty variable
#Autowired
private UserRepository userRepository;
//create an UserRepository instance - instantiation (new) is done by Spring
public UserController(UserRepository userRepository) {
this.userRepository = userRepository;
}
//Mapping for the /index URL when initiated through Tomcat
#RequestMapping({"/index"})
public String showUserList(Model model) {
model.addAttribute("customers", userRepository.findAll());
return "index";
}
//Mapping for the /signup URL - calls the add-user HTML, to add a user
#RequestMapping({"/signup"})
public String showSignUpForm(Users user) {
return "add-user";
}
//Mapping for the /signup URL - to add a user
#RequestMapping({"/adduser"})
public String addUser(#Validated Users users, BindingResult result, Model model) {
if (result.hasErrors()) {
return "add-user";
}
userRepository.save(users);
return "redirect:/index";
}
//Mapping for the /edit/user URL to edit a user
#GetMapping("/edit/{id}")
public String showUpdateForm(#PathVariable("id") long id, Model model) {
Users user = userRepository.findById(id)
.orElseThrow(() -> new IllegalArgumentException("Invalid user Id:" + id));
model.addAttribute("customer", user);
return "update-user";
}
//Mapping for the /update/id URL to update a user
#PostMapping("/update/{id}")
public String updateUser(#PathVariable("id") long id, #Validated Users user,
BindingResult result, Model model) {
if (result.hasErrors()) {
user.setId(id);
return "update-user";
}
userRepository.save(user);
return "redirect:/index";
}
//Mapping for the /delete/id URL to delete a user
#GetMapping("/delete/{id}")
public String deleteUser(#PathVariable("id") long id, Model model) {
Users user = userRepository.findById(id)
.orElseThrow(() -> new IllegalArgumentException("Invalid user Id:" + id));
userRepository.delete(user);
return "redirect:/index";
}
}
The html documents
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="ISO-8859-1">
<title>Add User</title>
</head>
<body>
<form action="#" th:action="#{/adduser}" th:object="${users}" method="post">
<label for="name">Name</label>
<input type="text" th:field="*{name}" id="name" placeholder="Name">
<span th:if="${#fields.hasErrors('name')}" th:errors="*{name}"></span>
<label for="email">Email</label>
<input type="text" th:field="*{email}" id="email" placeholder="Email">
<span th:if="${#fields.hasErrors('email')}" th:errors="*{email}"></span>
<input type="submit" value="Add User">
</form>
</body>
</html>
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="ISO-8859-1">
<title>Add User</title>
</head>
<body>
<div th:switch="${users}">
<h2 th:case="null">No users yet!</h2>
<div th:case="*">
<h2>Users</h2>
<table>
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
<tr th:each="user : ${users}">
<td th:text="${user.name}"></td>
<td th:text="${user.email}"></td>
<td><a th:href="#{/edit/{id}(id=${user.id})}">Edit</a></td>
<td><a th:href="#{/delete/{id}(id=${user.id})}">Delete</a></td>
</tr>
</tbody>
</table>
</div>
<p>Add a new user</p>
</div>
</body>
</html>

How do I pass an object with thymeleaf to java spring controller?

I can't pass a object Project without the object is null.
How do I pass the object to the spring controller from the html?
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Home</title>
</head>
<body>
<form action="/addproject" method="POST">
<input type="hidden" name="project" th:value="${project}"/>
<input type="submit" value="Save Project" class="submit">
</form>
</body>
</html>
#Controller
public class ProjectController {
#GetMapping("/")
public String indexPage(Model model) {
model.addAttribute("project", new Project("Test", "Test"));
return "index";
}
#PostMapping("/addproject")
public String add(WebRequest webRequest) {
Project p = (Project) webRequest.getAttribute("project", WebRequest.SCOPE_REQUEST);
return "index";
}
}
Please check this article. In short you need to pass required object to ModelAndView, not Model:
#GetMapping("/")
public ModelAndView indexPage(Model model) {
ModelAndView mav = new ModelAndView("index");
mav.addObject("project", new Project("Test", "Test"));
return mav;
}
and access it by name from template:
<b th:text="${project.attribute}">Text ...</b>
I would suggest you to proceed with the document here first.
You don't have a requirement or problem with ModelAndView.
The first time you call the /project page, the project class information will be loaded by #GetMapping, if you want, it will be captured by #PostMapping when you change and submit it.
project.html file:
<!DOCTYPE HTML>
<html xmlns:th="https://www.thymeleaf.org">
<head>
<title>Project Form</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<h1>Project Form</h1>
<form method="post" th:action="#{/project}" th:object="${project}">
<p>Name: <input type="text" th:field="*{name}" /></p>
<p>Description: <input type="text" th:field="*{description}" /></p>
<p><input type="submit" value="Submit" /> </p>
</form>
</body>
</html>
Project.java file:
public class Project {
private String name;
private String description;
public Project(String name, String description) {
this.name = name;
this.description = description;
}
// getter/setter ...
}
ProjectController.java file:
#Controller
public class ProjectController {
#GetMapping("/project")
public String greetingForm(Model model) {
model.addAttribute("project", new Project("PN1", "PD1"));
return "project";
}
#PostMapping("/project")
public String greetingSubmit(#ModelAttribute Project project, Model model) {
model.addAttribute("project", project);
return "project";
}
}

Form submission with Java and Thymeleaf

I am creating my first form with Java developing with Sprint Tool Suite on my local machine. I created an index.html page with a simple form with 3 input fields. I want to have the form submit to a results.html page which just displays the values entered into the form. The issue I am having is that when I launch the application, fill in some data, and click the submit button, I get a 404 error. Also, what I noticed is that when I click on the submit button, the url box of the browser changes to localhost:8080/person. I expected to see localhost:8080/results. I thank you in advance for any assistance.
My main application class code is this:
package com.baconbuddy;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class BaconBuddyApplication {
public static void main(String[] args) {
SpringApplication.run(BaconBuddyApplication.class, args);
}
}
My index.html has the following code:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Home Page</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
</head>
<body>
<h1>Hello world!</h1>
<form action="#" th:action="#{/person}" th:object="${person}" method="post" >
<input th:field="*{firstName}" placeholder="First Name" />
<input th:field="*{lastName}" placeholder="Last Name" />
<input th:field="*{age}" placeholder="Age" />
<button >Submit</button>
</form>
</body>
</html>
My results.html has the following code:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Insert title here</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<div>
<p>First Name:
<span th:text="${person.firstName}"></span>
</p>
<br />
<p>Last Name:
<span th:text="${person.lastName}"></span>
</p>
<br />
<p>Age:
<span th:text="${person.age}"></span>
</p>
</div>
</body>
</html>
My Person.java file looks like this:
package com.baconbuddy.models;
public class Person {
private String firstName;
private String lastName;
private int age;
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 int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
and my HomeController.java looks like this:
package com.baconbuddy.controllers;
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 org.springframework.web.bind.annotation.RequestMapping;
import com.baconbuddy.models.Person;
#Controller
#RequestMapping({ "/", "/home" })
public class HomeController {
#GetMapping()
public String index(Model model) {
model.addAttribute("person", new Person());
// The string index will be looked for in src/main/resources/templates
return "index";
}
#PostMapping()
public String personSubmit(#ModelAttribute Person person) {
return "results";
}
}
You have #{/person} as your th:action in your <form> HTML, but your controller isn't mapping a method for it. The POST you have mapped right now is mapping to / and /home (inherited from your class-level #RequestMapping). Change your #PostMapping or modify your <form>, e.g.:
#PostMapping("person")
public String personSubmit(#ModelAttribute Person person) {
return "results";
}
Or update your form:
<form action="#" th:action="#{/}" th:object="${person}" method="post" >

Submitting HTML form for Spring

I'm trying to create a simple login page using Spring.
I've created a form as described in the tutorial [here][1]
For some reason, when I hit the submit button, the request doesn't go through to the controller. (I've set a breakpoint in the first line of the controllers method)
Does anyone have an idea why?
My code:
Controller:
#RequestMapping(value="/login", method=RequestMethod.POST)
public String login(#ModelAttribute(value="loginModel") LoginModel loginModel) {
if(loginModel.getEmail().equals("null") || loginModel.getPassword().equals("null")) {
return "Wrong user email or password";
}
return "result";
}
Model:
public class LoginModel {
private String email;
private String password;
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public LoginModel(String email, String password) {
super();
this.email = email;
this.password = password;
}
}
View:
<!doctype html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" href="css/login.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
</head>
<body>
<div class="form">
<ul class="tab-group">
<li class="tab active">Sign Up</li>
<li class="tab">Log In</li>
</ul>
<div id="login">
<h1>Welcome Back!</h1>
<form action="#" th:action="#{/login}" th:object="${loginModel}" method="post">
<div class="field-wrap">
<input type="email" required autocomplete="off" th:field="*{email}"/>
</div>
<div class="field-wrap">
<input type="password" required autocomplete="off" th:field="*{password}"/>
</div>
<p class="forgot">
Forgot Password?
</p>
<input type="submit" value="Log in" />
</form>
</div>
</div>
</body>
</html>
UPDATE:
Found the problem...
The LoginModel class MUST have empty constructor
Remove #ModelAttribute and then try again.

How to receive all request parameters in a model in Java Struts2?

I am trying to receive all the request parameters from a form in controller having a modelobj. But the model parameters remains null. I dont want to create all the parameters and their setter/getters of models in my controller class...Plz help
Form :
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="/struts-tags" prefix="s"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Login</title>
</head>
<body>
<div>
<form action="login" method="post">
<label>Email Id</label>
<input type="text" name="emailId">
<label>Password</label>
<input type="password" name="password">
<input type="submit" value="Login">
</form>
</div>
</body>
</html>
Model :
public class UserModel {
String emailId;
String password;
public String getEmailId() {
return emailId;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
Controller :
import com.opensymphony.xwork2.ActionSupport;
public class LoginController extends ActionSupport{
UserModel userModelObj = new UserModel();
public UserModel getUserModelObj() {
return userModelObj;
}
public void setUserModelObj(UserModel userModelObj) {
this.userModelObj = userModelObj;
}
public String login()
{
UserModel userModelObj = new UserModel();
System.out.println(userModelObj.emailId);
System.out.println(userModelObj.password);
return "success";
}
}
On console it returns null null
You must use your bean class reference in your form's name attribute like this :
<div>
<form action="login" method="post">
<label>Email Id</label>
<input type="text" name="userModelObj.emailId"/>
<label>Password</label>
<input type="password" name="userModelObj.password"/>
<input type="submit" value="Login">
</form>
</div>
Otherwise use the concept Of ModelDriven interface.

Categories