I am new to spring MVC. To practice out my skills I made a sample form whose elements gets populated through respective controller. Now to check the validation part, I used all methodologies through annotations i.e. #NotNull, #Size, #Valid, #ModelAttribute, and BindingResult object. Below are the files I am using. I was following every necessary aspect, but don't know why am I not able to see RED colored validation messages.
Student class
package com.sikka.springmvcworking.custombeans;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
public class Student {
private String firstName;
#NotNull
#Size(min=1,message="is required")
private String lastName;
private String country;
private String course;
private String[] knownOs;
private String[] coutries;
private Map<String,String> countryMap;
private Map<String,String> courseMap;
private Map<String,String> kosMap;
public Student() {
}
public Student(String firstName, String lastName, String country, String course, String[] knownOs, String[] coutries,
Map<String, String> countryMap, Map<String, String> courseMap, Map<String, String> kosMap) {
this.firstName = firstName;
this.lastName = lastName;
this.country = country;
this.course = course;
this.knownOs = knownOs;
this.coutries = coutries;
this.countryMap = countryMap;
this.courseMap = courseMap;
this.kosMap = kosMap;
}
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 getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public Map<String, String> getCountryMap() {
return countryMap;
}
public void setCountryMap(Map<String, String> countryMap) {
this.countryMap = countryMap;
}
public String getCourse() {
return course;
}
public void setCourse(String course) {
this.course = course;
}
public String[] getKnownOs() {
return knownOs;
}
public void setKnownOs(String[] knownOs) {
this.knownOs = knownOs;
}
public String[] getCoutries() {
return coutries;
}
public void setCoutries(String[] coutries) {
this.coutries = coutries;
}
public Map<String, String> getCourseMap() {
return courseMap;
}
public void setCourseMap(Map<String, String> courseMap) {
this.courseMap = courseMap;
}
public Map<String, String> getKosMap() {
return kosMap;
}
public void setKosMap(Map<String, String> kosMap) {
this.kosMap = kosMap;
}
}
Student Controller class
package com.sikka.springmvcworking.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.*;
import javax.validation.Valid;
import com.sikka.springmvcworking.custombeans.Student;
#Controller
#RequestMapping("stu")
public class StudentController {
#RequestMapping("studentForm")
public String getStudentForm(Model model) {
Student student = new Student();
Map<String,String> countryMap = new LinkedHashMap<String,String>();
countryMap.put("IN", "INDIA");
countryMap.put("BR", "BRAZIL");
countryMap.put("MX", "MEXICO");
student.setCountryMap(countryMap);
Map<String,String> courseMap = new LinkedHashMap<String,String>();
courseMap.put("java", "JAVA");
courseMap.put(".net", ".NET");
courseMap.put("php", "PHP");
courseMap.put("andr", "ANDROID");
student.setCourseMap(courseMap);
Map<String,String> kosMap = new LinkedHashMap<String,String>();
kosMap.put("win", "WINDOWS");
kosMap.put("lnx", "LINUX");
kosMap.put("mac", "MACINTOSH");
student.setKosMap(kosMap);
model.addAttribute("student", student);
System.out.println("inside STUDENT-FORM");
return "STUDENT-FORM";
}
#RequestMapping("processStudent")
public String outputStudent(#Valid #ModelAttribute("student") Student student, BindingResult bindingResult) {
if(bindingResult.hasErrors()) {
return "redirect:studentForm";
}
return "VIEW-STUDENT";
}
}
Student Form JSP
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%# taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<style>
.error {color: red;}
</style>
</head>
<body>
<form:form action="processStudent" modelAttribute="student">
FirstName : <form:input type="text" path="firstName" placeholder="enter your first name"/><br>
LastName : <form:input type="text" path="lastName" placeholder="enter your last name"/>
<form:errors path="lastName" cssClass="error"/><br>
select country : <form:select path="coutries">
<form:options items="${student.countryMap}"/>
</form:select><br>
select course : <form:radiobuttons path="course" items="${student.courseMap}"/><br>
known OS(s) : <form:checkboxes items="${student.kosMap}" path="knownOs"/><br>
<input type="submit" value="submit">
</form:form>
</body>
</html>
Student Submit/View Jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<br>
Student Name : ${student.firstName} ${student.lastName} <br>
Student visited countries:<br>
<c:forEach var="t" items="${student.coutries}">
<li> ${t} </li>
</c:forEach><br>
Known OS by student : <br>
<c:forEach var="t" items="${student.knownOs}">
<li> ${t} </li>
</c:forEach><br>
Student course : ${student.course}<br>
</body>
</html>
Every time to try lastName validation, I am leaving it blank. I am being redirected to same Student Form but with no error messages.
Is there any way to show validation error message in this jsp form.
I changed my Student Controller class to below code. Basically I used RedirectAttributes in my processStudent mapping. I also separate out the spring form element making maps to different methods. In studentForm I checked if student already exist (due to after validation process in processStudent mapping). Please see code:
Student-Controller class
package com.sikka.springmvcworking.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import java.util.*;
import javax.validation.Valid;
import com.sikka.springmvcworking.custombeans.Student;
#Controller
#RequestMapping("stu")
public class StudentController {
#RequestMapping("studentForm")
public String getStudentForm(Model model) {
Student student = new Student();
student.setCountryMap(getCountryMap());
student.setCourseMap(getCourseMap());
student.setKosMap(getKosMap());
if (!model.containsAttribute("student")) {
System.out.println("student not there");
model.addAttribute("student",student);
}
else {
System.out.println("student already there");
}
return "STUDENT-FORM";
}
#RequestMapping("processStudent")
public String outputStudent(#Valid #ModelAttribute("student") Student student, BindingResult bindingResult,RedirectAttributes attr) {
if(bindingResult.hasErrors()) {
attr.addFlashAttribute("org.springframework.validation.BindingResult.student", bindingResult);
student.setCountryMap(getCountryMap());
student.setCourseMap(getCourseMap());
student.setKosMap(getKosMap());
attr.addFlashAttribute("student", student);
return "redirect:studentForm";
}
return "VIEW-STUDENT";
}
private Map<String,String> getCountryMap(){
Map<String,String> countryMap = new LinkedHashMap<String,String>();
countryMap.put("IN", "INDIA");
countryMap.put("BR", "BRAZIL");
countryMap.put("MX", "MEXICO");
return countryMap;
}
private Map<String,String> getCourseMap(){
Map<String,String> courseMap = new LinkedHashMap<String,String>();
courseMap.put("java", "JAVA");
courseMap.put(".net", ".NET");
courseMap.put("php", "PHP");
courseMap.put("andr", "ANDROID");
return courseMap;
}
private Map<String,String> getKosMap(){
Map<String,String> kosMap = new LinkedHashMap<String,String>();
kosMap.put("win", "WINDOWS");
kosMap.put("lnx", "LINUX");
kosMap.put("mac", "MACINTOSH");
return kosMap;
}
}
Above approach solved my problem. I am not an expert in spring. Anyone out here can explain more deeply.
Related
i am beginner of spring boot and mysql. i need to load DropDownList. i don't know how to load them.what tried so far i attached below.i want load the student name on the dropdown.
index.html- DropDown load
<select class="form-control" name="example" id="example">
<option value="0">ALL</option>
<option th:each="Student : ${allStudents}"
th:value="${Student.id}"
th:selected="${Student.isSelected(lastselected)}"
th:text="${Student.studentname}">
</option>
</select>
Student Class
package com.example.StudentCrud.domain;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
#Entity
public class Student {
#Id
#GeneratedValue(strategy= GenerationType.IDENTITY)
private Long id;
private String studentname;
private String course;
private int fee;
public Student() {
}
public Student(Long id, String studentname, String course, int fee) {
this.id = id;
this.studentname = studentname;
this.course = course;
this.fee = fee;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getStudentname() {
return studentname;
}
public void setStudentname(String studentname) {
this.studentname = studentname;
}
public String getCourse() {
return course;
}
public void setCourse(String course) {
this.course = course;
}
public int getFee() {
return fee;
}
public void setFee(int fee) {
this.fee = fee;
}
}
Contorller i wrote like this. i stuck with this area how to get the Student names only
#ModelAttribute("allStudent")
public List<Student> allUsers() {
List<Student> userList= service.listAll();
return userList;
}
Here, I'm using <form:select /> , <form:option /> and <form:options /> tags to render HTML dropdown box. And <c:forEach /> for loop each student.
Don't forget to import below taglib to jsp.
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
For example, POST request path is /students. And modelAttribute="studentForm" will be used to bind Student POJO.
Index.jsp
<form:form modelAttribute="studentForm"
action="${pageContext.request.contextPath}/students" method="POST">
<form:select path="studentName">
<form:option value="NONE" label="Select" />
<c:forEach var="student" items="${allStudents}">
<form:option value="${student.id}" label="${student.studentName}"/>
</c:forEach>
</form:select>
</form:form>
By the way, I used camelCase for studentName.
Supposed service.listAll() works fine. When GET request /students is called -
Controller be like
#ModelAttribute(name = "studentForm")
public Student setUp() {
return new Student();
}
#GetMapping
public String list(Model model) {
List<Student> students = service.listAll();
// add to model
model.addAttribute("allStudent", students);
// view
return "index";
}
Method level #ModelAttribute will be invoked before any other method in controller. To use studentForm model attribute in form, we need to initialize first. You can do it without using method level #ModelAttribute.
Why am I getting PropertyNotFoundException?
Flight.java:
package com.bulbul.flightreservation.entities;
import java.sql.Timestamp;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.Table;
#Entity
#Table(name="Flight")
public class Flight extends AbstractEntity
{
private String Flight_Number;
public String Operating_Airlines;
private String Departure_City;
private String Arrival_City;
private Date date_Of_Departure;
private Timestamp estimated_departure_time;
public String getFlight_Number() {
return Flight_Number;
}
public void setFlight_Number(String flight_Number) {
Flight_Number = flight_Number;
}
public String getOperating_Airlines() {
return Operating_Airlines;
}
public void setOperating_Airlines(String Operating_Airlines) {
this.Operating_Airlines =Operating_Airlines;
}
public String getDeparture_City() {
return Departure_City;
}
public void setDeparture_City(String departure_City) {
Departure_City = departure_City;
}
public String getArrival_City() {
return Arrival_City;
}
public void setArrival_City(String arrival_City) {
Arrival_City = arrival_City;
}
public Timestamp getEstimated_departure_time() {
return estimated_departure_time;
}
public void setEstimated_departure_time(Timestamp estimated_departure_time) {
this.estimated_departure_time = estimated_departure_time;
}
public Date getDate_Of_Departure() {
return date_Of_Departure;
}
public void setDate_Of_Departure(Date date_Of_Departure) {
this.date_Of_Departure = date_Of_Departure;
}
}
Controller.java:
#RequestMapping(value="/findFlights",method=RequestMethod.POST)
public String findFlights(#RequestParam("from") String from,#RequestParam("to") String to,
#RequestParam("date_Of_Departure") #DateTimeFormat(pattern="yyyy-MM-dd") Date date_Of_Departure,ModelMap modelMap)
{
List<Flight> flight = flightRepository.findFlights(from,to,date_Of_Departure);
modelMap.addAttribute("flight",flight);
return "displayFlights";
}
#RequestMapping(value="/Already_User",method=RequestMethod.GET)
public String alreadyUser()
{
return "login/login";
}
FlightRepository.java
package com.bulbul.flightreservation.repository;
import java.util.Date;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import com.bulbul.flightreservation.entities.Flight;
public interface FlightRepository extends JpaRepository<Flight,Long>
{
#Query("from Flight where Departure_City=:Departure_City and Arrival_City=:Arrival_City and date_Of_Departure=:date_Of_Departure")
List<Flight> findFlights(#Param("Departure_City") String from,#Param("Arrival_City")
String to,#Param("date_Of_Departure") Date date_Of_Departure);
}
displayFlight.jsp:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%#page isELIgnored="false"%>
<!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>Display Flights</title>
</head>
<body>
<center>
<h1>Flight Available</h1>
<table>
<tr>
<th>Operating_Airlines</th>
<th>Departure_City</th>
<th>Arrival_City</th>
<th>Departure_Time</th>
</tr>
<c:forEach items="${flight}" var="flight">
<tr>
<td>${flight.Operating_Airlines}</td>
<td>${flight.Departure_City}</td>
<td>${flight.Arrival_City}</td>
<td>${flight.Departure_Time}</td>
<td><a href=showCompleteReservation?id=${flight.id}>Select</a></td>
</tr>
</c:forEach>
</table>
</center>
</body>
</html>
Exception:Property [Operating_Airlines] not found on type
[com.bulbul.flightreservation.entities.Flight]
javax.el.PropertyNotFoundException: Property [Operating_Airlines] not found on type [com.bulbul.flightreservation.entities.Flight]
at javax.el.BeanELResolver$BeanProperties.get(BeanELResolver.java:260) ~[tomcat-embed-el-8.5.34.jar:8.5.34]
at javax.el.BeanELResolver$BeanProperties.access$300(BeanELResolver.java:212) ~[tomcat-embed-el-8.5.34.jar:8.5.34]
at javax.el.BeanELResolver.property(BeanELResolver.java:347) ~[tomcat-embed-el-8.5.34.jar:8.5.34]
at javax.el.BeanELResolver.getValue(BeanELResolver.java:92) ~[tomcat-embed-el-8.5.34.jar:8.5.34]
at org.apache.jasper.el.JasperELResolver.getValue(JasperELResolver.java:110) ~[tomcat-embed-jasper-8.5.34.jar:8.5.34]
at org.apache.el.parser.AstValue.getValue(AstValue.java:169) ~[tomcat-embed-el-8.5.34.jar:8.5.34]
at org.apache.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:190) ~[tomcat-embed-el-8.5.34.jar:8.5.34]
at org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate(PageContextImpl.java:944) ~[tomcat-embed-jasper-8.5.34.jar:8.5.34]
at org.apache.jsp.WEB_002dINF.jsps.displayFlights_jsp._jspx_meth_c_005fforEach_005f0(displayFlights_jsp.java:196) ~[na:na]
at org.apache.jsp.WEB_002dINF.jsps.displayFlights_jsp._jspService(displayFlights_jsp.java:138) ~[na:na]
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70) ~[tomcat-embed-jasper-8.5.34.jar:8.5.34]
Program is executing Select query is also running in console but not displaying on page,please check the program and correct me thank you
Output
Output of the Program
product class
package com.ecom.Model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
#Entity
#Table(name="product")
public class Product {
#Id
#Column
private int id;
#Column
#NotNull
#Size(min=1,message="is required")
private String product_name;
#Column
#NotNull
#Size(min=1,message="is required")
private String manufacturer;
#Column
private int stock;
#Column
private String description;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getProduct_name() {
return product_name;
}
public void setProduct_name(String product_name) {
this.product_name = product_name;
}
public String getManufacturer() {
return manufacturer;
}
public void setManufacturer(String manufacturer) {
this.manufacturer = manufacturer;
}
public int getStock() {
return stock;
}
public void setStock(int stock) {
this.stock = stock;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Product(int id, String product_name, String manufacturer, int stock, String description) {
super();
this.id = id;
this.product_name = product_name;
this.manufacturer = manufacturer;
this.stock = stock;
this.description = description;
}
public Product()
{}
#Override
public String toString() {
return "Product [id=" + id + ", product_name=" + product_name + ", manufacturer=" + manufacturer + ", stock="
+ stock + ", description=" + description + "]";
}
}
product controller class
In controller i have created the model to save the data into model with the help of Product reference calling getAllProduct method.
package com.ecom.Controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import com.ecom.DAO.ProductDAO;
import com.ecom.Model.Product;
#Controller
public class ProductController {
//injecting Dependecy
#Autowired
private ProductDAO productDAO;
#RequestMapping("/ProductList")
public String ListProducts(Model theModel)
{
List<Product> theProducts = productDAO.getAllProduct();
theModel.addAttribute("products",theProducts);
return "productlist";
}
#RequestMapping("/ProductForm")
public String ProductForm(Model theModel)
{
Product theProduct = new Product();
theModel.addAttribute("addProduct", theProduct);
return "productform";
}
#RequestMapping("/saveProduct")
public String saveProduct(#ModelAttribute("addProduct") Product theProdut)
{
productDAO.addProducts(theProdut);
return "productform";
}
}
Product Dao Implementation
package com.ecom.DAOImplementation;
import java.util.List;
import javax.transaction.Transactional;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.ecom.DAO.ProductDAO;
import com.ecom.Model.Product;
#Repository("ProductDAO")
public class ProductImpl implements ProductDAO {
#Autowired
private SessionFactory sessionFactory;
#Transactional
public List<Product> getAllProduct() {
Session currentSession = sessionFactory.getCurrentSession();
Query<Product> theQuery = currentSession.createQuery("from Product",Product.class);
List<Product> products = theQuery.getResultList();
return products;
}
#javax.transaction.Transactional
public void addProducts(Product theProdut)
{
Session currentSession = sessionFactory.getCurrentSession();
System.out.println("Adding Product");
currentSession.save(theProdut);
System.out.println("Success");
}
}
Jsp page
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!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>Insert title here</title>
</head>
<body>
<table border="1px">
<tr>
<th>ID</th>
<th>Product Name</th>
<th>Manufacturer</th>
<th>Stock</th>
<th>Description</th>
</tr>
<c:forEach var="tempCustomer" items="${products}">
<tr>
<td> ${tempCustomer.id} </td>
<td> ${tempCustomer.product_name} </td>
<td> ${tempCustomer.manufacturer} </td>
<td> ${tempCustomer.stock} </td>
<td> ${tempCustomer.description} </td>
</tr>
</c:forEach>
</table>
</body>
</html>
Just tried to set this up by creating a sample list as shown below.
#RequestMapping("/ProductList")
public String ListProducts(Model theModel)
{
List<Product> theProducts = productDAO.getAllProduct();
Product product = new Product(1,"pro-1","man-1",10,"pro-1 desc");
theProducts.add(product);
product = new Product(2,"pro-2","man-2",10,"pro-2 desc");
theProducts.add(product);
product = new Product(3,"pro-3","man-3",10,"pro-3 desc");
theProducts.add(product);
product = new Product(4,"pro-4","man-4",10,"pro-4 desc");
theProducts.add(product);
product = new Product(5,"pro-5","man-5",10,"pro-5 desc");
theProducts.add(product);
theModel.addAttribute("products",theProducts);
return "productlist";
}
The JSP page productlist.jsp is as is. No changes done. I get the output as below.
You can perhaps try putting up debug statements to see if the theProducts is correctly populated.
Im developing a webapp with Spring and hibernate. I have a simple form with a text field and a select:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%# page language="java" contentType="text/html; charset=utf8" pageEncoding="utf8" %>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%# page trimDirectiveWhitespaces="true" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<meta http-equiv="Content-Language" content="English"/>
<!-- <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<meta http-equiv="Content-Language" content="es"/>-->
<link rel="stylesheet" media="all" href="<c:url value="/resources/site.css"/>">
<title>Nuevo expediente</title>
</head>
<body>
<h2>Nuevo expediente</h2>
<form:form modelAttribute="expediente" method="post">
<table>
<tr>
<td>Tipo de expediente:</td>
<td>
<form:select path="tipoExpediente">
<form:option value="-" label="Seleccione un tipo"/>
<form:options items="${expedientes}" itemValue="tipoExpediente" itemLabel="tipoExpediente" />
</form:select>
<form:errors path="tipoExpediente" element="span"/>
</td>
</tr>
<tr>
<td>Estado:</td>
<td>
<form:input path="estado"/>
<form:errors path="estado" element="span"/>
</td>
</tr>
</table>
<br/>
<input type="submit" value="Create" />
</form:form>
</body>
</html>
The form show correctly, but when i submit, I get a HTTP Status 400 exception, with the description:
description The request sent by the client was syntactically incorrect ()..
I have read that it would be caused by requestparams, but i not using them.
Here is my controller:
package com.atlantis.atecliente.controller;
import com.atlantis.atecliente.model.Book;
import com.atlantis.atecliente.model.Expediente;
import com.atlantis.atecliente.model.TipoExpediente;
import com.atlantis.atecliente.repository.ExpedienteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.List;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMethod;
#Controller
public class ExpedienteController {
#Autowired
protected ExpedienteService service;
#RequestMapping(value = {"/*", "/expedientes"})
public String getExpedientes(Model model) {
List<Expediente> expedientes = service.getExpedientes();
model.addAttribute("expedientes", expedientes);
return "expediente";
}
#RequestMapping(value = "nuevo-expediente")
public String createExpedienteGet(Model model) {
model.addAttribute("expediente", new Expediente());
List<TipoExpediente> tiposExpediente = service.getTiposExpedientes();
// List<String> canales = service.getCanales();
model.addAttribute("expedientes", tiposExpediente);
// model.addAttribute("canales", canales);
return "nuevo-expediente";
}
#RequestMapping(value = "nuevo-expediente", method = RequestMethod.POST)
public String createExpedientePost(#ModelAttribute("expediente") Expediente expediente) {
service.createExpediente(expediente);
return "redirect:expedientes";
}
}
Finalyy the Expediente class:
package com.atlantis.atecliente.model;
import java.util.Date;
import javax.persistence.*;
#Entity
#Table(name="Expediente")
public class Expediente {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int codExpediente;
#ManyToOne
#JoinColumn(name = "tipoExpediente")
private TipoExpediente tipoExpediente;
#ManyToOne
#JoinColumn(name = "estadoExpediente")
private EstadoExpediente estadoExpediente;
#ManyToOne
#JoinColumn(name = "expedientePadre")
private Expediente expedientePadre;
#ManyToOne
#JoinColumn(name = "tipoRelacion")
private TipoRelacion tipoRelacion;
#ManyToOne
#JoinColumn(name = "canalEntrada")
private CanalExpediente canalEntrada;
#ManyToOne
#JoinColumn(name = "idiomaEntrada")
private IdiomaExpediente idiomaEntrada;
#ManyToOne
#JoinColumn(name = "idiomaSalida")
private IdiomaExpediente idiomaSalida;
#ManyToOne
#JoinColumn(name = "tipoResolucion")
private TipoResolucion tipoResolucion;
#ManyToOne
#JoinColumn(name = "canalSalida")
private CanalExpediente canalSalida;
#Column(length = 30)
private String estado;
#Column(length = 10)
private String numeroSerie;
#Column(length = 10)
private String numeroHoja;
#Temporal(javax.persistence.TemporalType.TIMESTAMP)
private Date fechaRedaccion;
#Temporal(javax.persistence.TemporalType.TIMESTAMP)
private Date fechaRecepcion;
#Column(length = 200)
private String asunto;
#Column (length = 1000)
private String descripcion;
#Column(length = 20)
private String usuarioRegistro;
#Temporal(javax.persistence.TemporalType.DATE)
private Date fechaRegistro;
#Column (length = 20)
private String usuarioModificacion;
#Temporal(javax.persistence.TemporalType.TIMESTAMP)
private Date fechaModificacion;
#Column (length = 20)
private String usuarioCierre;
#Temporal(javax.persistence.TemporalType.TIMESTAMP)
private Date fechaCierre;
public int getCodExpediente() {
return codExpediente;
}
public void setCodExpediente(int codExpediente) {
this.codExpediente = codExpediente;
}
public EstadoExpediente getEstadoExpediente() {
return estadoExpediente;
}
public void setEstadoExpediente(EstadoExpediente estadoExpediente) {
this.estadoExpediente = estadoExpediente;
}
public Expediente getExpedientePadre() {
return expedientePadre;
}
public void setExpedientePadre(Expediente expedientePadre) {
this.expedientePadre = expedientePadre;
}
public TipoRelacion getTipoRelacion() {
return tipoRelacion;
}
public void setTipoRelacion(TipoRelacion tipoRelacion) {
this.tipoRelacion = tipoRelacion;
}
public CanalExpediente getCanalEntrada() {
return canalEntrada;
}
public void setCanalEntrada(CanalExpediente canalEntrada) {
this.canalEntrada = canalEntrada;
}
public IdiomaExpediente getIdiomaEntrada() {
return idiomaEntrada;
}
public void setIdiomaEntrada(IdiomaExpediente idiomaEntrada) {
this.idiomaEntrada = idiomaEntrada;
}
public IdiomaExpediente getIdiomaSalida() {
return idiomaSalida;
}
public void setIdiomaSalida(IdiomaExpediente idiomaSalida) {
this.idiomaSalida = idiomaSalida;
}
public TipoResolucion getTipoResolucion() {
return tipoResolucion;
}
public void setTipoResolucion(TipoResolucion tipoResolucion) {
this.tipoResolucion = tipoResolucion;
}
public CanalExpediente getCanalSalida() {
return canalSalida;
}
public void setCanalSalida(CanalExpediente canalSalida) {
this.canalSalida = canalSalida;
}
public String getUsuarioRegistro() {
return usuarioRegistro;
}
public void setUsuarioRegistro(String usuarioRegistro) {
this.usuarioRegistro = usuarioRegistro;
}
public String getNumeroSerie() {
return numeroSerie;
}
public void setNumeroSerie(String numeroSerie) {
this.numeroSerie = numeroSerie;
}
public String getNumeroHoja() {
return numeroHoja;
}
public void setNumeroHoja(String numeroHoja) {
this.numeroHoja = numeroHoja;
}
public Date getFechaRedaccion() {
return fechaRedaccion;
}
public void setFechaRedaccion(Date fechaRedaccion) {
this.fechaRedaccion = fechaRedaccion;
}
public Date getFechaRecepcion() {
return fechaRecepcion;
}
public void setFechaRecepcion(Date fechaRecepcion) {
this.fechaRecepcion = fechaRecepcion;
}
public String getAsunto() {
return asunto;
}
public void setAsunto(String asunto) {
this.asunto = asunto;
}
public String getDescripcion() {
return descripcion;
}
public void setDescripcion(String descripcion) {
this.descripcion = descripcion;
}
public Date getFechaRegistro() {
return fechaRegistro;
}
public void setFechaRegistro(Date fechaRegistro) {
this.fechaRegistro = fechaRegistro;
}
public String getUsuarioModificacion() {
return usuarioModificacion;
}
public void setUsuarioModificacion(String usuarioModificacion) {
this.usuarioModificacion = usuarioModificacion;
}
public Date getFechaModificacion() {
return fechaModificacion;
}
public void setFechaModificacion(Date fechaModificacion) {
this.fechaModificacion = fechaModificacion;
}
public String getUsuarioCierre() {
return usuarioCierre;
}
public void setUsuarioCierre(String usuarioCierre) {
this.usuarioCierre = usuarioCierre;
}
public Date getFechaCierre() {
return fechaCierre;
}
public void setFechaCierre(Date fechaCierre) {
this.fechaCierre = fechaCierre;
}
public TipoExpediente getTipoExpediente() {
return tipoExpediente;
}
public void setTipoExpediente(TipoExpediente tipoExpediente) {
this.tipoExpediente = tipoExpediente;
}
public String getEstado() {
return estado;
}
public void setEstado(String estado) {
this.estado = estado;
}
}
Some help?
Thanks
I have resolve this issue. The problem was with the controller method mapping to the url.
I modified the function createExpedientePost to:
public String createExpedientePost(#ModelAttribute("expediente") Expediente expediente, BindingResult result) {
The change was the addition of BindingResult as an argument.
I hope this may help others.
It seems somebody can get such error status, when arguments for a controller method were set incorrectly.
For instance I had the same because of wrong name of referer header(It was called as referrer)
public String foo(#RequestHeader(value = "referer") final String referer) {}
I've the following sequence of steps to register a team:
Select Team - This will display the list of players of this team as check boxes (JSP page below)
User can select one or more players displayed
newdTeam request handler method should be called setting the selected players from step 2 above. The handler is being called but the players set is empty even if I've selected players in step 2. Not sure where the issue is.
I doesn't see the property editor invoked. Any help is appreciated.
Team
#NodeEntity
public class Team
{
#GraphId
private Long nodeId;
#GraphProperty
#Indexed (unique = true)
private String name;
#Fetch
#RelatedTo (type = "PLAYED_WITH_TEAM", direction = Direction.INCOMING)
private final Set<Player> players = new HashSet<Player>();
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = StringUtil.capitalizeFirstLetter(name);
}
public Long getNodeId()
{
return nodeId;
}
public Collection<Player> getPlayers()
{
return players;
}
public void setPlayers(Set<Player> plyrs)
{
System.err.println("called set plrs");
players.addAll(plyrs);
}
}
Player
#NodeEntity
public class Player
{
#GraphId
private Long nodeId;
#Indexed (unique = true)
private String name;
#GraphProperty
#Indexed
private String firstName;
#GraphProperty
private String email;
//getters and setters
}
Controller
#Controller
#RequestMapping ("/registration")
public class RegistrationController
{
private transient final Logger LOG = LoggerFactory.getLogger(getClass());
#Autowired
private LeagueRepository leagueRepo;
#Autowired
private TeamRepository teamRepo;
#RequestMapping (method = RequestMethod.GET)
public String get()
{
return "/registration/start";
}
#Transactional
#RequestMapping (value = "/start", method = RequestMethod.POST)
public String hasParticipatedEarlier(#RequestParam boolean participatedInEarlierLeague, Model model)
{
if (participatedInEarlierLeague)
{
LOG.debug("Participated in earlier leagues. Retrieving the past league teams.");
Iterable<League> allLeagues = leagueRepo.findAll();
Set<League> sortedLeagues = new TreeSet<League>();
for (League l: allLeagues)
{
sortedLeagues.add(l);
}
LOG.debug("Past leagues sorted by start date {}", sortedLeagues);
model.addAttribute("pastLeagues", sortedLeagues);
}
else
{
LOG.debug("Did not participate in earlier leagues. Redirecting to register the new one.");
}
return "/registration/leagues";
}
#RequestMapping (value = "/selectTeam", method = RequestMethod.POST)
public String selectTeam(#RequestParam Long selectedTeam, Model model)
{
LOG.debug("Participated as team {} in previous league", selectedTeam);
Team team = teamRepo.findOne(selectedTeam);
model.addAttribute("team", team);
model.addAttribute("players", team.getPlayers());
return "registration/players";
}
#RequestMapping (value = "/newTeam", method = RequestMethod.POST)
public String newdTeam(#ModelAttribute Team team, Model model)
{
LOG.debug("Selected players from existing list {}", team.getPlayers());
return "registration/registrationConfirmation";
}
#InitBinder
public void initBinder(WebDataBinder binder)
{
binder.registerCustomEditor(Player.class, new PlayerPropertyEditor());
}
}
PlayerPropertyEditor
public class PlayerPropertyEditor extends PropertyEditorSupport
{
#Autowired
PlayerRepository playerRepo;
#Override
public String getAsText()
{
System.err.println("get as txt");
return ((Player) getValue()).getNodeId().toString();
}
#Override
public void setAsText(String incomingId) throws IllegalArgumentException
{
System.err.println(incomingId);
Player player = playerRepo.findOne(Long.valueOf(incomingId));
setValue(player);
}
}
JSP
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://www.springframework.org/tags" prefix="s" %>
<%# taglib prefix="f" uri="http://www.springframework.org/tags/form" %>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<!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>Players of ${team.name}</title>
</head>
<body>
<f:form action="newTeam" method="post" modelAttribute="team">
<f:checkboxes items="${players}" path="players" itemLabel="name" itemValue="nodeId" delimiter="<br/>"/>
<input type="submit" value="Submit">
</f:form>
</body>
</html>
One issue that I see is that you inject PlayerRepository inside PlayerPropertyEditor, which has no effect, since it is not in a Spring context. You should pass it through a constructor. And then inject it in the Controller
PlayerPropertyEditor
public class PlayerPropertyEditor extends PropertyEditorSupport
{
private PlayerRepository playerRepo;
public PlayerPropertyEditor(PlayerRepository playerRepo) {
this.playerRepo = playerRepo;
}
// other methods
}
inside Controller
#Autowired
private PlayerRepository playerRepo;
#InitBinder
public void initBinder(WebDataBinder binder)
{
binder.registerCustomEditor(Player.class, new PlayerPropertyEditor(playerRepo));
}
Secondly, and I guess that this is the main issue, is that you should override equals and hashCode for your Player class. I haven't tested that, but I rely on this answer