Spring one-to-many Object in Thymeleaf Tab - java

I am using Spring and Thymeleaf templates. What I am trying is, to show a customer's addresses within a Thymeleaf template (using Bootstrap tabs) in a many-to-one relation.
I can't get the addresses to show up or add new ones. Any help is appreciated!
customerAddressform.html (Thymeleaf)
<html>
<head lang="en">
<!--/*/ <th:block th:include="fragments/headerinc :: head"></th:block> /*/-->
</head>
<body>
<div th:if="${not #lists.isEmpty(address)}">
<table class="table table-striped table-bordered table-hover">
<thead class="thead-dark">
<tr>
<th>Id</th>
<th>Address Id</th>
<th>Description</th>
<th>Price</th>
<th>Delete</th>
</tr>
</thead>
<tr th:each="address : ${address}">
<td th:text="${address.id}" href="/customer/${customer.id}/address/${address.id}">Id</td>
<td><a th:text="${address.addressId}" th:href="${ '/customer/' + customer.id + '/address/' + address.id}">Address
Id</a></td>
<td>description</td>
<td>price</td>
<td><a>Delete</a></td>
</tr>
</table>
</div>
<div>
<!-- Button trigger modal -->
<button type="button" href="#" class="btn-primary btn-sm btn-block btn-addrow" data-toggle="modal"
data-target="#modalNewCustomerAddress">+</button>
<!-- Modal -->
<div class="modal fade" id="modalNewCustomerAddress" tabindex="-1" role="dialog" aria-labelledby="New Address"
aria-hidden="true">
<div class="modal-dialog modal-dialog-centered modal-dialog-scrollable" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalScrollableTitle">New Address</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body margin-15">
<form id="customerAddressForm" th:object="${address}" th:action="#{/customer/{customer.id}/address/new}" method="post">
<div class="row">
<input type="hidden" />
<input type="hidden" />
<label for="streetName">Street:</label>
<input type="text" class="form-control form-control-lg" th:field="*{streetName}" id="streetName" />
<label for="houseNumber">House Number:</label>
<input type="text" class="form-control form-control-lg" id="houseNumber"/>
<label for="postalCode">Postal Code:</label>
<input type="text" class="form-control form-control-lg" id="postalCode"/>
<label for="city">City:</label>
<input type="text" class="form-control form-control-lg" id="city"/>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" form="customerAddressForm" class="btn btn-primary">Save</button>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
AddressController.java
#Controller
public class AddressController {
private AddressService addressService;
#Autowired
public void setAddressService(AddressService addressService) {
this.addressService = addressService;
}
#RequestMapping(value = "/address", method = RequestMethod.GET)
public String list(Model model){
model.addAttribute("address", addressService.listAllAddress());
System.out.println("Returning address:");
return "customerAddress";
}
// #RequestMapping("address/{id}")
// public String showAddress(#PathVariable Integer id, Model model){
// model.addAttribute("address", addressService.getAddressById(id));
// return "addressshow";
// }
#RequestMapping("customer/{customer.id}/address")
public String edit(#PathVariable Integer id, Model model){
model.addAttribute("address", addressService.getAddressById(id));
return "customerAddressform";
}
#RequestMapping("customer/{customer.id}/address/new")
public String newAddress(Model model){
model.addAttribute("address", new Address());
return "customerAddressform";
}
// #RequestMapping(value = "address", method = RequestMethod.POST)
// public String saveAddress(Address address){
// addressService.saveAddress(address);
// //return "redirect:/addresss";
// return "redirect:/address/" + address.getId();
// }
#RequestMapping("customer/{customer.id}/deleteAddress")
public String deleteAddress(#RequestParam Integer id) {
addressService.deleteAddressById(id);
return "redirect:/customer/{customer.id}/address";
}
}
Address.java
#Entity
public class Address {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
#Version
private Integer version;
private String addressId;
private String addressType;
private String streetName;
private String houseNumber;
private String postalCode;
private String cityName;
private String country;
#ManyToOne(fetch = FetchType.LAZY, optional = false)
#JoinColumn(name = "customer_id", nullable = false)
#OnDelete(action = OnDeleteAction.CASCADE)
private Customer customer;
public Address(){
}
public Address(String addressId, String addressType, String streetName, String houseNumber, String postalCode, String cityName, String country, Customer customer){
this.addressId = addressId;
this.addressType = addressType;
this.streetName = streetName;
this.houseNumber = houseNumber;
this.postalCode = postalCode;
this.cityName = cityName;
this.country = country;
this.customer = customer;
}
Customer.java
#Entity
public class Customer {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
#Version
private Integer version;
private String customerId;
private String name;
#OneToMany(fetch=FetchType.LAZY, mappedBy="customer")
private Set<Address> address;

Related

'Required request parameter 'id' for method parameter type Integer is present but converted to null'

I'm creating todo-app with spring-boot.
After adding a task, once I enter a check on checkbox provided next to each todo and then click the done-button, the error occurs.'Required request parameter 'id' for method parameter type Integer is present but converted to null' has occurs.
below is codes.
Todo.java
#Entity
#Data
#Table(name = "todos")
public class Todo {
#Id
#Nullable
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#Nullable
#Column(name = "user_id", nullable = false)
private Integer userId;
#NotNull
#NotBlank
#Column(name = "title")
private String title;
#NotNull
#NotBlank
#Column(name = "description")
private String description;
#NotNull
#NotBlank
#Column(name = "due_date")
private String dueDate;
#Column(name = "priority")
private Integer priority;
#NotNull
#Column(name = "is_completed")
private Boolean isCompleted = false;
public Todo() {
}
public Todo(Integer userId, String title, String description, String dueDate, Integer priority, Boolean isCompleted) {
this.userId = userId;
this.title = title;
this.description = description;
this.dueDate = dueDate;
this.priority = priority;
this.isCompleted = isCompleted;
}
}
TodoController.java
#Controller
public class TodoController {
#Autowired
TodoRepository todoRepository;
#Autowired
TodoService todoService;
#GetMapping("/todo/{id}")
public String home(Model model, User user, Todo todo, #PathVariable("id")Integer id) {
Integer userId = user.getId();
if(userId == null) {
return "redirect:/todo/{id}";
}
List<Todo> list = todoRepository.find(userId);
model.addAttribute("list", list);
model.addAttribute("todo", new Todo(user.getId(), todo.getTitle(), todo.getDescription(), todo.getDueDate(), todo.getPriority(), todo.getIsCompleted()));
return "home";
}
#PostMapping("/todo/{id}")
public String createTodo(#Validated Todo todo,BindingResult result, User user) {
if(result.hasErrors()){
return "redirect:/todo/{id}";
}
Todo userTodo = new Todo(user.getId(), todo.getTitle(), todo.getDescription(), todo.getDueDate(), todo.getPriority(), todo.getIsCompleted());
todoService.addTodo(userTodo);
return "redirect:/todo/{id}";
}
#PostMapping("/todo/update/{id}")
public String doneTodo(#RequestParam(name="id")Integer todoId) {
Todo updateTodo = todoService.findById(todoId);
updateTodo.setIsCompleted(true);
todoService.addTodo(updateTodo);
return "redirect:/todo/{id}";
}
#PostMapping("/todo/edit/{id}")
public String editTodo() {
System.out.println("edit");
return "redirect:/todo/{id}";
}
}
TodoService.java
#Service
public class TodoService {
#Autowired
TodoRepository todoRepository;
public List<Todo> searchAll() {
return todoRepository.findAll();
}
public void addTodo(Todo todo) {
todoRepository.save(todo);
}
public Todo findById(Integer id) {
Optional<Todo> updateTodo = todoRepository.findById(id);
return updateTodo.orElseGet(updateTodo::get);
}
}
home.html
<html xmlns:th="http://www.thymeleaf.org" xmlns="http://www.w3.org/1999/html">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<link th:href="#{/css/home.css}" rel="stylesheet"/>
<title>Todo</title>
</head>
<body>
<h1>Todo</h1>
<div>
<form method="post" th:action="#{/todo/}+${id}" th:object="${todo}">
<p th:errors="*{title}" class="todo-error-message"></p>
<input th:field="*{title}" class="add-input" type="text" placeholder="title">
<input th:field="*{description}" class="add-input" type="text" placeholder="details">
<input th:field="*{dueDate}" class="add-input-third" type="date"><br/>
<div class="add-form">
<span>priority</span>
<input th:field="*{priority}" type="radio" name="priority" value="3" checked>3
<input th:field="*{priority}" type="radio" name="priority" value="2">2
<input th:field="*{priority}" type="radio" name="priority" value="1">1
</div>
<button type="submit" class="add-btn">add</button>
</form>
</div>
<h2>LIST</h2>
<form method="post" th:action="#{/todo/edit/}+${id}" th:each="list:${list}" th:object="${todo}">
<div th:if="${!todo.isCompleted}">
<input type="checkbox" th:id="${todo.id}" th:value="${todo.id}" th:field="*{isCompleted}" form="done-todo">
<input type="hidden" name="userId" th:value="${list.userId}">
<input type="text" name="title" th:value="${list.title}">
<input type="text" name="description" th:value="${list.description}">
<input type="date" name="dueDate" th:value="${list.dueDate}">
<input type="submit" value="update">
</div>
</form>
<form method="post" id="done-todo" th:action="#{/todo/update/}+${id}">
<input type="hidden" name="id" th:value="${todo.id}">
<input type="submit" value="done">
</form>
<div>
<button type="button" class="btn btn-primary p-3" data-toggle="collapse" data-target="#collapseExample" aria-expanded="false" aria-controls="collapseExample">
show done todos
</button>
<div class="collapse" id="collapseExample">
<form class="border p-3" th:action="#{/todo/delete/}+${id}" th:each="todo:${todo}">
<div th:if="${todo.isCompleted}">
<input type="text" name="title" th:value="${todo.title}">
<input type="submit" value="delete">
</div>
</form>
</div>
</div>
<form th:action="#{/logout}" method="post">
<button class="logout-button" type="submit" value="logout">logout</button>
</form>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
</body>
</html>
What I want to do
I aim to change the value of added todo from false to true after entering a check on checkbox provided next to each todo and then click the done-button.
I aim to show todos of which value is true.(true means 'done')
Does anyone know how to fix this?
I couldn't find the way to fix this and I’m so badly stuck at this task.

Failed to convert value of type 'java.lang.String' to required type 'example.entity.Address'

#Getter
#Setter
#AllArgsConstructor
#NoArgsConstructor
#Entity
#Table(name="addresses")
public class Address {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private Long add_id;
#Column
private String address;
#Column
private String postalcode;
#Column
private String city;
#Column
private String state;
#Column
private String country;
public Long getAdd_id() {
return add_id;
}
public void setAdd_id(Long add_id) {
this.add_id = add_id;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPostalcode() {
return postalcode;
}
public void setPostalcode(String postalcode) {
this.postalcode = postalcode;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
}
HTML Page :
<form
method="post"
role="form"
th:action="#{/address/save}"
th:object="${address}"
>
<input type="hidden" th:field="*{add_id}" />
<div class="form-group mb-3">
<label class="form-label">Address</label>
<input
class="form-control"
id="address"
name="address"
placeholder="Enter Address"
th:field="*{address}"
type="text"
/>
<p th:errors = "*{address}" class="text-danger"
th:if="${#fields.hasErrors('address')}"></p>
</div>
<div class="form-group mb-3">
<label class="form-label">Postal Code</label>
<input
class="form-control"
id="postalcode"
name="postalcode"
placeholder="Enter Postal Code"
th:field="*{postalcode}"
type="text"
/>
<p th:errors = "*{postalcode}" class="text-danger"
th:if="${#fields.hasErrors('postalcode')}"></p>
</div>
<div class="form-group mb-3">
<label class="form-label">City</label>
<input
class="form-control"
id="city"
name="city"
placeholder="Enter City"
th:field="*{city}"
type="text"
/>
<p th:errors = "*{city}" class="text-danger"
th:if="${#fields.hasErrors('city')}"></p>
</div>
<div class="form-group mb-3">
<label class="form-label">State</label>
<input
class="form-control"
id="state"
name="state"
placeholder="Enter State"
th:field="*{state}"
type="text"
/>
<p th:errors = "*{state}" class="text-danger"
th:if="${#fields.hasErrors('state')}"></p>
</div>
<div class="form-group mb-3">
<label class="form-label">Country</label>
<input
class="form-control"
id="country"
name="country"
placeholder="Enter Country"
th:field="*{country}"
type="text"
/>
<p th:errors = "*{country}" class="text-danger"
th:if="${#fields.hasErrors('country')}"></p>
</div>
<div class="form-group" style="text-align:center">
<button class="btn btn-success" type="submit">Save</button>
</div>
</form>
Controller:
#Autowired
private AddressRepository addressRepository;
#GetMapping("/address/{id}")
public String addAddress(#PathVariable("id") Long add_id, Model model){
System.out.println("\nInside addressform :\n");
#SuppressWarnings("deprecation")
Address address = addressRepository.getById(add_id);
System.out.println(address.getAdd_id());
System.out.println("add_id : "+add_id);
model.addAttribute("address", address);
return "addressform";
}
// handler method to handle post request to save address
#PostMapping("/address/save")
public String saveAddress(#Valid #ModelAttribute("address") Address address) {
System.out.println("\nInside address save method.");
System.out.println(address.getAdd_id());
System.out.println(address.getAddress());
System.out.println(address.getPostalcode());
System.out.println(address.toString());
addressRepository.save(address);
return "redirect:/users";
}
ERROR :
There was an unexpected error (type=Bad Request, status=400).
Failed to convert value of type 'java.lang.String' to required type 'example.entity.Address'; Failed to convert from type [java.lang.String] to type [java.lang.Long] for value 'madhapur'
org.springframework.beans.TypeMismatchException: Failed to convert value of type 'java.lang.String' to required type 'example.entity.Address'; Failed to convert from type [java.lang.String] to type [java.lang.Long] for value 'madhapur'
at org.springframework.beans.TypeConverterSupport.convertIfNecessary(TypeConverterSupport.java:79)
at org.springframework.beans.TypeConverterSupport.convertIfNecessary(TypeConverterSupport.java:53)
at org.springframework.validation.DataBinder.convertIfNecessary(DataBinder.java:729)
at org.springframework.web.servlet.mvc.method.annotation.ServletModelAttributeMethodProcessor.createAttributeFromRequestValue(ServletModelAttributeMethodProcessor.java:142)
at org.springframework.web.servlet.mvc.method.annotation.ServletModelAttributeMethodProcessor.createAttribute(ServletModelAttributeMethodProcessor.java:78)
at org.springframework.web.method.annotation.ModelAttributeMethodProcessor.resolveArgument(ModelAttributeMethodProcessor.java:147)
at org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:122)
at org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:181)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:148)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:117)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:884)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:797)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
Firstly I figured out couple of codes that can cause serious performance issues and is not advised.
Here's a few:
Take off your Generated Getters and Setters and Leave the annotation #Getter and #Setter to do the work.
Take off <input type="hidden" th:field="*{add_id}" /> as it will be auto-generated from your entity Address private Long add_id
Take off address.toString() from your saveAddress controller as this is not needed to parse data to your Entity, your entity receives String already which will be parsed from your form, there is no need to convert with toString again.
One of your error states Failed to convert from type [java.lang.String] to type [java.lang.Long] which simply means you're trying to convert Long to String which should be auto generated by your Entity
I hope this helps!!!

How to configure the modal to display the retrieved data from a table in springboot?

Customer.java
#Entity
#Data
#AllArgsConstructor
#NoArgsConstructor
public class Customer {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String relative;
private String address;
private Long aadhar;
private Long contact;
private String townname;
public Long getAadhar() {
return aadhar;
}
public void setAadhar(Long aadhar) {
this.aadhar = aadhar;
}
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 getRelative() {
return relative;
}
public void setRelative(String relative) {
this.relative = relative;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Long getContact() {
return contact;
}
public void setContact(Long contact) {
this.contact = contact;
}
public String getTownname() {
return townname;
}
public void setTownname(String townname) {
this.townname = townname;
}
CustomerController.java
#Controller
public class CustomerController {
#Autowired
private CustomerService customerService;
#Autowired
private TownService townService;
#GetMapping("/customer")
public String findAllCustomers(Model model) {
model.addAttribute("customers", customerService.findAllCustomers());
model.addAttribute("towns", townService.findAllTown());
return "customer";
}
#PostMapping("/customer/addnew")
public String addNew(Customer customer) {
customerService.saveCustomer(customer);
return "redirect:/customer";
}
#RequestMapping(value="/customer/findCustomerById/",method = RequestMethod.GET)
#ResponseBody
public Optional<Customer> findCustomerById(Long id) {
return customerService.getCustomerById(id);
}
}
CustomerService.java
#Service
public class CustomerService {
#Autowired private CustomerRepository customerRepository;
public List<Customer> findAllCustomers() {
return customerRepository.findAll();
}
public void saveCustomer(Customer customer) {
customerRepository.save(customer);
}
public Optional<Customer> getCustomerById(Long id) {
return customerRepository.findById(id);
}
}
customer.html
<a th:href="#{/customer/findCustomerById/(id=${customer.id})}"
type="button" class="btn btn-primary "
data-toggle="modal" data-target=".bd-edit-modal-lg">
<span class="material-icons" >edit</span></a>
<form class="row g-3">
<div class="col-md-8">
<label for="customername" class="form-label">Customer ID</label>
<input type="text" class="form-control" id="nameEdit" name="id"
onKeyup="this.value = this.value.toUpperCase()" readonly>
</div>
<div class="col-md-4">
<label for="aadhar" class="form-label">Aadhar No.</label>
<input type="number" min="0" max="999999999999" class="form-control" id="aadhar"
name="aadhar">
</div>
<div class="col-md-8">
<label for="customername" class="form-label">Customer Name</label>
<input type="text" class="form-control" id="nameEdit" name="name"
onKeyup="this.value = this.value.toUpperCase()" required>
</div>
<div class="col-md-6">
<label for="relative" class="form-label">S/O,D/O,C/O</label>
<input type="text"class="form-control" id="relativeEdit" name="relative"
onKeyup="this.value = this.value.toUpperCase()" required>
</div>
<div class="col-md-6">
<label for="contact" class="form-label">Contact No.</label>
<input type="number" minlength="10" max="9999999999" class="form-control"
id="contactEdit" name="contact">
</div>
<div class="col-12">
<label for="inputAddress5" class="form-label">Address</label>
<input type="text"class="form-control" id="addressEdit" name="address"
onKeyup="this.value = this.value.toUpperCase()" placeholder="1234 Main St" required>
</div>
<div class="col-md-4">
<label for="inputTown" class="form-label" id="selecttown">Town/Area</label>
<select class="form-control" id="selecttownEdit" name="townname" required>
<option selected>Choose...</option>
<option th:each="town:${towns}" th:value="${town.townname}"
th:text="${town.townname}">...
</option>
</select>
</div>
<div class="text-center" style="margin-bottom:10px">
<button type="submit" class="btn btn-primary mx-1 my-1">Submit</button>
<button type="reset" class="btn btn-secondary mx-1 my-1">Reset</button>
</div>
</form><!-- End Multi Columns Form -->
I checked my responsebody in postman,works fine.But i am stuck at how to populate this data to the form.anything i tried my html page becames blank
My Json Response Body:
{
"id": 1,
"name": "M",
"relative": "U",
"address": "130",
"aadhar": 8891,
"contact": 90,
"townname": "DAR"
}

Spring Boot Thymeleaf Dropdown List option doesn't display values

It's my first topic at this beautiful site;)
I cant fix this, I am trying to present names of states and products in drop down lists. Intelij is helping me by underlines these fields.
https://ibb.co/wKgV940 (cant add image)
When I am adding th:object to divs or form it doesn't help.
There are racords on my db, and mathod retrieves values properly.
<div class="row justify-content-center">
<div class="form-group col-md-8" >
<label for="firstName" class="col-form-label">Choose State</label>
<select class="form-control" th:field="*{state.id}" id="state">
<options items="${listStates}>"></options>
<option th:each="state : ${states}"
th:value="${state.id}"
th:utext="${state.stateName}"></option>
</select>
</div>
<div class="form-group col-md-8" >
<label for="firstName" class="col-form-label">Choose products</label>
<select class="form-control" th:field="*{product.id}" id="product">
<option th:each="product : ${products}"
th:value="${product.id}"
th:utext="${product.productName}"></option>
</select>
</div>
<div class="form-group col-md-8">
<label for="firstName" class="col-form-label">Start price</label>
<input id="firstName" type="number" value="1" min="0" max="1000" step="1"/>
</div>
<div class="form-group col-md-8">
<label for="firstName" class="col-form-label">Preferred final prize</label>
<input type="text" class="form-control"
id="lastName" placeholder=""/>
</div>
<div class="form-group col-md-8">
<label for="firstName" class="col-form-label">Logistic costs</label>
<input type="text" class="form-control"
id="email" placeholder=""/>
</div>
<div class="col-md-6">
<input type="submit" class="btn btn-primary" value=" Calculate ">
</div>
</div>
</form>
public class CalculateController {
#Autowired
private StateRepository stateService;
#Autowired
private ProductRepository productService;
#RequestMapping(value = { "/calculateForm" }, method = RequestMethod.GET)
public String selectState(Model model) {
List<Product> product = new ArrayList<>();
List<State> state = new ArrayList<>();
model.addAttribute("product", product);
model.addAttribute("state", state);
List<Product> products = productService.findAll();
List<State> states = stateService.findAll();
model.addAttribute("states", states);
model.addAttribute("products", products);
return "calculateForm";
}
}
public class Product {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String productName;
private String category;
private Double wholePrice;
public Product() {
}
public Product(String productName, String category, Double wholePrice) {
this.productName = productName;
this.category = category;
this.wholePrice = wholePrice;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public Double getWholePrice() {
return wholePrice;
}
public void setWholePrice(Double wholePrice) {
this.wholePrice = wholePrice;
}
}
I have replaced this:
List<Product> product = new ArrayList<>();
List<State> state = new ArrayList<>();
model.addAttribute("product", product);
model.addAttribute("state", state);
by this:
Product product = new Product();
State state = new State();
model.addAttribute("product", product);
model.addAttribute("state", state);```
now it works. Thank you.

Spring + Hibernate Validation error

I am trying to implement Hibernate+Spring Validation to my application,but there is one issue, it won't display error message on page after I submit faulty data. Here is code:
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
public class StudentVO {
private int studentID;
private String userName;
#NotNull
#Size(min=2, max=45, message="Your Name should be between 2 - 45 characters.")
private String firstName;
private String middleName;
#NotNull
#Size(min=2, max=45, message="Your Surname should be between 2 - 45 characters.")
private String lastName;
JSP
<form:form id="myform" modelAttribute="student" method="post" class="form-horizontal" action="/register/registerStudent">
<div class="form-group">
<label for="firstname" class="col-sm-3 control-label">First Name</label>
<div class="col-sm-6">
<form:input type="text" class="form-control float_left" id="firstname" path="firstName" placeholder="First Name" />
<form:errors path="firstName"></form:errors>
</div>
</div>
<div class="form-group">
<label for="middlename" class="col-sm-3 control-label" id="md">Middle Name</label>
<div class="col-sm-6">
<form:input type="text" class="form-control" id="middlename" path="middleName" placeholder="Middle Name" />
</div>
</div>
<div class="form-group">
<label for="lastname" class="col-sm-3 control-label">Last Name</label>
<div class=" col-sm-6">
<form:input type="text" class="form-control float_left" id="lastname" path="lastName" placeholder="Last Name" required="true" />
<form:errors path="lastName"></form:errors>
</div>
Controller
#RequestMapping(value = { "/register/registerStudent" }, method = { RequestMethod.GET, RequestMethod.POST })
public String registerSubmit(#Valid StudentVO student, BindingResult result, Model model, HttpServletRequest request,
#RequestParam String action, #RequestParam(value = "parentID", required = false) String parentID,
#RequestParam(value = "studentID", required = false) String studentID,
RedirectAttributes redirectAttributes) {
if(result.hasErrors()){
model.addAttribute("student", student);
List<Map<String, String>> age = lookupService.getFields("age");
model.addAttribute("age", age);
return "studentSignup";
}
Thanks for help!
I found problem in my registerSubmit method I didn't mention #ModelAttribute, so code for method should look like:
#RequestMapping(value = { "/register/registerStudent" }, method = { RequestMethod.GET, RequestMethod.POST })
public String registerSubmit(#Valid #ModelAttribute StudentVO student, BindingResult result, Model model, HttpServletRequest request,
#RequestParam String action, #RequestParam(value = "parentID", required = false) String parentID,
#RequestParam(value = "studentID", required = false) String studentID,
RedirectAttributes redirectAttributes) {
if(result.hasErrors()){
model.addAttribute("student", student);
List<Map<String, String>> age = lookupService.getFields("age");
model.addAttribute("age", age);
return "studentSignup";
}

Categories

Resources