Spring + thymeleaf Validanting integer error Neither BindingResult nor plain target object for bean name available as request attribute - spring

I'm in the process of learning spring and thymeleaf and working on a timekeeping project.
For this I need to validate the number of hours an employee clocks in one day.
I used the tutorial in the spring documentation for this however i keep getting the following error
Neither BindingResult nor plain target object for bean name 'timetable' available as request attribute
Any ideas what I might be doing wrong?
Controller class
#RequestMapping(value="Timetable/AddToTimetable", method = RequestMethod.GET)
public String newUser(Model md) {
md.addAttribute("assignments", serv.findAll());
return "AddToTimetable";
}
#RequestMapping(value = "/createEntry", method = RequestMethod.POST)
public String create(#RequestParam("assignmentId") int assignmentId,
#RequestParam("date") #DateTimeFormat(pattern = "yyyy-MM-dd") Date date,
#RequestParam("hoursWorked") int hoursWorked,
#Valid Timetable timetable, BindingResult bindingResult,
Model md) {
timetable = new Timetable();
timetable.setAssignmentId(assignmentId);
timetable.setDate(date);
timetable.setHoursWorked(hoursWorked);
md.addAttribute("timetables", service.timetableAdd(timetable));
if (bindingResult.hasErrors()) {
return "AddToTimetable";
}
return "redirect:/Timetable";
}
Service class
public BigInteger timetableAdd(Timetable timetable){
KeyHolder keyHolder = new GeneratedKeyHolder();
String sql = "INSERT INTO timetables ( assignmentId, date, hoursWorked) VALUES ( ?, ?, ?)";
template.update(new PreparedStatementCreator() {
public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
PreparedStatement pst = con.prepareStatement(sql, new String[] {"id"});
pst.setInt(1, timetable.getAssignmentId());
pst.setDate(2, new java.sql.Date(timetable.getDate().getTime()));
pst.setInt(3, timetable.getHoursWorked());
return pst;
}
}, keyHolder);
return (BigInteger) keyHolder.getKey();
}
}
Model class
package ro.database.jdbcPontaj.model;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.util.Date;
public class Timetable {
private int timetableId;
private int assignmentId;
private Date date;
private String project;
#NotNull
#Min(0)
#Max(12)
private int hoursWorked;
public int getTimetableId() {
return timetableId;
}
public void setTimetableId(int timetableId) {
this.timetableId = timetableId;
}
public int getAssignmentId() {
return assignmentId;
}
public void setAssignmentId(int assignmentId) {
this.assignmentId = assignmentId;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public int getHoursWorked() {
return hoursWorked;
}
public void setHoursWorked(int hoursWorked) {
this.hoursWorked = hoursWorked;
}
public String getProject() {
return project;
}
public void setProject(String project) {
this.project = project;
}
public Timetable() {
}
public Timetable(int timetableId, String project, Date date, int hoursWorked) {
this.timetableId = timetableId;
this.project=project;
this.date = date;
this.hoursWorked = hoursWorked;
}
public Timetable(int timetableId, int assignmentId, Date date, int hoursWorked) {
this.timetableId = timetableId;
this.assignmentId = assignmentId;
this.date = date;
this.hoursWorked = hoursWorked;
}
}
Html
<form method="post" name="comment_form" id="comment_form" th:action="#{/createEntry}" th:object="${timetable}" role="form">
<p> Project</p><br>
<select name="assignmentId">
<option value="" th:each="assignment: ${assignments}" th:value="${assignment.assignmentId}" th:text="${assignment.assignmentId}"></option>
</select>
<p>Date</p> <br>
<input class="datepicker" type="text" name="date"><br>
<p>Number of hours</p>
<input type="text" name="hoursWorked" th:field="*{hoursWorked}"><br>
<p th:if="${#fields.hasErrors('hoursWorked')}" th:errors="*{hoursWorked}">Age Error</p>
<button type="submit" id="submit" class="btn btn-primary">Submit</button>
</form>
UPDATE:
Timetable (skipping bootstrap divs)
<div class="row">
<div class="col-md-10 title">
<h2>Timetable</h2>
</div>
<div class="col-md-2">
</div>
<div class="col-md-12">
<table class="table table-bordered">
<thead>
<tr>
<th>id</th>
<th>assignment</th>
<th>date</th>
<th>number of hours</th>
</tr>
</thead>
<tbody>
<tr th:each = "timetable: ${timetables}">
<td th:text="${timetable.timetableId}">45</td>
<td th:text="${timetable.project}">vasi</td>
<td th:text="${timetable.date}">1 ian</td>
<td th:text="${timetable.hoursWorked}">3000</td>
</tr>
</tbody>
</table>
Service method for Timetable
#Autowired
JdbcTemplate template;
public List<Timetable> findAll(String loginname) {
String sql = " SELECT timetables.timetableId, timetables.assignmentId, timetables.date, " +
"timetables.hoursWorked, users.username, projects.projectName AS project " +
"FROM timetables INNER join assignments on timetables.assignmentId = assignments.assignmentId " +
"INNER JOIN projects on assignments.projectId = projects.projectId " +
"INNER JOIN users on users.userId = assignments.userId where username= ?";
RowMapper<Timetable> rm = new RowMapper<Timetable>() {
#Override
public Timetable mapRow(ResultSet resultSet, int i) throws SQLException {
Timetable timetable = new Timetable(resultSet.getInt("timetableId"),
resultSet.getString("project"),
resultSet.getDate("date"),
resultSet.getInt("hoursWorked"));
return timetable;
}
};
return template.query(sql, rm, loginname);
}
The controller method for Timetable
#RequestMapping(value = {"/Timetable"}, method = RequestMethod.GET)
public String index(Model md){
org.springframework.security.core.Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String loginname = auth.getName();
md.addAttribute("timetables", service.findAll(loginname));
return "Timetable";
}

If I understand correctly you have two html pages one that shows all the assignments and one that you enter the new entry.I think that get the error when there is a validation error in the new entry page.
Substitute these lines
if (bindingResult.hasErrors()) {
return "AddToTimetable";
}
with these ones
if (bindingResult.hasErrors()) {
return "newEntry";//replace the newentry with the html page that you enter the new entry
}
When there is an error, you should go to the page that you tried to enter the new entry and not in the page that has all the assignments.

Related

Springboot and thymealf loop

hope you can help with this simple noob problem. I creating a Multiple choice question using springboot and thymeleaf.I am getting this error and hope you can help me write the controller method.
Error during execution of processor 'org.thymeleaf.spring4.processor.attr.SpringInputGeneralFieldAttrProcessor' (learning:23)
Neither BindingResult nor plain target object for bean name 'options[0]' available as request attribute
<form method="post" th:action="#{/list}" >
<table>
<tr th:each="option, rowStat : *{a}">
<td><input type="radio" th:field="*{options[__${rowStat.index}__].ansA}" th:value="A"/></td>
<td><input type="radio" th:field="*{options[__${rowStat.index}__].ansB}" th:value="B"/></td>
</tr>
</table>
<input type="submit" value="ok"/>
</form>
Model object
#Entity
public class LearningStyle {
private int Qid;
private String question;
private String ansA;
private String ansB;
public LearningStyle(int qid, String question, String ansA, String ansB) {
Qid = qid;
this.question = question;
this.ansA = ansA;
this.ansB = ansB;
}
public LearningStyle(){}
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "Qid", nullable = false, updatable = false)
public int getQid() {
return Qid;
}
public void setQid(int qid) {
Qid = qid;
}
public String getQuestion() {
return question;
}
public void setQuestion(String question) {
this.question = question;
}
public String getAnsA() {
return ansA;
}
public void setAnsA(String ansA) {
this.ansA = ansA;
}
public String getAnsB() {
return ansB;
}
public void setAnsB(String ansB) {
this.ansB = ansB;
}
}
Controller
public class LearningStyleController {
#Autowired
LearningStyleService learningstyleservice;
#RequestMapping("/list")
public String learningstyle(Model model) {
List<LearningStyle> a= learningstyleservice.findAll();
model.addAttribute("a",a);
return "learning";
}
#RequestMapping(value = "/list", method = RequestMethod.POST)
public String learn(#ModelAttribute("a") LearningStyle learningStyle, Model model) {
//code to get list of object
return "home";
}

Error with NullPointerExcetion Native Method Accessor, Can give me a solution

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.

The request sent by the client was syntactically incorrect.-Spring MVC + JDBC Template

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").

Spring Validator for duplicate record in database

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");
}
...
Ну как то так))))

Spring mvc add multiple rows

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.

Resources