Error shown is Bean property 'emergencyComplaint.emergencyComplaint' is not readable or has an invalid getter method: Does the return type of the getter match the parameter type of the setter?
The getters and setters have the same return type, still it is showing this error.
JSP Page
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>CRS | Kolkata</title>
</head>
<body>
<div>
<h1>Lodge an Emergency Complaint Now</h1>
<form:form action="" method="post" modelAttribute="people">
<form:label
path="emergencyComplaint.emergencyComplaint"
for="emergencyComplaint"
>
Emergency Complaint
</form:label>
<form:input
type="text"
name="emergencyComplaint"
id="emergencyComplaint"
path="emergencyComplaint.emergencyComplaint"
/>
<form:label
path="emergencyComplaint.status"
for="emergencyComplaintStatus"
>Status</form:label
>
<form:input
type="text"
name="emergencyComplaintStatus"
id="emergencyComplaintStatus"
path="emergencyComplaint.status"
></form:input>
<form:label path="name" for="name">Name</form:label>
<form:input path="name" type="text" name="name" id="name" />
<form:label path="phoneNumber" for="phoneNumber"
>Phone Number</form:label
>
<form:input
path="phoneNumber"
type="text"
name="phoneNumber"
id="phoneNumber"
/>
<button type="submit">Lodge</button>
</form:form>
</div>
</body>
</html>
Model Class
package com.naha.crimereportingsystem.people;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import com.naha.crimereportingsystem.emergencyComplaint.EmergencyComplaint;
#Entity
public class People {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String name;
private String phoneNumber;
#OneToMany(targetEntity = EmergencyComplaint.class, cascade = CascadeType.ALL)
private List<EmergencyComplaint> emergencyComplaint;
public People() {
}
public People(long id, String name, String phoneNumber) {
this.id = id;
this.name = name;
this.phoneNumber = phoneNumber;
this.emergencyComplaint = (List<EmergencyComplaint>) new EmergencyComplaint();
}
public List<EmergencyComplaint> getEmergencyComplaint() {
return emergencyComplaint;
}
public void setEmergencyComplaint(List<EmergencyComplaint> emergencyComplaint) {
this.emergencyComplaint = emergencyComplaint;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(final String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public void setName(final String name) {
this.name = name;
}
}
Mapped Other Model Class
package com.naha.crimereportingsystem.emergencyComplaint;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
#Entity
public class EmergencyComplaint {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
long id;
private String emergencyComplaint;
private String status;
public String getEmergencyComplaint() {
return emergencyComplaint;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public void setEmergencyComplaint(String emergencyComplaint) {
this.emergencyComplaint = emergencyComplaint;
}
public EmergencyComplaint(long id, String emergencyComplaint, String status) {
this.id = id;
this.emergencyComplaint = emergencyComplaint;
this.status = status;
}
public EmergencyComplaint(String emergencyComplaint, String status) {
this.emergencyComplaint = emergencyComplaint;
this.status = status;
}
public EmergencyComplaint() {
}
}
This is a valid error. Take a close look at your Entity and your modelAttribute. There is no such thing emergencyComplaint.emergencyComplaint.
So, instead of:
<form:input type="text" name="emergencyComplaint" id="emergencyComplaint" path="emergencyComplaint.emergencyComplaint" />
Try this:
<form:input type="text" name="emergencyComplaint" id="emergencyComplaint" path="emergencyComplaint" />
I do not have OneToMany example handy but I think you are smart enough to identify the issue by now while reading this. If not then to get an idea, take a look at this and this.
Related
Controller
Controller:
package com.isolutions4u.onlineshopping.controllers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import com.isolutions4u.onlineshopping.model.Reservation;
import com.isolutions4u.onlineshopping.service.ReservationService;
#Controller
public class ReservationController {
#Autowired
private ReservationService reservationService;
#RequestMapping("/reservation")
public String reservationReg()
{
return "contactSave";
}
#RequestMapping("/saveContact")
public String saveReservation(#ModelAttribute Reservation model)
{
reservationService.saveMyUser(model);
return "contactSave";
}
}
Repository
Repository:
package com.isolutions4u.onlineshopping.repository;
import java.util.List;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import com.isolutions4u.onlineshopping.model.Reservation;
#Repository
public interface ReservationRepository extends CrudRepository<Reservation, Long> {
public List<Reservation> findAll();
}
Service
Service:
package com.isolutions4u.onlineshopping.service;
import javax.transaction.Transactional;
import org.springframework.stereotype.Service;
import com.isolutions4u.onlineshopping.model.Reservation;
import com.isolutions4u.onlineshopping.repository.ReservationRepository;
#Service
#Transactional
public class ReservationService {
private ReservationRepository repo;
public ReservationService(ReservationRepository repo) {
super();
this.repo = repo;
}
public void saveMyUser(Reservation reservation)
{
repo.save(reservation);
}
}
Model
package com.isolutions4u.onlineshopping.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "reservation")
public class Reservation {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String mobile;
private String email;
private String message;
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 getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Reservation(String name, String mobile, String email, String message) {
super();
this.name = name;
this.mobile = mobile;
this.email = email;
this.message = message;
}
public Reservation()
{
}
#Override
public String toString() {
return "Reservation [name=" + name + ", mobile=" + mobile + ", email=" + email + ", message=" + message + "]";
}
}
Form in localhost
fail to save
jsp location
Jsp coding :
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Reservation Form</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
</head>
<style>
body
{
background-color: grey;
}
.row{
margin-top: 10%;
margin-left:35%;
}
</style>
<body>
<form method="post" action="/saveContact">
<div class="row">
<div class="col s12 m6">
<div class="card white">
<div class="card-content black-text">
<span class="card-title center">Reservation Form</span>
<input type="text" placeholder="Enter the name" id="name" name="name" required/>
<input type="email" placeholder="Enter Email" id="email" name="email" required/>
<input type="text" placeholder="Enter the number" id="mobile" name="mobile" required/>
<input type="text" placeholder="Enter Message" id="message" name="message" required />
<input type="submit" value="SAVE">
</div>
</div>
</div>
</div>
</form>
</body>
</html>
Normally: store my information in the MySQL database, then this page will refresh to an empty table.
But I fail to store in my database
The above is the problem I'm having, thanks!
Console error:
2022-05-05 15:01:22.852 WARN 9356 --- [nio-8080-exec-2] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'POST' not supported]
2022-05-05 15:03:33.517 WARN 9356 --- [io-8080-exec-10] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'POST' not supported]
application-properties:
spring.datasource.url=jdbc:mysql://localhost:3307/test?useSSL=false&serverTimezone=UTC&useLegacyDatetimeCode=false
spring.datasource.username=root
spring.datasource.password= xxx
spring.datasource.testWhileIdle=true
spring.datasource.validationQuery=SELECT 1
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
spring.jpa.hibernate.naming-strategy=org.hibernate.cfg.ImprovedNamingStrategy
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
spring.http.multipart.max-file-size=10MB
spring.http.multipart.max-request-size=10MB
spring.http.multipart.file-size-threshold=1MB
spring.queries.users-query=select email, password, enabled from user_detail where email=?
spring.queries.roles-query=select email, role from user_detail where email=?
From the error you shared in comments, looks like you're making a HTTP POST request while the controller you've defined is for HTTP GET.
Change your controller annotations to the either of the following
#PostMapping("/saveContact")
or
#RequestMapping(path = "/saveContact", method = RequestMethod.POST)
Controller:
package com.isolutions4u.onlineshopping.controllers;
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 org.springframework.web.bind.annotation.RequestMethod;
import com.isolutions4u.onlineshopping.model.Reservation;
import com.isolutions4u.onlineshopping.service.ReservationService;
#Controller
public class ReservationController {
#Autowired
private ReservationService reservationservice;
#RequestMapping(value="/reservation",method=RequestMethod.GET)
String addReservationForm(Model model) {
System.out.println("Add reservation Form testing 123");
model.addAttribute("reservation", new Reservation());
return"reservation_form";
}
#RequestMapping(value="/saveReservation",method=RequestMethod.POST)
String saveReservation(Reservation reservation_info) {
System.out.println("Save repository information testing 456");
reservationservice.saveReservation(reservation_info);
return"sucessful_page";
}
}
Model:
package com.isolutions4u.onlineshopping.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="reservation")
public class Reservation {
#Id
#Column(name="id")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column
private String name;
private String email;
private String phone_number;
private String datetime;
private String message;
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 getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone_number() {
return phone_number;
}
public void setPhone_number(String phone_number) {
this.phone_number = phone_number;
}
public String getDatetime() {
return datetime;
}
public void setDatetime(String datetime) {
this.datetime = datetime;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
Repository:
package com.isolutions4u.onlineshopping.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.isolutions4u.onlineshopping.model.Reservation;
public interface ReservationRepository extends JpaRepository<Reservation,Long>{
}
Service:
package com.isolutions4u.onlineshopping.service;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.isolutions4u.onlineshopping.model.Reservation;
import com.isolutions4u.onlineshopping.repository.ReservationRepository;
#Service
#Transactional
public class ReservationService {
#Autowired
private ReservationRepository reservationrepo;
public void saveReservation(Reservation Reservation) {
reservationrepo.save(Reservation);
}
}
Reservation_form.jsp
<body>
<h3 style="text-align:center;">Reservation Form</h3>
<div class="row">
<div class="col s12 m6">
<div class="card white">
<div class="card-content black-text">
<table>
<form:form id="ReservationForm" modelAttribute="reservation" action="saveReservation" method="post">
<form:hidden path="id" />
<form:label path="name" for="name" >Name:</form:label>
<form:input path="name" name="name" required="required"/>
<form:label path="email" for="email" >Email:</form:label>
<form:input path="email" name="email" required="required"/>
<form:label path="phone_number" for="phone_number" >Email/Phone:</form:label>
<form:input path="phone_number" name="phone_number" required="required"></form:input>
<form:label path="datetime" for="datetime" >Reservation Date & Time</form:label>
<form:input path="datetime" name="datetime" required="required"></form:input>
<form:label path="message" for="message" >Message:</form:label>
<form:input path="message" name="message" required="required"></form:input>
<form:button name="submit" type="submit">Submit</form:button>
</form:form>
</table>
</div>
</div>
</div>
</div>
</body>
I need to update my category object
my model:
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.validation.constraints.NotNull;
#Entity
public class Category {
#Id
#GeneratedValue
private int id;
#NotNull
private String name;
private String description;
#NotNull
private Long created;
private Long updated;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Long getCreated() {
return created;
}
public void setCreated(Long created) {
this.created = created;
}
public Long getUpdated() {
return updated;
}
public void setUpdated(Long updated) {
this.updated = updated;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
Here my controller:
#Controller
public class CategoryController {
private CategoryRepository categoryRepository;
private static Logger logger = LogManager.getLogger(CategoryController.class);
// If class has only one constructore then #Autowired wiil execute automatically
public CategoryController(CategoryRepository categoryRepository) {
this.categoryRepository = categoryRepository;
createStubCategoryList();
}
#PostMapping(value = "/category")
public String submitCategory(Category category, Model model) {
logger.info("updateCategory = " + category);
model.addAttribute("submitted", true);
model.addAttribute("category", category);
categoryRepository.save(category);
return "category";
}
#RequestMapping("category/edit/{id}")
public String editCategory(#PathVariable("id") int id, Model model) {
Optional<Category> category = categoryRepository.findById(id);
logger.info("find_category = " + category);
model.addAttribute("category", category);
return "category";
}
Here my template to edit category:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title th:text="${appName}">Category template title</title>
<link th:href="#{/public/style.css}" rel="stylesheet"/>
<meta charset="UTF-8"/>
</head>
<body>
<div class="container">
<form method="post" action="#" th:object="${category}" th:action="#{/category}">
<h3>Category</h3>
<input type="text" placeholder="name" id="name" th:field="*{name}"/>
<textarea placeholder="Description of the category" rows="5" id="description"
th:field="*{description}"></textarea>
<input type="submit" value="Submit"/>
</form>
<div class="result_message" th:if="${submitted}">
<h3>Your category has been submitted.</h3>
<p>Find all categories here</p>
</div>
</div>
</body>
</html>
When call method in log has:
[INFO ] 2020-01-07 19:38:07.493 [http-nio-8090-exec-8] CategoryController - find_category = Optional[
Category{id=2, name='Electronics', created=1578418669105, updated=null, description='Electronics's description'}]
and here screen:
As you can see the field created=1578418669105
Nice.
Now I edit name "Electronics" to "Electronics2" and click submit.
As result call method: submitCategory in my controller. Nice.
Here result in log:
[INFO ] 2020-01-07 19:40:23.327 [http-nio-8090-exec-2] CategoryController - updateCategory =
Category{id=0, name='Electronics2', created=null, updated=null, description='Electronics's description'}
but as you can see the field created is null. Why?
I need to update only editable fields: name and description.
Another fields (like created, updated, id) must not change. This fields are not mapped.
How I can do this?
Because created, updated, id you need to pass as hidden. It is not available in html page.
Each column should be changed to updatable to false because by default is true.
#Column(name = "created", updatable = false)
private Long created;
I want to insert into two tables from jsp using spring mvc4 and hibernate.
Here is my two model class.
1)Employee.java
package com.websystique.springmvc.model;
import java.math.BigDecimal;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.validation.constraints.Digits;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.Type;
import org.hibernate.validator.constraints.NotEmpty;
import org.joda.time.LocalDate;
import org.springframework.format.annotation.DateTimeFormat;
import com.websystique.springmvc.model.UserLogin;;
#Entity
#Table(name="EMPLOYEE")
public class Employee {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
#Size(min=3, max=50)
#Column(name = "NAME", nullable = false)
private String name;
#NotNull
#DateTimeFormat(pattern="dd/MM/yyyy")
#Column(name = "JOINING_DATE", nullable = false)
#Type(type="org.jadira.usertype.dateandtime.joda.PersistentLocalDate")
private LocalDate joiningDate;
#NotNull
#Column(name = "SALARY", nullable = false)
private int salary;
#NotEmpty
#Column(name = "SSN", unique=true, nullable = false)
private String ssn;
#Column(name="emp_id",nullable=true)
private String emp_id;
public UserLogin getUserlogin() {
return userlogin;
}
public void setUserlogin(UserLogin userlogin) {
this.userlogin = userlogin;
}
public String getEmp_id() {
return emp_id;
}
public void setEmp_id(String emp_id) {
this.emp_id = emp_id;
}
#OneToOne(targetEntity=UserLogin.class,cascade=CascadeType.ALL)
#JoinColumn(name="emp_id",referencedColumnName="emp_id",insertable=false, updatable=false)
private UserLogin userlogin;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public LocalDate getJoiningDate() {
return joiningDate;
}
public void setJoiningDate(LocalDate joiningDate) {
this.joiningDate = joiningDate;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
public String getSsn() {
return ssn;
}
public void setSsn(String ssn) {
this.ssn = ssn;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id;
result = prime * result + ((ssn == null) ? 0 : ssn.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof Employee))
return false;
Employee other = (Employee) obj;
if (id != other.id)
return false;
if (ssn == null) {
if (other.ssn != null)
return false;
} else if (!ssn.equals(other.ssn))
return false;
return true;
}
#Override
public String toString() {
return "Employee [id=" + id + ", name=" + name + ", joiningDate="
+ joiningDate + ", salary=" + salary + ", ssn=" + ssn + "]";
}
}
2)UserLogin.java
package com.websystique.springmvc.model;
import java.io.Serializable;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator;
#Entity
#Table(name="users")
public class UserLogin implements Serializable{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
#Column(name="emp_id", unique=true, nullable=true)
private String emp_id;
#Column(name="user_name",nullable=false)
private String user_name;
#Column(name="password",nullable=false)
private String password;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUser_name() {
return user_name;
}
public void setUser_name(String user_name) {
this.user_name = user_name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
And here is my jsp page(registration.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" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Employee Registration Form</title>
<style>
.error {
color: #ff0000;
}
</style>
</head>
<body>
<h2>Registration Form</h2>
<form:form method="POST" modelAttribute="employee">
<form:input type="hidden" path="id" id="id"/>
<table>
<tr>
<td><label for="name">Name: </label> </td>
<td><form:input path="name" id="name"/></td>
<td><form:errors path="name" cssClass="error"/></td>
</tr>
<tr>
<td><label for="user_name">User Name: </label> </td>
<td><form:input path="user_name" id="user_name"/></td>
<td><form:errors path="user_name" cssClass="error"/></td>
</tr>
<tr>
<td><label for="pwd">Password: </label> </td>
<td><form:input type="password" path="password" id="password"/></td>
<td><form:errors path="password" cssClass="error"/></td>
</tr>
<tr>
<td><label for="joiningDate">Joining Date: </label> </td>
<td><form:input path="joiningDate" id="joiningDate"/></td>
<td><form:errors path="joiningDate" cssClass="error"/></td>
</tr>
<tr>
<td><label for="salary">Salary: </label> </td>
<td><form:input path="salary" id="salary"/></td>
<td><form:errors path="salary" cssClass="error"/></td>
</tr>
<tr>
<td><label for="ssn">SSN: </label> </td>
<td><form:input path="ssn" id="ssn"/></td>
<td><form:errors path="ssn" cssClass="error"/></td>
</tr>
<tr>
<td colspan="3">
<c:choose>
<c:when test="${edit}">
<input type="submit" value="Update"/>
</c:when>
<c:otherwise>
<input type="submit" value="Register"/>
</c:otherwise>
</c:choose>
</td>
</tr>
</table>
</form:form>
<br/>
<br/>
Go back to List of All Employees
</body>
</html>
Here is my controller
#RequestMapping(value = { "/new" }, method = RequestMethod.POST)
public String saveEmployee(#Valid Employee employee,#Valid UserLogin userLogin, BindingResult result,
ModelMap model) {
System.out.println("inside controller");
System.out.println("result>>>> "+result);
if (result.hasErrors()) {
System.out.println("inside controller1111111111");
return "registration";
}
if(!service.isEmployeeSsnUnique(employee.getId(), employee.getSsn())){
System.out.println("inside controller1111111111222222222222222222222");
FieldError ssnError =new FieldError("employee","ssn",messageSource.getMessage("non.unique.ssn", new String[]{employee.getSsn()}, Locale.getDefault()));
result.addError(ssnError);
return "registration";
}
String emp="Emp-"+employee.getId()+"-"+employee.getName();
System.out.println("emp>>> "+emp);
employee.setEmp_id(emp);
service.saveEmployee(employee);
userservice.saveUser(userLogin);
model.addAttribute("success", "Employee " + employee.getName() + " registered successfully");
return "success";
}
So I want to save user_name and password into login table and rest of the data want to save into another table. Is there anyone who can help me how to insert data into two tables. I searched a lot but did not get fruitful result. Any link for this problem is also appreciated. Thanks in advance
You can use entity inheritance. Check this http://www.thoughts-on-java.org/complete-guide-inheritance-strategies-jpa-hibernate/
. Select strategy which fits your reqirements.
I am newbie to Spring MVC.
I was stuck by an error while running my project
Error-The request sent by the client was syntactically incorrect.
I have an entity class PatientInfo.
My jsp page is demo1.
My controller is Patient Controller.
The functionality i want to implement is Inserting values into database.
But i am not able to call my function(add-update2) in controller.
demo1.jsp
<%#taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<html>
<head>
<title>Registration Form</title>
</head>
<body>
<h2 align="center">Full Registration Form</h2>
<hr />
<table align="center" cellpadding="5" cellspacing="5">
<form:form modelAttribute="patientInfo" method="POST" action="add-update2">
<tr>
<td> First Name</td>
<td><form:input path="firstName"/></td>
</tr>
<tr>
<td>Middle Name</td>
<td><form:input path="middleName" /></td>
</tr>
<tr>
<td>Last Name</td>
<td><form:input path="lastName"/>
</td>
</tr>
<tr>
<td>Age</td>
<td><form:input path="age" /></td>
</tr>
<tr>
<td>Gender</td>
<td><form:select path="gender">
<form:option value="" label="Select Gender" />
<form:options items="${genderList}" itemLabel="gender" itemValue="gender" />
</form:select></td>
</tr>
<tr>
<td>Marital Status</td>
<td><form:select path="maritalStatus">
<form:option value="" label="Select Marital Status" />
<form:options items="${maritalList}" itemLabel="maritalstatus" itemValue="maritalstatus" />
</form:select></td>
</tr>
<tr>
<td>Nationality</td>
<td><form:select path="nationality">
<form:option value="" label="Select Nationality" />
<form:options items="${nationalityList}" itemLabel="country" itemValue="country" />
</form:select></td>
</tr>
<tr name="tstest">
<td>Date Of Birth</td>
<td><form:input path="dateOfBirth" name="timestamp" value=""/>
<img src="../images/cal.gif" width="16" height="16" border="0" alt="Click Here to Pick up the timestamp">
</td>
</tr>
<tr>
<td>E-mail</td>
<td><form:input path="email"/></td>
</tr>
<tr>
<td>Blood Group</td>
<td><form:select path="bloodGroup">
<form:option value="" label="Select Blood Group" />
<form:options items="${bloodList}" itemLabel="bloodgroupname" itemValue="bloodgroupname" />
</form:select></td>
</tr>
<tr>
<td><input type="submit" value="submit"/></td>
</tr>
</form:form>
</table>
</body>
</html>
Controller-PatientController.java
package com.app.ehr.api;
import com.app.ehr.domain.Bloodgroup;
import com.app.ehr.domain.Gendertype;
import com.app.ehr.entities.Patientinfo;
import com.app.ehr.domain.Maritalstatus;
import com.app.ehr.domain.Nationality;
import com.app.ehr.model.Patient;
import com.app.ehr.service.PatientService;
import org.springframework.stereotype.Controller;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
#Controller
public class PatientController {
public PatientService patientService;
#Autowired
public PatientController(PatientService patientService){
this.patientService = patientService;
}
#RequestMapping(value="/", method= RequestMethod.GET)
public String index(ModelMap map) {
return "index";
}
#RequestMapping(value="/full-reg", method= RequestMethod.GET)
public String fullreg(ModelMap map,Patientinfo patientInfo) {
List<Bloodgroup> bloodList = new ArrayList<Bloodgroup>();
List<Gendertype> genderList = new ArrayList<Gendertype>();
List<Nationality> nationalityList = new ArrayList<Nationality>();
List<Maritalstatus> maritalList = new ArrayList<Maritalstatus>();
bloodList=patientService.getAllBloodgroup();
genderList= patientService.getAllGendertype();
nationalityList=patientService.getAllNationality();
maritalList=patientService.getAllMaritalstatus();
for(int i=0;i<bloodList.size();i++)
{
System.out.println("---------------------Controller"+bloodList.get(i));
}
// map.addAttribute("hello", "Hello Spring from Netbeans!!");
map.addAttribute("patientInfo", patientInfo);
map.addAttribute("bloodList", patientService.getAllBloodgroup());
map.addAttribute("genderList", patientService.getAllGendertype());
map.addAttribute("maritalList", patientService.getAllMaritalstatus());
map.addAttribute("nationalityList", patientService.getAllNationality());
return "demo1";
}
#RequestMapping(value="/add-update2", method= RequestMethod.POST)
public String addUpdate(#ModelAttribute("patientInfo") Patientinfo patientInfo) {
System.out.println("----------------------------------------- From Controller------------------------------------------------");
//patientService.addPatient(patientInfo);
return "redirect:/full-reg";
}
}
Entity Class- PatientInfo.java
package com.app.ehr.entities;
import java.io.Serializable;
import java.math.BigInteger;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
/**
*
* #author HP LAPTOP
*/
#Entity
#Table(name = "patientinfo")
#NamedQueries({
#NamedQuery(name = "Patientinfo.findAll", query = "SELECT p FROM Patientinfo p")})
public class Patientinfo implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#Column(name = "PatientKey")
private Long patientKey;
#Column(name = "PatientMRNumber")
private String patientMRNumber;
#Column(name = "IntPrimaryPhysicianKey")
private BigInteger intPrimaryPhysicianKey;
#Column(name = "FirstName")
private String firstName;
#Column(name = "MiddleName")
private String middleName;
#Column(name = "LastName")
private String lastName;
#Column(name = "Age")
private Short age;
#Column(name = "Gender")
private String gender;
#Column(name = "Nationality")
private String nationality;
#Column(name = "DateOfBirth")
#Temporal(TemporalType.TIMESTAMP)
private Date dateOfBirth;
#Column(name = "MaritalStatus")
private String maritalStatus;
#Column(name = "Occupation")
private String occupation;
#Column(name = "AnnualIncome")
private String annualIncome;
#Column(name = "BloodGroup")
private String bloodGroup;
#Column(name = "Email")
private String email;
#Column(name = "ModeOfPayment")
private String modeOfPayment;
#Column(name = "ModeOfPaymentAlt")
private String modeOfPaymentAlt;
#Column(name = "ExtPrimaryPhysicianName")
private String extPrimaryPhysicianName;
#Column(name = "ExtPrimaryPhysicianPhoneNumber")
private String extPrimaryPhysicianPhoneNumber;
#Column(name = "IsDeleted")
private Boolean isDeleted;
#Column(name = "Meta_CreatedByUser")
private String metaCreatedByUser;
#Column(name = "Meta_UpdatedDT")
#Temporal(TemporalType.TIMESTAMP)
private Date metaUpdatedDT;
#Column(name = "Meta_CreatedDT")
#Temporal(TemporalType.TIMESTAMP)
private Date metaCreatedDT;
public Patientinfo() {
}
public Patientinfo(Long patientKey) {
this.patientKey = patientKey;
}
public Long getPatientKey() {
return patientKey;
}
public void setPatientKey(Long patientKey) {
this.patientKey = patientKey;
}
public String getPatientMRNumber() {
return patientMRNumber;
}
public void setPatientMRNumber(String patientMRNumber) {
this.patientMRNumber = patientMRNumber;
}
public BigInteger getIntPrimaryPhysicianKey() {
return intPrimaryPhysicianKey;
}
public void setIntPrimaryPhysicianKey(BigInteger intPrimaryPhysicianKey) {
this.intPrimaryPhysicianKey = intPrimaryPhysicianKey;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getMiddleName() {
return middleName;
}
public void setMiddleName(String middleName) {
this.middleName = middleName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Short getAge() {
return age;
}
public void setAge(Short age) {
this.age = age;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getNationality() {
return nationality;
}
public void setNationality(String nationality) {
this.nationality = nationality;
}
public Date getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(Date dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
public String getMaritalStatus() {
return maritalStatus;
}
public void setMaritalStatus(String maritalStatus) {
this.maritalStatus = maritalStatus;
}
public String getOccupation() {
return occupation;
}
public void setOccupation(String occupation) {
this.occupation = occupation;
}
public String getAnnualIncome() {
return annualIncome;
}
public void setAnnualIncome(String annualIncome) {
this.annualIncome = annualIncome;
}
public String getBloodGroup() {
return bloodGroup;
}
public void setBloodGroup(String bloodGroup) {
this.bloodGroup = bloodGroup;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getModeOfPayment() {
return modeOfPayment;
}
public void setModeOfPayment(String modeOfPayment) {
this.modeOfPayment = modeOfPayment;
}
public String getModeOfPaymentAlt() {
return modeOfPaymentAlt;
}
public void setModeOfPaymentAlt(String modeOfPaymentAlt) {
this.modeOfPaymentAlt = modeOfPaymentAlt;
}
public String getExtPrimaryPhysicianName() {
return extPrimaryPhysicianName;
}
public void setExtPrimaryPhysicianName(String extPrimaryPhysicianName) {
this.extPrimaryPhysicianName = extPrimaryPhysicianName;
}
public String getExtPrimaryPhysicianPhoneNumber() {
return extPrimaryPhysicianPhoneNumber;
}
public void setExtPrimaryPhysicianPhoneNumber(String extPrimaryPhysicianPhoneNumber) {
this.extPrimaryPhysicianPhoneNumber = extPrimaryPhysicianPhoneNumber;
}
public Boolean getIsDeleted() {
return isDeleted;
}
public void setIsDeleted(Boolean isDeleted) {
this.isDeleted = isDeleted;
}
public String getMetaCreatedByUser() {
return metaCreatedByUser;
}
public void setMetaCreatedByUser(String metaCreatedByUser) {
this.metaCreatedByUser = metaCreatedByUser;
}
public Date getMetaUpdatedDT() {
return metaUpdatedDT;
}
public void setMetaUpdatedDT(Date metaUpdatedDT) {
this.metaUpdatedDT = metaUpdatedDT;
}
public Date getMetaCreatedDT() {
return metaCreatedDT;
}
public void setMetaCreatedDT(Date metaCreatedDT) {
this.metaCreatedDT = metaCreatedDT;
}
#Override
public int hashCode() {
int hash = 0;
hash += (patientKey != null ? patientKey.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Patientinfo)) {
return false;
}
Patientinfo other = (Patientinfo) object;
if ((this.patientKey == null && other.patientKey != null) || (this.patientKey != null && !this.patientKey.equals(other.patientKey))) {
return false;
}
return true;
}
#Override
public String toString() {
return "com.app.ehr.entities.Patientinfo[ patientKey=" + patientKey + " ]";
}
}
I think the issue is that Spring doesn't know how to deserialize the date your browser client sends when submitting the following input field in
<tr name="tstest">
<td>Date Of Birth</td>
<td><form:input path="dateOfBirth" name="timestamp" value=""/>
<img src="../images/cal.gif" width="16" height="16" border="0" alt="Click Here to Pick up the timestamp">
</td>
</tr>
Spring doesn't know how to take the value that you enter into that field and convert it into a Date object. You need to register a PropertyEditor for that. For example, add the following to your #Controller class
#InitBinder
public void initBinder(WebDataBinder binder) {
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
sdf.setLenient(true);
binder.registerCustomEditor(Date.class, new CustomDateEditor(sdf, true));
}
Obviously, change the SimpleDateFormat to whatever your client is sending.
On a related note, you're sending a 302 response by sending a redirect
return "redirect:/full-reg";
Remember that request and model attributes only live for the duration of one request. So when your client send the request to full-reg, none of the form input parameters you sent originally exist any more. You should re-think how you do this.
I came across the same error this morning. The problem with my code was that I had declared a variable as an integer in my form binding object but on the actual form I was capturing text. Changing the variable to the correct type worked out for me
This happens when the defined binding does not match to what the user is sending. The most common issues are:
Missing PathVariable declaration
Incomplete PathVariable declaration (for example missing value="variableName")
Wrong data type, such as Sotirios Delimanolis answer above. If the Class of an input parameter cannot be serialized the request is not processable
So, in general, be sure that:
Each PathVariable is declared
A value is assigned that corresponds to value to be match in the path - #PathVariable(value="myVariableName", String myVariable) where the path defines #RequestMapping(value = "/userInfo/myVariableName", method = RequestMethod.GET)
Each class declared for a PathVariable must be serializable.
try with this (with /add-update2 instead of just add-update2) and replace modelAttribute by commandName
<form:form commandName="patientInfo" method="POST" action="/add-update2">
In my case, I try to create an object that has ID and NAME as attributes.
ID is int, NAME is String.
But my js set values like this
ID = '', NAME = 'brabrabra...'
After set ID = 0, problem is fixed.
I had a similar issue recently and solved it by annotating my Date field with the #DateTimeFormat. In your case, you would edit your PatientInfo.java file to:
import org.spring.framework.annotation.DateTimeFormat;
#Column(name = "DateOfBirth")
#Temporal(TemporalType.TIMESTAMP)
#DateTimeFormat(pattern = ${pattern})
private Date dateOfBirth;
Make sure to replace ${pattern} with a string representing the format that will be received (e.g. "yyyy-MM-dd").
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) {}