Ok I am having an issue and have been stuck for a few hours. I am running the current version of spring with Hibernate and need to take data from a form and save it do the database, that's all but it is giving me tons of trouble and have no idea how to go about it. Below is the controller, JSP, Model, and Dao.
Controller
private final String addNewView = "addAward";
#RequestMapping(value = "/addAwardType", method = RequestMethod.GET)
public String addAwardType() {
LOG.debug("Display form to add a new contact.");
return addNewView;
}
#RequestMapping(value = "/addAwardType", method = RequestMethod.POST)
public ModelAndView addAwardType(
#ModelAttribute("AwardTypeModel") AwardType awardType,
BindingResult result) {
return new ModelAndView(addNewView, "AwardType", new AwardTypeModel(awardType));
}
}
JSP
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h2>Add AwardType</h2>
<form:form method="POST" commandName="addAwardType">
<table>
<tr>
<td><form:label path="AwardType.name">Award Name</form:label></td>
<td><form:input path="AwardType.name" /></td>
</tr>
<tr>
<td><form:label path="AwardType.description">Last Name</form:label></td>
<td><form:input path="AwardType.description" /></td>
</tr>
<tr>
<td> <form:checkbox path="AwardType.isActive" value="Active"/></td>
</tr>
<tr>
<td><form:label path="AwardType.created"></form:label></td>
<td><form:input path="AwardType.created" /></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Add Award"/>
</td>
</tr>
</table>
</form:form>
</body>
</html>
Model
public class AwardTypeModel extends BaseModel {
private int id;
private String name;
private String description;
private boolean active;
private Date created;
private Date modified;
/**
* Construct from persistence object
* A similar constructor will be needed in each model
* #param dbo - the Persistence Object (data base object)
*/
public AwardTypeModel(AwardType dbo){
this.id = dbo.getAwardTypeId();
this.name = dbo.getAwardName();
this.description = dbo.getDescription();
this.active = dbo.isActive();
this.created = dbo.getCreated();
this.modified = dbo.getModified();
}
/* (non-Javadoc)
* #see com.eaglecrk.recognition.model.BaseModel#convertToDb()
*/
#Override
public BasePersistence convertToDb() {
AwardType dbo = new AwardType();
dbo.setAwardTypeId(this.id);
dbo.setAwardName(this.name);
dbo.setDescription(this.description);
dbo.setActive(this.active);
dbo.setCreated(this.created);
dbo.setModified(this.modified);
return dbo;
}
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 String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
public Date getModified() {
return modified;
}
public void setModified(Date modified) {
this.modified = modified;
}
}
Related
I've a problem to insert data to table from my form.
So, I have a two table with relation ManyToOne.
TORDER and TSYSTEM.
I want to insert data to TORDER table via form in my .jsp page. Data for one field is from TSYSTEM table - System Name.
I was able to fill the dropdown list with data from the mentioned table but I have an error message when submitting the form and trying to insert data to TORDER Table.
Do you have any idea why could be wrong here?
My Order model class:
#Entity
#Table(name="TORDER")
public class Order implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="ORDER_ID")
private int orderId;
#ManyToOne(cascade = CascadeType.ALL, targetEntity=System.class)
#JoinColumn(name = "SYSTEM_ID", referencedColumnName = "SYSTEM_ID")
private int sysId;
#ManyToOne(cascade = CascadeType.ALL, targetEntity=System.class)
#JoinColumn(name = "SYSTEM_NAME", referencedColumnName = "SYSTEM_NAME")
private String systemName;
#Column(name="ORDER_DATE")
private String orderDate;
#Column(name="STATUS")
private String status;
#Column(name="COMMENT")
private String comment;
#Column(name="APPROVED_BY_MANAGER")
private String managerApproval;
#Column(name="APPROVED_BY_ADMIN")
private String adminApproval;
public int getOrderId() {
return orderId;
}
public void setOrderId(int orderId) {
this.orderId = orderId;
}
public int getSystemId() {
return sysId;
}
public void setSystemId(int sysId) {
this.sysId = sysId;
}
public String getSystemName() {
return systemName;
}
public void setSystemName(String systemName) {
this.systemName = systemName;
}
public String getOrderDate() {
return orderDate;
}
public void setOrderDate(String orderDate) {
this.orderDate = orderDate;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public String getManagerApproval() {
return managerApproval;
}
public void setManagerApproval(String managerApproval) {
this.managerApproval = managerApproval;
}
public String getAdminApproval() {
return adminApproval;
}
public void setAdminApproval(String adminApproval) {
this.adminApproval = adminApproval;
}
}
System model:
#Entity
#Table(name="TSYSTEM")
public class System implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="SYSTEM_ID")
private int sysId;
#Column(name="SYSTEM_NAME")
private String systemName;
#Column(name="DESCRIPTION")
private String description;
#Column(name="GROUP_NAME")
private String groupName;
public int getSysId() {
return sysId;
}
public void setSysId(int sysId) {
this.sysId = sysId;
}
public String getSystemName() {
return systemName;
}
public void setSystemName(String systemName) {
this.systemName = systemName;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getGroupName() {
return groupName;
}
public void setGroupName(String groupName) {
this.groupName = groupName;
}
}
Controller methods:
#RequestMapping(value="/addOrder", method=RequestMethod.GET)
public ModelAndView addOrder() {
ModelAndView model = new ModelAndView();
Order order = new Order();
model.addObject("orderForm", order);
List<System> systemList = systemService.getAllSystemsName();
model.addObject("systemList", systemList);
model.setViewName("order_form");
return model;
}
#RequestMapping(value="/saveOrder", method=RequestMethod.POST)
public ModelAndView save(#ModelAttribute("orderForm") Order order) {
orderService.saveOrUpdate(order);
return new ModelAndView("redirect:/employee/orderList");
}
Repository methods to get all system names from TSYSTEM Table:
public interface SystemRepository extends CrudRepository<System, Integer> {
#Query("select a.systemName from System a")
public List<System> getAllSystemsName();
}
and finally my .jsp form:
<form:form modelAttribute="orderForm" method="post" action="${saveURL }" cssClass="form" >
<form:hidden path="orderId"/>
<table>
<tr>
<td>System Name</td>
<td><form:select path="systemName">
<form:option value="NONE" label="--- Select ---" />
<form:options items="${systemList}" />
</form:select>
</td>
<td><form:errors path="systemName" cssClass="error" /></td>
</tr>
<tr>
<td><label>Komentarz</label></td>
<td><form:textarea path="comment" cssClass="form-control" id="comment"
title="Dodaj komentarz do zamówienia" /></td>
</tr>
<tr>
<td><label>Data zamówienia</label></td>
<td><form:input type="text" path="orderDate" cssClass="form-control"
id="orderDate" pattern="{2,}" title="Data zamówienia" required="required"/>
</td>
</tr>
<tr>
<td><button type="reset" class="btn btn-primary">Wyczyść dane</button>
</td>
<td><button type="submit" class="btn btn-primary">Zamów dostęp</button>
</td>
</tr>
</table>
</form:form>
and after form submit action i received and error:
2018-11-13 17:32:32.846 ERROR 7416 --- [nio-8090-exec-9] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.orm.jpa.JpaSystemException: Error accessing field [private int com.project.model.System.sysId] by reflection for persistent property [com.project.model.System#sysId] : 0; nested exception is org.hibernate.property.access.spi.PropertyAccessException: Error accessing field [private int com.project.model.System.sysId] by reflection for persistent property [com.project.model.System#sysId] : 0] with root cause
java.lang.IllegalArgumentException: Can not set int field com.project.model.System.sysId to java.lang.Integer
at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:167) ~[na:1.8.0_161]
at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:171) ~[na:1.8.0_161]
at sun.reflect.UnsafeFieldAccessorImpl.ensureObj(UnsafeFieldAccessorImpl.java:58) ~[na:1.8.0_161]
at sun.reflect.UnsafeIntegerFieldAccessorImpl.getInt(UnsafeIntegerFieldAccessorImpl.java:56) ~[na:1.8.0_161]
at java.lang.reflect.Field.getInt(Field.java:574) ~[na:1.8.0_161]
at org.hibernate.property.access.spi.GetterFieldImpl.get(GetterFieldImpl.java:62) ~[hibernate-core-5.3.7.Final.jar:5.3.7.Final]
Please post SYSTEM model. I think you need change System model with field sysId to Integer type. Because you set repository with model sysId is Integer.
i browse "http://localhost:8080/subject/form" for fill information in Subjectform.jsp, after will direct "http://localhost:8080/subject/add" for insert subject object in table subject. But it not insert subject object and encouter following error:
null<br/>
edu.java.spring.controller.SubjectController.addSubject(SubjectController.java:5
0)<br/>
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)<br/>
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)<br
/>
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.jav
a:43)<br/>
java.lang.reflect.Method.invoke(Method.java:497)<br/>
org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHa
ndlerMethod.java:215)<br/>
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(I
nvocableHandlerMethod.java:132)<br/>
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMet
hod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)<br/>
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapt
er.invokeHandleMethod(RequestMappingHandlerAdapter.java:749)<br/>
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapt
er.handleInternal(RequestMappingHandlerAdapter.java:689)<br/>
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(A
bstractHandlerMethodAdapter.java:83)<br/>
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.j
ava:938)<br/>
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.ja
va:870)<br/>
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet
.java:961)<br/>
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:86
3)<br/>
javax.servlet.http.HttpServlet.service(HttpServlet.java:707)<br/>
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:8
37)<br/>
javax.servlet.http.HttpServlet.service(HttpServlet.java:790)<br/>
org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:801)<br/>
org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:587)<br/>
org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:143)<br
/>
org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:577)<br/>
org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:223
)<br/>
org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:112
6)<br/>
org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:515)<br/>
org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:185)
<br/>
org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1060
)<br/>
org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141)<br
/>
org.eclipse.jetty.server.handler.ContextHandlerCollection.handle(ContextHandlerC
ollection.java:215)<br/>
org.eclipse.jetty.server.handler.HandlerCollection.handle(HandlerCollection.java
:110)<br/>
org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:113)<
br/>
org.eclipse.jetty.server.Server.handle(Server.java:509)<br/>
org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:288)<br/>
org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:240)<br/>
org.eclipse.jetty.io.AbstractConnection$2.run(AbstractConnection.java:539)<br/>
org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:620)
<br/>
org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:540)<
br/>
java.lang.Thread.run(Thread.java:745)<br/>
Here file SubjectController.class
#Controller
public class SubjectController {
#Autowired
public StudentDAO studentDao;
public SubjectDao subjectDao;
#RequestMapping(value = "subject/form",method = RequestMethod.GET)
public ModelAndView subjectForm (){
ModelAndView model = new ModelAndView("SubjectForm", "subject", new Subject());
List<Student> students = studentDao.listStudents();
Map<Integer,String> map = new HashMap<Integer,String>();
for(int i=0;i<students.size();i++){
map.put(students.get(i).getId(), students.get(i).getName());
}
model.getModelMap().put("studentList",map);
return model;
}
#RequestMapping(value="subject/add",method = RequestMethod.POST)
public void addSubject(#Valid #ModelAttribute("subject")Subject subject){
// ModelAndView model = new ModelAndView("redirect:/subject/list");
subjectDao.insert(subject);
// return model;
}
Here file SubjectHibernateDaoImpl.class
public class SubjectHibernateDaoImpl implements SubjectDao {
#Autowired
public LocalSessionFactoryBean sessionFactory;
#Override
public void insert(Subject subject){
Session session = sessionFactory.getObject().openSession();
try {
session.save(subject);
session.flush();
} finally {
// TODO: handle finally clause
session.close();
}
}
public List<Subject> listSubject() {
// TODO Auto-generated method stub
Session session = sessionFactory.getObject().openSession();
Query query = session.createQuery("from Subject");
try {
return query.list();
} finally {
// TODO: handle finally clause
session.close();
}
}
Here file Subject.class
#Entity
#Table(name = "subject",uniqueConstraints={#UniqueConstraint(columnNames="id")})
public class Subject {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id", unique = true, nullable = false)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#Column(name = "title", nullable = false, length = 200)
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
#Column(name = "student", nullable = false)
public int getStudent() {
return student;
}
public void setStudent(int student) {
this.student = student;
}
#Column(name = "score", nullable = false)
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
public int id;
public String title;
public int student;
public int score;
}
Here file Subject.jsp
<html>
<head>
<title>Add New Subject Information</title>
</head>
<body>
<h2>Please Input Subject Information</h2>
<form:form method="POST" modelAttribute="subject" action="add">
<table>
<tr>
<td><form:label path="student">Student</form:label></td>
<td><form:input path="student" type = "number"/></td>
</tr>
<tr>
<td><form:label path="title">Title</form:label></td>
<td><form:input path="title"/></td>
</tr>
<tr>
<td><form:label path="score">Score</form:label></td>
<td><form:input path="score" type = "number"/></td>
</tr>
<tr>
<td colspan="3"><input type="submit" value="Submit"/></td>
</table>
</form:form>
</body>
</html>
Looks like you forgot to add the #Autowired annotation. It's present for the studentDao but not for the subjectDao, resulting in that object not being initialized.
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").
In my page jsp, i have a form where i can add a user to my database, and i use a validator to show errors when fields are empty, but what i want to do is, when i insert a duplicate entry of the primary key of my table, the validator show me a message that this login for example is already taken instead having an error by Apache!
this is my User POJO :
package gestion.delegation.domaine;
import java.io.Serializable;
public class User implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
int id;
String nom;
String prenom;
String login;
String password;
String role;
boolean enable;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public String getPrenom() {
return prenom;
}
public void setPrenom(String prenom) {
this.prenom = prenom;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public boolean getEnable() {
return this.enable;
}
public void setEnable(boolean enable) {
this.enable = enable;
}
public User(int id, String nom, String prenom, String login,
String password, String role, boolean enable) {
super();
this.id = id;
this.nom = nom;
this.prenom = prenom;
this.login = login;
this.password = password;
this.role = role;
this.enable = enable;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public User() {
super();
}
}
and this is my validator :
package gestion.delegation.validator;
import gestion.delegation.domaine.User;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
public class AddUserValidator implements Validator{
#Override
public boolean supports(Class<?> clazz) {
return User.class.isAssignableFrom(clazz);
}
#Override
public void validate(Object obj, Errors err) {
ValidationUtils.rejectIfEmptyOrWhitespace(err, "nom", "name.required","Choisissez un nom");
ValidationUtils.rejectIfEmptyOrWhitespace(err, "prenom", "prenom.required", "Choisissez un prenom");
ValidationUtils.rejectIfEmptyOrWhitespace(err, "login", "login.required", "Choisissez un login");
ValidationUtils.rejectIfEmptyOrWhitespace(err, "password", "password.required", "Choisissez un password");
ValidationUtils.rejectIfEmpty(err, "role", "role.required", "Choisissez un role");
}
}
the form :
<c:if test="${not empty msg_success}">
<div class="success">Vous avez ajouter un utilisateur avec
succès !</div>
</c:if>
<form:form name="ajf"
action="${pageContext.request.contextPath}/ajouter_user"
method="post" commandName="user">
<table id="tabmenu">
<tr>
<td id="idtab">Nom :</td>
<td><form:input type="text" path="nom"
class="round default-width-input" name="name_" /></td>
<td><form:errors path="nom" Class="errorbox" /></td>
</tr>
<tr>
<td id="idtab">Prénom :</td>
<td><form:input type="text" path="prenom" name="prenom_"
class="round default-width-input" /></td>
<td><form:errors path="prenom" cssClass="errorbox" />
</tr>
<tr>
<td id="idtab">Login :</td>
<td><form:input type="text" path="login" name="login_"
cssClass="round default-width-input" /></td>
<td><form:errors path="login" cssClass="errorbox" /></td>
</tr>
<tr>
<td id="idtab">Password :</td>
<td><form:input type="password" path="password" name="pass_"
class="round default-width-input" /></td>
<td><form:errors path="password" cssClass="errorbox" /></td>
</tr>
<tr>
<td id="idtab">Séléctionner un rôle :</td>
<td><form:select path="role">
<form:option value="" label="" />
<form:option value="ROLE_ADMIN">Administrateur</form:option>
<form:option value="ROLE_USER">Simple utilisateur</form:option>
</form:select></td>
<td><form:errors path="role" cssClass="errorbox" /></td>
</tr>
<tr>
<td id="idtab">Activé :</td>
<td><form:input type="checkbox" value="true" path="enable" />
Oui</td>
</tr>
<tr></tr>
<tr></tr>
<tr>
<td><input
class="button round blue image-right ic-right-arrow"
type="submit" value="Créer" /></td>
<td><input
class="button round blue image-right ic-right-arrow"
type="reset" value="Initialiser" /></td>
</tr>
</table>
</form:form>
Any Idea?
I'm afraid that a Validator will not be sufficient in this case. Although you could extend your AddUserValidator class to check whether the given user name is free, it will not
work in a situation in which two users simultaneously try to register using the same user name - the validation will pass, however one of the users will get an error from the database.
To protect yourself against such situations I would place the registration logic in a try catch block and in case of an error display a proper message to the user. This would be kind of an application-level validation.
Spring validator simply checks your object in accordance with the prescribed rules before you bring it into the database. It does not know anything about the database. To display the error that occurred while working with a database, you need to catch the exception manually.
In your Controller Just Check the duplication by querying from Model Repository.
#Model Entity
#Table(name = "people")
public class People {
#Column(name = "nic")
#NotEmpty(message = "*Please provide your nic")
private String nic;
#Repository
public interface PeopleRepository extends JpaRepository<People, Integer>{
People findByNic(String nic);
}
#Controller
#RequestMapping(value = "/welcome", method = RequestMethod.POST)
public ModelAndView createNewPeople(Model model,, BindingResult bindingResult) {
ModelAndView modelAndView = new ModelAndView();
People peopleExistsEmail = peopleService.findUserByNic(people.getNic());
if (peopleExistsEmail != null) {
bindingResult
.rejectValue("nic", "error.people",
"There is already a person registered with the nic provided");
}
if (bindingResult.hasErrors()) {
modelAndView.setViewName("welcome");
} else {
peopleService.savePeople(people);
modelAndView.addObject("successMessage", "People has been registered successfully");
modelAndView.addObject("people", new People());
} catch (Exception e) {
e.printStackTrace();
}
}
return modelAndView;
}
So this is the Right Answer :
The method in DAO class implementation is like that :
public boolean AddUser(User user) {
boolean t=true;
final String User_INSERT1 = "insert into utilisateurs (login, password, nom, prenom,enable) "
+ "values (?,?,?,?,?)";
final String User_INSERT2="insert into roles (login,role) values(?,?)";
/*
* On récupère et on utilisera directement le jdbcTemplate
*/
MessageDigestPasswordEncoder encoder = new MessageDigestPasswordEncoder("SHA");
String hash = encoder.encodePassword(user.getPassword(), "");
final String check ="select count(*) from utilisateurs where login = ?";
int result= getJdbcTemplate().queryForInt(check, new Object[]{String.valueOf(user.getLogin())});
if (result==0) {
getJdbcTemplate()
.update(User_INSERT1,
new Object[] {user.getLogin(),
hash, user.getNom(),
user.getPrenom(), user.getEnable(),
});
getJdbcTemplate().update(User_INSERT2, new Object[]{user.getLogin(),user.getRole()});
return t;
}
else { t = false ; return t;}
}
The controller :
#RequestMapping(value ="/ajouter_user", method = RequestMethod.POST)
public String add(#ModelAttribute User us,BindingResult result,ModelMap model) {
AddUserValidator uservalid=new AddUserValidator();
uservalid.validate(us, result);
if (result.hasErrors()) {
model.addAttribute("usersystem", userservice.getAllUsers());
return "gestionUser";
}else {
boolean e = userservice.AddUser(us);
if (e==false){
model.addAttribute("msg_failed","true");
}
else {
model.addAttribute("msg_success","true");}
model.addAttribute("usersystem", userservice.getAllUsers()); /*verifier*/
return "gestionUser";
}
}
And for showing the error in the jsp file :
<c:if test="${not empty msg_failed}">
<div class="errorblock">Il existe déjà un utilisateur avec cet login </div>
</c:if>
The method in DAO class implementation is like that :
public final long insert(final User user) throws MyException {
String sql = "INSERT INTO users ....";
String chkSql = "SELECT count(*) FROM users WHERE username=:username";
Map namedParams = new HashMap();
namedParams.put("username", user.getUsername());
long newId = namedTemplate.queryForInt(chkSql, namedParams);
if (newId > 0) {
try {
throw new MyException(-1);
} catch (MyException e) {
throw e;
}
}
newId = ...;// could be generated if not inc field or triggered...
namedParams.put("username", user.getUserName());
...
...
namedParams.put("id", newId);
namedTemplate.update(sql, namedParams);
return newId;
}
MyException like that:
public class MyException extends Exception{
private static final long serialVersionUID = 1L;
int a;
public MyException(int b) {
a=b;
}
}
Controller:
#RequestMapping(value = "/user", method = RequestMethod.POST)
public final ModelAndView actionUser(
final ModelMap model,
#ModelAttribute("myitemuser") #Valid final User user,
final BindingResult bindResult,
...);
...
try {
userService.addUser(user); // or dao... ;)
} catch (Exception e) {
UserValidator userValidator = new UserValidator();
userValidator.custError(bindResult);
}
UserValidator like that:
...
#Override
public final void validate(final Object object, final Errors errors) {
User user = (User) object;
...
if (user.getPassword().isEmpty()) {
errors.rejectValue("password", "error.users.emptypass");
}
}
public final void custError(final Errors errors){
errors.rejectValue("username"/* or login */, "error.users.uniqname");
}
...
Ну как то так))))
i need your help as the title says i have a problem inserting multiple rows from a jsp form. The code is from an answer from this site.
Controller
#ModelAttribute("programform")
public ProgramForm populatePojos() {
// Don't forget to initialize the pojos list or else it won't work
ProgramForm programform = new ProgramForm();
List<Programs> programs = new ArrayList<Programs>();
for(int i=0; i<2; i++) {
programs.add(new Programs());
}
programform.setPrograms(programs);
return programform;
}
#RequestMapping(value = "/createprog")
public ModelAndView tiles2(#ModelAttribute("programform") ProgramForm programform,
BindingResult result) {
//Map<String, Object> model = new HashMap<String, Object>();
//model.put("articles", articleService.listArticles());
return new ModelAndView("createprogram");
}
#RequestMapping(value = "/saveprogram", method = RequestMethod.POST)
public ModelAndView saveProgram(#ModelAttribute("programform") ProgramForm programform,
BindingResult result) {
for(Programs programs : programform.getPrograms()) {
System.out.println(programs.getProgram_id());
articleService.addProgram(programs);
}
jsp
<c:url var="saveProgramUrl" value="/articles/saveprogram.html" />
<form:form modelAttribute="programform" method="POST" action="${saveProgramUrl}">
<table>
<tr>
<th>ProgramId</th>
<th>Date</th>
<th>Type</th>
<th>Start</th>
<th>End</th>
<th>Location</th>
<th>User</th>
<th>Program Name</th>
</tr>
<tr>
<th><form:input path="programs[0].program_id" /></th>
<th> <form:input path="programs[0].date" id="datepick" class="date-pick"/>
<script type="text/javascript">
datepickr('datepick', { dateFormat: 'Y-m-d' });
</script></th>
<th><form:input path="programs[0].type" /></th>
<th><form:input path="programs[0].start" /></th>
<th><form:input path="programs[0].end" /></th>
<th><form:input path="programs[0].location" /></th>
<th><form:input path="programs[0].user_id" /></th>
<th><form:input path="programs[0].program_name" /></th>
</tr>
<tr>
<th><form:input path="programs[1].program_id" /></th>
<th> <form:input path="programs[1].date" id="datepick" class="date-pick"/>
<script type="text/javascript">
datepickr('datepick', { dateFormat: 'Y-m-d' });
</script></th>
<th><form:input path="programs[1].type" /></th>
<th><form:input path="programs[1].start" /></th>
<th><form:input path="programs[1].end" /></th>
<th><form:input path="programs[1].location" /></th>
<th><form:input path="programs[1].user_id" /></th>
<th><form:input path="programs[1].program_name" /></th>
</tr>
</table>
<br/>
<input type="submit" value="Insert User" />
</form:form>
Program
package net.roseindia.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "program")
public class Programs {
#Id
#Column(name = "Program_Id")
private int program_id;
#Column(name = "Date")
private String date;
#Column(name = "Duty_Type")
private String type;
#Column(name = "Duty_Start_Time")
private String start;
#Column(name = "Duty_End_Time")
private String end;
#Column(name = "Location")
private String location;
#Column(name = "User_Id")
private int user_id;
#Column(name = "Program_Name")
private String program_name;
public int getProgram_id() {
return program_id;
}
public void setProgram_id(int program_id) {
this.program_id = program_id;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getStart() {
return start;
}
public void setStart(String start) {
this.start = start;
}
public String getEnd() {
return end;
}
public void setEnd(String end) {
this.end = end;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public int getUser_id() {
return user_id;
}
public void setUser_id(int user_id) {
this.user_id = user_id;
}
public String getProgram_name() {
return program_name;
}
public void setProgram_name(String program_name) {
this.program_name = program_name;
}
public Programs() {
}
}
ProgramForm
package net.roseindia.model;
import java.util.List;
public class ProgramForm {
private List<Programs> programs;
public List<Programs> getPrograms() {
return programs;
}
public void setPrograms(List<Programs> programs) {
this.programs = programs;
}
}
When i push the button to save this to programs nothing inserted in the database, what i am doing wrong?
To add multiple rows you need to lazy init your list. Please change your code in the #ModelAttribute("programform") as per following and then try again.
#ModelAttribute("programform")
public ProgramForm populatePojos() {
// Don't forget to initialize the pojos list or else it won't work
ProgramForm programform = new ProgramForm();
List<Programs> programs = LazyList.decorate(new ArrayList<Programs>(), FactoryUtils.instantiateFactory(Programs.class));
for(int i=0; i<2; i++) {
programs.add(new Programs());
}
programform.setPrograms(programs);
return programform;
}
With having list inilialized as above you can also add more fields run time using javascript and can get those values binded in your list.
After doing this changes if it won't work then you need to do changes in your jsp page. Instead of using the use simple tag but don't forget to specify the same value in name attribute as you have specified in the path attribute here.
Hope this helps you. Cheers.