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.
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 am populate a List of String as radio button in the JSP. I add the List to the ModelMap but still the below Exception occurred. What am i missing please?
Attribute 'items' must be an array, a Collection or a Map:
java.lang.IllegalArgumentException: Attribute 'items' must be an
array, a Collection or a Map
#Controller
public class EmployeeController {
#Autowired
private EmployeeManager employeeManager;
#RequestMapping(value = {"/"}, method = RequestMethod.GET)
public String homePage(ModelMap map) {
map.addAttribute("employee", new Employee());
populateDepartments(map);
return "addEmployee";
}
private void populateDepartments(ModelMap map){
List<String> departments = new ArrayList<String>();
departments.add("Dept 1");
departments.add("Dept 2");
map.addAttribute("departments",departments);
}
}
addEmployee.jsp:
<form:form method="post" action="add" commandName="employee">
<table>
<tr>
<td><form:label path="name">Name</td>
<td><form:input path="name" /></td>
<td>Address</td>
<td><form:input path="address" /></td>
<td>Departments</td>
<td><form:radiobuttons path="empDepartment" items="${departments}"/></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Add"/>
</td>
</tr>
</table>
</form:form>
The entity
#Entity
public class Employee {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Integer id;
private String name;
private String address;
#Transient
private String empDepartment;
}
I have a table cards which is related to some other master tables (divisions and units) with one to one relation.
On UI I am showing drop downs to select the division and unit values for card, this is the function to create form in CardController.java
#RequestMapping(value = "/addCardForm", method = RequestMethod.GET)
public String addCardForm(ModelMap map)
{
map.addAttribute("divisions", divisionService.getAllDivisions());
map.addAttribute("units", unitService.getAllUnits());
return "admin/addCard";
}
addCard.jsp :
<form:form method="post" action="addCard">
<table cellspacing="10" id="card-table">
<tr>
<td><label for="division" class="control-label">Division : </label></td>
<td><select name="division" class="selectpicker">
<option>Select</option>
<c:forEach items="${divisions}" var="division">
<option value="${division.id}">${division.name}</option>
</c:forEach>
</select></td>
</tr>
<tr>
<td><label for="unit" class="control-label">Unit : </label></td>
<td><select name="unit" class="selectpicker">
<option>Select</option>
<c:forEach items="${units}" var="unit">
<option value="${unit.id}">${unit.name}</option>
</c:forEach>
</select></td>
</tr>
<tr>
<td><button type="submit" class="btn btn-primary">Submit</button></td>
<td></td>
</tr>
</table>
</form>
Drop downs are populated with the data but on submitting form its not setting division or unit to the cardEntity object they are set to null, this is the addCard function in controller :
#RequestMapping(value = "/addCard", method = RequestMethod.POST)
public String addCard(#ModelAttribute(value="card") CardEntity card, BindingResult result)
{
cardService.addCard(card);
//card.getDivision(); -- this is null
return "redirect:/card";
}
There are other fields which are added in the card except drop downs.
CardEntity.java
#Entity
#Table(name="cards")
#Proxy(lazy=false)
public class CardEntity {
#Id
#Column(name="id")
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
#OneToOne
#JoinColumn(name="division_id", referencedColumnName="id")
private DivisionEntity division;
#OneToOne
#JoinColumn(name="unit_of_qty_id", referencedColumnName="id")
private UnitEntity units;
public DivisionEntity getDivision() {
return division;
}
public void setDivision(DivisionEntity division) {
this.division = division;
}
public UnitEntity getUnits() {
return units;
}
public void setUnits(UnitEntity units) {
this.units = units;
}
}
Edit :
I have to set divisionEntity and unitEntity manually :
#RequestMapping(value = "/addCard", method = RequestMethod.POST)
public String addCard(HttpServletRequest request, #ModelAttribute(value="card") CardEntity card, BindingResult result)
{
card.setDivision(divisionService.findOne(Integer.parseInt(request.getParameter("division"))));
card.setUnit(unitService.findOne(Integer.parseInt(request.getParameter("unit"))));
cardService.addCard(card);
return "redirect:/card";
}
So I guess the problem is divisionEntity and unitEntity objects are not set in card after submitting the form.
You can do this too:
<tr>
<td><label for="division.id" class="control-label">Division : </label></td>
<td><select name="division.id" class="selectpicker">
<option>Select</option>
<c:forEach items="${divisions}" var="division">
<option value="${division.id}">${division.name}</option>
</c:forEach>
</select></td>
</tr>
<tr>
<td><label for="unit.id" class="control-label">Unit : </label></td>
<td><select name="unit.id" class="selectpicker">
<option>Select</option>
<c:forEach items="${units}" var="unit">
<option value="${unit.id}">${unit.name}</option>
</c:forEach>
</select></td>
</tr>
The rest is same as your original. But:
Make sure you have a default constrcutor in Division class;
The CardEntity should have getUnit() and setUnit(), not getUnits() and setUnits().
Hope it help.
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 have a form like this :
<form:form method="POST" action="searchProjects" commandName="projectcriteria">
<table>
<tr>
<td class="label"><spring:message code="number" /></td>
<td><form:input path="number" /></td>
<td class="label"><spring:message code="customer" /></td>
<td><form:input path="customer" /></td>
</tr>
<tr>
<td class="label"><spring:message code="name" /></td>
<td><form:input path="name" /></td>
<td class="label"><spring:message code="status" /></td>
<td>
<form:select path="status">
<option value=""><spring:message code="please_select" /></option>
<c:forEach var="enum" items="${allStatus}">
<option value="${enum}"><spring:message code="${enum.statusEnum}" /></option>
</c:forEach>
</form:select>
</td>
</tr>
<tr>
<td colspan="4" style="text-align: center;">
<input type="submit" value="<spring:message code="search"/>" />
<input type="button" value="<spring:message code="reset_criteria"/>" />
</td>
</tr>
</table>
</form:form>
The Projectcriteria and the StatusEnum are like this:
public enum StatusEnum {
INV("Invalidate"),
TOV("Validate"),
VAL("Validated"),
FIN("Finished");
private String name;
private StatusEnum(String name) {
this.name = name;
}
public String getStatusEnum() {
return this.name;
}
}
public class ProjectCriteria {
private long number;
private String name;
private String customer;
private StatusEnum status;
/**
* #return the number
*/
public long getNumber() {
return number;
}
/**
* #param number the number to set
*/
public void setNumber(long number) {
this.number = number;
}
/**
* #return the name
*/
public String getName() {
return name;
}
/**
* #param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* #return the customer
*/
public String getCustomer() {
return customer;
}
/**
* #param customer the customer to set
*/
public void setCustomer(String customer) {
this.customer = customer;
}
/**
* #return the status
*/
public StatusEnum getStatus() {
return status;
}
/**
* #param status the status to set
*/
public void setStatus(StatusEnum status) {
this.status = status;
}
}
How do I populate the StatusEnum attribute in the ProjectCriteria class to the jsp page. What do i have to put into the Controller?
Thanks a lot for any help.
Add your enum values in Controller method which giving request to respective page i.e.
model.addAttribute("enumValues",StatusEnum.value());
Then iterate enumValues in dropdown menu using foreach.
You could try this (sorry code not tested):
<c:forEach var="enum" items="${StatusEnum.values()}">
<option value="${enum}"><spring:message code="${enum.name}" /></option>
</c:forEach>
Note: if your enum class has a package name, you might have to include the fully qualified class name in the items attribute. You might be able to pass the enum as a model attribute from your controller as well (?).