i have one model object Person
public class Person {
public String firstName;
public String lastName;
public String country;
public String sex;
private Integer age;
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String toString(){
return firstName + " " + sex;
}
}
and in controller i populated reference data countryList in below method
#ModelAttribute
public void populateCountryList(Model model){
System.out.println("inside populateCountryList");
Map<String,String> country = new LinkedHashMap<String,String>();
country.put("Select", "-----Select------");
country.put("US", "United Stated");
country.put("CHINA", "China");
country.put("SG", "Singapore");
country.put("MY", "Malaysia");
country.put("MY1", "India");
country.put("MY2", "UK");
country.put("MY3", "SA");
country.put("MY4", "Newzeland");
model.addAttribute("countryList", country);
}
Also populated Person object in another method
#ModelAttribute
public Person populateModel(){
System.out.println("inside populateCountry");
Person person = new Person();
person.setCountry("India");
person.setSex("M");
return person;
}
Now in jsp my components are text boxes for firstName, age, dropdown for country and radio button for sex. I want the radio button for Sex (M) and in dropdown the country "India" be selected by default. My jsp is below.
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
...
<h1>Person page</h1>
<p>This is Person page</p>
<form:form method="POST" commandName="person" action="process-person.html">
<table>
<tbody><tr>
<td><form:label path="firstName">Name:</form:label></td>
<td><form:input path="firstName"></form:input></td>
</tr>
<tr>
<td><form:label path="age">Age:</form:label></td>
<td><form:input path="age"></form:input></td>
</tr>
<tr>
<td><form:label path="country">Country:</form:label></td>
<td>
<form:select path="country">
<form:options items="${countryList}" />
</form:select>
</td>
</tr>
<tr>
<td>Sex :</td>
<td><form:radiobutton path="sex" value="M" />Male
<form:radiobutton path="sex" value="F" />Female
</td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Submit">
</td>
<td></td>
<td></td>
</tr>
</tbody></table>
</form:form>
When i am running the application default values are not getting selected. I also tried to print Person object in jsp, it is printing the Person object value of its properties are getting null.
Please suggest me what is wrong in this implementation.
Solution
In the handler method i have written the below code.
**#RequestMapping(value="/person-form")
public ModelAndView personPage() {
return new ModelAndView("person-page", "person", new Person());
}**
so i've changed the code to
**#RequestMapping(value="/person-form")
public ModelAndView personPage() {
return new ModelAndView("person-page");
}**
It is because you need to set KEY instead the Value in your person object:
person.setCountry("MY1");
Related
I am new to Spring Boot and I am am working on creating connecting the front of an application to the back at the moment.
I used this site https://spring.io/guides/gs/validating-form-input/
to work on a simple example and it worked fine. It uses the names 'name' and 'age' for the two fields, and getAge, and getName etc for getters and setters.
This code works:
HTML form:
<html>
<body>
<form action="#" th:action="#{/}" th:object="${personForm}" method="post">
<table>
<tr>
<td>Name:</td>
<td><input type="text" th:field="*{name}" /></td>
<td th:if="${#fields.hasErrors('name')}" th:errors="*{name}">Name Error</td>
</tr>
<tr>
<td>Age:</td>
<td><input type="text" th:field="*{age}" /></td>
<td th:if="${#fields.hasErrors('age')}" th:errors="*{age}">Age Error</td>
</tr>
<tr>
<td><button type="submit">Submit</button></td>
</tr>
</table>
</form>
</body>
</html>
Person java class
public class PersonForm {
#NotNull
#Size(min=2, max=30)
private String name;
#NotNull
#Min(18)
private Integer age;
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String toString() {
return "Person(Name: " + this.name + ", Age: " + this.age + ")";
}
}
Controller
#Controller
public class WebController extends WebMvcConfigurerAdapter {
#Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/results").setViewName("results");
}
#GetMapping("/")
public String showForm(PersonForm personForm) {
return "form";
}
#PostMapping("/")
public String checkPersonInfo(#Valid PersonForm personForm, BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
return "form";
}
return "redirect:/results";
}
}
I have simply changed the names of the variables to the below: (2 strings instead of an int and a string). The following error is displayed when I try to view the page: Error during execution of processor 'org.thymeleaf.spring4.processor.attr.SpringInputGeneralFieldAttrProcessor' (form:33)
Line 33 has " th:field="*{testcolumn}" " on it.
Is there certain naming conventions you must follow with thymeleaf perhaps? I cannot find information about it. Thanks
Person class:
#NotNull
#Size(min=2, max=30)
private String testcolumn;
#NotNull
private String testcolumntwo;
public String getTestcolumn() {
return this.testcolumn;
}
public void setTestcolumn(String testcolumn) {
this.testcolumn = testcolumn;
}
public String getTestcolumntwo() {
return testcolumntwo;
}
public void setTestcolumntwo(String testcolumntwo) {
this.testcolumntwo = testcolumntwo;
}
public String toString() {
return "Person(Name: " + this.testcolumntwo + ", Age: " + this.testcolumntwo + ")";
}
HTML Form:
<form action="#" th:action="#{/}" th:object="${personForm}" method="post">
<table>
<tr>
<td>Name:</td>
<td><input type="text" th:field="*{testcolumn}" /></td>
<td th:if="${#fields.hasErrors('testcolumn')}" th:errors="*{testcolumn}">Name Error</td>
</tr>
<tr>
<td>Age:</td>
<td><input type="text" th:field="*{testcolumntwo}" /></td>
<td th:if="${#fields.hasErrors('testcolumntwo')}" th:errors="*{testcolumntwo}">Age Error</td>
</tr>
<tr>
<td><button type="submit">Submit</button></td>
</tr>
</table>
</form>
I have two webpages.One is "user.jsp" and "person.jsp".when i click on "Register" button it goes to "user.jsp" and when i click on submit button its showing "Http Status 400".
PersonController.java
#Controller
public class PersonController {
private PersonService personService;
private UserService userService;
#Autowired(required=true)
#Qualifier(value="personService")
public void setPersonService(PersonService ps){
this.personService = ps;
}
#RequestMapping(value = "/persons", method = RequestMethod.GET)
public String listPersons(Model model) {
model.addAttribute("person", new Person());
model.addAttribute("listPersons", this.personService.listPersons());
return "person";
}
//For add and update person both
#RequestMapping(value= "/person/add", method = RequestMethod.POST)
public String addPerson(#ModelAttribute("person") Person p,#ModelAttribute("user") User u){
String name = p.getName();
System.out.println("name is :"+name);
if(name == null || name == "") {
System.out.println("user is"+name);
return "user";
}
else{
//new person, add it
this.personService.addPerson(p);
}
return "redirect:/persons";
}
#RequestMapping(value = "/user/add", method = RequestMethod.POST)
public String addUser(#ModelAttribute("user") User user) {
// new user, add to DB
this.userService.addUser(user);
return "redirect:/persons";
}
PersonDAOImpl.java
#Repository
public class PersonDAOImpl implements PersonDAO {
private static final Logger logger = LoggerFactory.getLogger(PersonDAOImpl.class);
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sf){
this.sessionFactory = sf;
}
#Override
public void addPerson(Person p) {
Session session = this.sessionFactory.getCurrentSession();
session.persist(p);
logger.info("Person saved successfully, Person Details="+p);
}
#Override
public void updatePerson(Person p) {
Session session = this.sessionFactory.getCurrentSession();
session.update(p);
logger.info("Person updated successfully, Person Details="+p);
}
#SuppressWarnings("unchecked")
#Override
public List<Person> listPersons() {
Session session = this.sessionFactory.getCurrentSession();
List<Person> personsList = session.createQuery("from Person").list();
for(Person p : personsList){
logger.info("Person List::"+p);
}
return personsList;
}
#Override
public Person getPersonByName(String name) {
Session session = this.sessionFactory.getCurrentSession();
List<Person> usersList = session.createQuery(
"from Person ").list();
if (usersList.size() == 0)
return null;
Person usrObj1 = usersList.get(0);
return usrObj1;
}
UserDAOImpl.java
#Repository
public class UserDAOImpl implements UserDAO {
private static final Logger logger = LoggerFactory
.getLogger(UserDAOImpl.class);
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sf) {
this.sessionFactory = sf;
}
#Override
public void addUser(User user) {
Session session = this.sessionFactory.getCurrentSession();
session.persist(user);
logger.info("User saved successfully, User Details=" + user);
}
#Override
public void updateUser(User user) {
Session session = this.sessionFactory.getCurrentSession();
session.update(user);
logger.info("User updated successfully, User Details=" + user);
}
#SuppressWarnings("unchecked")
#Override
public List<User> listUsers() {
Session session = this.sessionFactory.getCurrentSession();
List<User> usersList = session.createQuery("from User").list();
for (User user : usersList) {
logger.info("User List::" + user);
}
return usersList;
}
#SuppressWarnings("unchecked")
#Override
public User getUserByName(String fullName) {
Session session = this.sessionFactory.getCurrentSession();
List<User> usersList = session.createQuery(
"from User ").list();
if (usersList.size() == 0)
return null;
User usrObj1 = usersList.get(0);
return usrObj1;
}
Person.java
#Entity
#Table(name="PERSON")
public class Person {
#Id
#Column(name="id")
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
private String name;
private String country;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
#Override
public String toString(){
return "id="+id+", name="+name+", country="+country;
}
}
User.java
#Entity
#Table(name = "user")
#XmlRootElement(name = "User")
public class User {
#Id
#Column(name = "id")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
#Column(name = "fullname")
private String fullName;
#Column(name = "password")
private String password;
#Column(name = "email")
private String email;
#Column(name = "phone")
private Integer phone;
#XmlElement(name = "Id")
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#XmlElement(name = "FullName")
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
#XmlElement(name = "Password")
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
#XmlElement(name = "EmailId")
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#XmlElement(name = "PhoneNo")
public Integer getPhone() {
return phone;
}
public void setPhone(Integer phone) {
this.phone = phone;
}
PersonServiceImpl.java
#Service
public class PersonServiceImpl implements PersonService {
private PersonDAO personDAO;
public void setPersonDAO(PersonDAO personDAO) {
this.personDAO = personDAO;
}
#Override
#Transactional
public void addPerson(Person p) {
this.personDAO.addPerson(p);
}
#Override
#Transactional
public void updatePerson(Person p) {
this.personDAO.updatePerson(p);
}
#Override
#Transactional
public List<Person> listPersons() {
return this.personDAO.listPersons();
}
#Override
#Transactional
public Person getPersonById(int id) {
return this.personDAO.getPersonById(id);
}
#Override
#Transactional
public Person getPersonByName(String name) {
return this.personDAO.getPersonByName(name);
}
#Override
#Transactional
public void removePerson(int id) {
this.personDAO.removePerson(id);
}
UserServiceImpl.java
#Service
public class UserServiceImpl implements UserService {
private UserDAO userDAO;
public void setUserDAO(UserDAO userDAO) {
this.userDAO = userDAO;
}
#Override
#Transactional
public void addUser(User user) {
this.userDAO.addUser(user);
}
#Override
#Transactional
public void updateUser(User user) {
this.userDAO.updateUser(user);
}
#Override
#Transactional
public List<User> listUsers() {
return this.userDAO.listUsers();
}
#Override
#Transactional
public User getUserById(int id) {
return this.userDAO.getUserById(id);
}
#Override
#Transactional
public void removeUser(int id) {
this.userDAO.removeUser(id);
}
#Override
#Transactional
public User getUserByName(String fullName) {
return this.userDAO.getUserByName(fullName);
}
}
person.jsp
<c:url var="addAction" value="/person/add" ></c:url>
<form:form action="${addAction}" commandName="person">
<table>
<c:if test="${!empty person.name}">
<tr>
<td>
<form:label path="id">
<spring:message text="ID"/>
</form:label>
</td>
<td>
<form:input path="id" readonly="true" size="8" disabled="true" />
<form:hidden path="id" />
</td>
</tr>
</c:if>
<tr>
<td>
<form:label path="name">
<spring:message text="Name"/>
</form:label>
</td>
<td>
<form:input path="name" />
</td>
</tr>
<tr>
<td>
<form:label path="country">
<spring:message text="Country"/>
</form:label>
</td>
<td>
<form:input path="country" />
</td>
</tr>
<tr>
<td colspan="2">
<input type="submit"
value="<spring:message text="Add Person"/>" />
<input type="submit"
value="<spring:message text="Register"/>" />
</td>
</tr>
</table>
</form:form>
user.jsp
<c:url var="addAction" value="/user/add"></c:url>
<form:form action="${addAction}" commandName="user">
<table width="400px" height="150px">
<c:if test="${!empty user.email}">
<tr>
<td><form:label path="id">
<spring:message text="ID" />
</form:label></td>
<td><form:input path="id" readonly="true" size="8"
disabled="true" /> <form:hidden path="id" /></td>
</tr>
</c:if>
<c:if test="${!empty user.email}">
</c:if>
<tr>
<td><form:label path="fullName">
<spring:message text="Full Name" />
</form:label></td>
<td><form:input path="fullName" /></td>
</tr>
<tr>
<td><form:label path="password">
<spring:message text="Password" />
</form:label></td>
<td><form:input type="password" path="password" /></td>
</tr>
<tr>
<td><form:label path="email">
<spring:message text="Email" />
</form:label></td>
<td><form:input path="email" /></td>
</tr>
<tr>
<td><form:label path="phone">
<spring:message text="Phone" />
</form:label></td>
<td><form:input path="phone" /></td>
</tr>
<tr>
<td colspan="2"><c:if test="${!empty user.email}">
<input type="submit"
value="<spring:message text="Update Details"/>" />
</c:if> <c:if test="${empty user.email}">
<input type="submit" value="<spring:message text="Submit"/>" />
</c:if></td>
</tr>
</table>
</form:form>
Any suggestion or advice in this it will be helpful for me
THanking You
I hope this helps!
https://en.wikipedia.org/wiki/List_of_HTTP_status_codes
400 Bad Request
The server cannot or will not process the request due to an apparent client error (e.g., malformed request syntax, too large size, invalid request message framing, or deceptive request routing).
You have not defined the http method attribute of your form:
<form:form action="${addAction}" commandName="user">
Then, the default method is GET, therefore it wont never found a controller because your controller /user/add expects RequestMethod.POST
If you add the method attribute It will work:
<form:form action="${addAction}" commandName="user" method="POST">
Im running a Spring MVC application using JPA for persistence. I have a form which has an update button. When this button is clicked its supposed to update a users record in the database. The User table has an embedded table Address in it. I am able to access all the fields in the User table but not the embedded table. Here is my Request mapping
#RequestMapping(value="/user/{userid}",method=RequestMethod.POST)
public String Update(#ModelAttribute("user")User user,#PathVariable("userid") String userid,Model model){
Here is my User.java
#Entity
#Table(name="User")
public class User {
#Id
#Column(name = "userid")
private String id;
#Column(name="firstname")
private String firstname;
#Column(name="lastname")
private String lastname;
#Column(name="title")
private String title;
#Embedded
private Address address;
#ManyToMany
#JoinTable(name="phone_user", joinColumns={#JoinColumn(name="userid")},
inverseJoinColumns={#JoinColumn(name="phoneid")})
private List<Phone> phones;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
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 getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public List<Phone> getPhones() {
return phones;
}
public void setPhones(List<Phone> phones) {
this.phones = phones;
}
}
Note the #Embedded tag of Address field.
Here is my Address.java
#Embeddable
public class Address {
String street;
String city;
String state;
String zip;
#Column(name="street")
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
#Column(name="city")
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
#Column(name="state")
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
#Column(name="zip")
public String getZip() {
return zip;
}
public void setZip(String zip) {
this.zip = zip;
}
}
Here is my JSP which sends the form data
<html>
<head>
<title>Home</title>
</head>
<body>
<h1>
Hello world!
</h1>
<form method="POST" action="/cmpe275/user/${userid}">
<table>
<tr>
<td>Name</td>
<td><input type="text" readonly="readonly" name="userid" value="${id}"/></td>
</tr>
<tr><tr><tr><tr><tr><tr><tr><tr><tr>
<td>First Name</td>
<td><input type="text" name="firstname" value="${firstname}"/></td>
<td>Last Name</td>
<td><input type="text" name="lastname" value="${lastname}"/></td>
</tr>
<tr>
<tr><tr><tr><tr>
<td>Street</td>
<td><input type="text" name="street" value="${street}"/></td>
<td>City</td>
<td><input type="text" name="city" value="${city}"/></td>
<td>State</td>
<td><input type="text" name="state" value="${state}"/></td>
<td>Zip</td>
<td><input type="text" name="zip" value="${zip}"/></td>
</tr>
<tr><tr><tr><tr>
<td><input type="submit" onclick="updateUser();" name="Update" value="Update"/></td>
<td><input type="button" name="Delete" value="Delete"/></td>
</table>
</form>
</body>
<script>
function updateUser(){
console.log("hi");
}
</script>
</html>
I am unable to access the address fields using the getter/setters.
For example - In my handler mapping - To get the first name of the updated profile I can access it using :
user.getFirstName()
But If i want to access the updated Address I do a
user.getAddress.getCity()
I get a null value.
Any idea why?
I think this
<td><input type="text" name="street" value="${street}"/></td>
<td>City</td>
<td><input type="text" name="city" value="${city}"/></td>
<td>State</td>
<td><input type="text" name="state" value="${state}"/></td>
<td>Zip</td>
<td><input type="text" name="zip" value="${zip}"/></td>
should be
<td><input type="text" name="address.street" value="${address.street}"/></td>
<td>City</td>
<td><input type="text" name="address.city" value="${address.city}"/></td>
<td>State</td>
<td><input type="text" name="address.state" value="${address.state}"/></td>
<td>Zip</td>
<td><input type="text" name="address.zip" value="${address.zip}"/></td>
A spring controller is expecting the #ModelAttribute or #RequestBody to be structured like the POJO. So if you where not using a form and sending this data vs some js it would look something like
{
'firstname':'peter',
'lastname': 'griffen',
'address': {
'street':'31 Spooner Street'
}
}
What you had was the object completely flat. Which might work if you add the correct setters in the User class.
i tried to save data in to table by spring but this error show when data submitted..
org.springframework.beans.NotReadablePropertyException: Invalid property 'user' of bean class [com.jit.model.Signup]: Bean property 'user' is not readable or has an invalid getter method: Does the return type of the getter match the parameter type of the setter?
controller class
#Controller
public class DatabaseController
{
#RequestMapping("/signup.htm")
public String loginCheck(#ModelAttribute("bean") #Valid Signup bean,BindingResult result,HttpServletRequest request , HttpServletResponse response) throws IOException {
Session session= HiberSession.getHiber();
if (result.hasErrors()){
return "signup";
} else{
session.save(bean);
return "abc";
}
Bean class
#Entity
#Table(name="user")
public class Signup {
#Id
#GeneratedValue
#Column(name="uid")
private Integer uid;
#NotEmpty
#Column(name="name")
private String name;
#NotEmpty
#Column(name="father_name")
private String father;
#NotEmpty
#Size(min =4,max =10)
#Column(name="password")
private String pass;
#NotEmpty
#Length(min =10,max =10)
#Column(name="contact")
private String contact;
#NotEmpty
#Column(name="city")
private String city;
#NotNull
#Column(name="introducer")
private Integer introducer;
#Column(name="status")
private Integer status;
#Column(name="amount")
private Integer amount=400;
public Integer getAmount() {
return amount;
}
public void setAmount(Integer amount) {
this.amount = amount;
}
public Integer getUid() {
return uid;
}
public void setUid(Integer uid) {
this.uid = uid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getFather() {
return father;
}
public void setFather(String father) {
this.father = father;
}
public String getPass() {
return pass;
}
public void setPass(String pass) {
this.pass = pass;
}
public String getContact() {
return contact;
}
public void setContact(String contact) {
this.contact = contact;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public Integer getIntroducer() {
return introducer;
}
public void setIntroducer(Integer introducer) {
this.introducer = introducer;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
}
signup.jsp
<%#page language="java" contentType="text/html"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<html>
<head>
<style>
.error {
color: #ff0000;
}
</style>
</head>
<body>
<c:if test="${not empty message}"><h2>${message}</h2></c:if>
<h3>New user registration form..</h3>
<form:form method="POST" commandName='bean' action="/jit/signup.htm">
<table>
<tr>
<td>Name :</td>
<td><form:input path="name"/></td>
<td><form:errors path="name" cssClass="error"/></td>
</tr>
<tr>
<td>Father Name :</td>
<td><form:input path="father"/></td>
<td><form:errors path="father" cssClass="error"/></td>
</tr>
<tr>
<td>Password :</td>
<td><form:password path="pass" /></td>
<td><form:errors path="pass" cssClass="error" /></td>
</tr>
<tr>
<td>Contact Number :</td>
<td><form:input path="contact"/></td>
<td><form:errors path="contact" cssClass="error"/></td>
</tr>
<tr>
<td>City/Village :</td>
<td><form:input path="city"/></td>
<td><form:errors path="city" cssClass="error"/></td>
</tr>
<tr>
<tr>
<td>Introducer ID:</td>
<td><form:input path="introducer"/></td>
<td><form:errors path="introducer" cssClass="error"/></td>
</tr>
<tr>
<td colspan="3"><input type="submit" /></td>
</tr>
</table>
</form:form>
</body>
</html>
I'd say that you should avoid having table names that are reserved words, with hibernate. Sure you can escape it, but it may cause problems in the future (in a query for example). So the safest way is to name the table another way - say users
#Entity
#Table(name="users")
public class Signup {
}
I am new to Thymeleaf, I try to execute a simple form submittion example using Thymeleaf and Spring MVC. I wrote the code according to Thymeleaf documentation. But I am getting null values in the controller.
<form action="thymeleafexample/thymeleaf.html" th:action="#{/thymeleaf}"
th:object="${loginModel}" method="post">
<table>
<tr>
<td th:text="#{emp.empId.label}">Emp ID</td>
<td><input type="text" th:field="*{empId}"/></td>
</tr>
<tr>
<td th:text="#{emp.empName.label}">Emp Name</td>
<td><input type="text" th:field="*{empName}"/></td>
</tr>
<tr>
<td>
<button type="submit" name="save" th:text="#{${'.emp.button.label'}}">submit</button>
</td>
</tr>
</table>
</form>
and my Controller is
#RequestMapping(value = "/thymeleaf", params = {"save"})
public String save(#Validated LoginModel loginModel, final BindingResult bindingResult, ModelMap model) {
if (bindingResult.hasErrors()) {
return "thymeleaf";
}
System.out.println(loginModel);
System.out.println(loginModel.getEmpName());
return "/thymeleaf";
}
and my Model class is
public class LoginModel {
private String empName;
private int empId;
public void setEmpId(int empId) {
this.empId = empId;
}
public int getEmpId() {
return empId;
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
}
I was having the same problem and as OP mentioned, creating a constructor for the POJO(Model) class with necessary member fields and using th:field=*{foo} instead of th:value=${foo} solved my issue.