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]
Related
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.
I'm beginning with jsp and spring framework in web. I have a controller, a model, and a view. I get some data from database in the controller and I have been trying to load it into the view, but when I try to show that data with the core tag lib it doesn't show anything. I have been looking for a solution, but I can't find anything, could you guys help me please?
This is my model:
package com.valdezbaluarte.models;
import com.valdezbaluarte.dao.Dao;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.springframework.jdbc.core.RowMapper;
public class Product extends Dao{
private double price;
private String description;
private String name;
public Product(){
super();
this.setTable("products");
}
public List get(){
List productos = this.getTmp().queryForList("select * from products");
return productos;
}
// getters and setters follow
}
My controller:
package com.valdezbaluarte.controllers;
import com.valdezbaluarte.models.Product;
import java.util.List;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.portlet.ModelAndView;
#Controller
public class HomeController {
private Product producto;
public HomeController(){
this.producto = new Product();
}
#RequestMapping("home.htm")
public ModelAndView home(){
ModelAndView mav = new ModelAndView();
List datos = this.producto.get();
//I know the query get results because I print them with this instruction:
this.printlist(datos);
mav.addObject("datos",datos);
mav.setViewName("home");
return mav;
}
public void printlist(List l){
for(int i=0; i<l.size(); i++){
System.out.println("\n"+l.get(i));
}
}
}
And finally the view:
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>Aca el home hommies</h1>
<h2><c:out value="${productos}"/> </h2>
<table>
<thead>
<th>Columna 1</th>
<th>Columna 2</th>
<th>Columna 3</th>
</thead>
<tbody>
<c:forEach items="${datos}" var="dato">
<tr>
<td><c:out value="${dato.description}" /></td>
</tr>
</c:forEach>
</tbody>
</table>
</body>
</html>
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.
I am writing a struts+spring+jooq integration sample webapp.
I have a employee table in db and a jsp where in I can search for an employee in the db and show details. Problem is on clicking search nothing happens. There is no error in logs as well my print statements in searchEmp action don't show anything on console. Can you please tell me why the struts action method is not being invoked?Here are the details
index.jsp file
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="/struts-tags" prefix="s"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Struts 2 Spring integration </title>
</head>
<body>
<s:form>
<s:textfield label="Enter Id" name="eid" value="Enter employee name here.."></s:textfield>
<s:textfield label="Enter name" name="name" value="Enter name here.."> </s:textfield>
<s:textfield label="Enter city" name="city" value="Enter city here.."> </s:textfield>
<s:submit value="Create new employee" action="saveEmpAction"/>
<s:submit value="Update Employee" action="updateEmpAction"></s:submit>
<s:submit value="Delete Employee" action="deleteEmpAction"></s:submit>
<s:submit value="Search Employee" action="searchEmpAction"></s:submit>
</s:form>
<s:property value="message"/>
<hr>
<table border="1">
<s:iterator value="emps">
<tr>
<td><s:property value="eid"/></td>
<td><s:property value="name"/></td>
<td><s:property value="city"/></td>
</tr>
</s:iterator>
</table>
</body>
</html>
Here is my EmpAction.java class
package com.rewardsapp.action;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletContext;
import org.apache.struts2.ServletActionContext;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import test.generated.tables.pojos.Emp;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.Preparable;
import com.rewardsapp.dao.EmpDao;
public class EmpAction extends ActionSupport implements ModelDriven<Emp>, Preparable{
/**
*
*/
private static final long serialVersionUID = -2435427486571261741L;
Emp emp;
EmpDao empdao;
String message;
List<Emp> empList;
#Override
public void prepare() throws Exception {
emp = new Emp();
message = "";
empList = new ArrayList<Emp>();
ServletContext ctx = ServletActionContext.getServletContext();
WebApplicationContext webappCtx = WebApplicationContextUtils.getWebApplicationContext(ctx);
empdao = (EmpDao)webappCtx.getBean("empDao");
}
#Override
public Emp getModel() {
return emp;
}
public String searchEmpAction() throws Exception {
System.out.println("In search emp action");
System.out.println("Search employee : " + emp.getName());
Emp emp2 = empdao.getEmployee(emp.getId());
empList.add(emp2);
System.out.println("In search emp action");
System.out.println("Searched employee : " + emp2.getName());
return SUCCESS;
}
public Emp getEmp() {
return emp;
}
public void setEmp(Emp emp) {
this.emp = emp;
}
public EmpDao getEmpdao() {
return empdao;
}
public void setEmpdao(EmpDao empdao) {
this.empdao = empdao;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public List<Emp> getEmpList() {
return empList;
}
public void setEmpList(List<Emp> empList) {
this.empList = empList;
}
}
Here is my dao class:
package com.rewardsapp.dao;
import org.jooq.DSLContext;
import org.springframework.dao.DataAccessException;
import com.rewardsapp.enums.ObjectType;
import com.rewardsapp.utils.NullObjectRegistry;
import static test.generated.tables.Emp.EMP;
import test.generated.tables.pojos.Emp;
import test.generated.tables.records.EmpRecord;
public class EmpDao {
/** The Constant NULL_CUSTOMER. */
private static final Emp NULL_EMP = (Emp) NullObjectRegistry.getNullObject(ObjectType.EMP);
DSLContext dslContext;
public DSLContext getDslContext() {
return dslContext;
}
public void setDslContext(DSLContext dslContext) {
this.dslContext = dslContext;
}
public Emp getEmployee(int empId) throws Exception {
try {
EmpRecord empRecord = (EmpRecord) dslContext.select().from(EMP)
.where((EMP.ID.equal(empId))).fetchAny();
return (empRecord != null) ? empRecord.into(Emp.class) : NULL_EMP;
} catch (DataAccessException e) {
e.printStackTrace();
/*throw new SystemException("Exception during getCustomerByCustomerType: " + customerType, e,
SystemErrorCode.SQL_EXCEPTION_ERROR)*/;
throw new Exception();
}
}
}
Struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<package name="default" extends="struts-default" namespace="/">
<action name="searchEmpAction" class="com.rewardsapp.action.EmpAction" method="searchEmpAction">
<result name="success">index.jsp</result>
<result name="input">index.jsp</result>
<result name="error">index.jsp</result>
</action>
</package>
</struts>
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) {}