i have simple for where i put one string and im using annotations to valid the value
and it doesnt work
here is my class:
public class Destination
{
#NotNull
String address;
public Destination(){}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
here is my controller method
#RequestMapping(value = "/search", method = RequestMethod.POST)
public String findDestination(#ModelAttribute("destination") #Valid Destination destination, BindingResult result, RedirectAttributes redirectAttrs) {
if(result.hasErrors()) {
return "redirect:/";
}
Location location = LocationManager.getLocation(destination.getAddress());
Weather weather = WeatherManager.getWeather(location);
redirectAttrs.addFlashAttribute("weather", weather);
redirectAttrs.addFlashAttribute("location", location);
return "redirect:/";
}
and here is my form in jsp file:
<form:form method="post" action="search" commandName="destination" class="form-horizontal">
<div class="control-group">
<div class="controls">
<form:input path="address" placeholder="Enter destination address"/>
<form:errors path="address" cssclass="error"></form:errors>
<input type="submit" value="Search" class="btn"/>
</form:form>
</div>
</div>
so the problem is that it doesnt valid my input
when i left it empty it still try to get addres for location object from null destination object and i get the exception
HTTP Status 500 - Request processing failed; nested exception is java.util.NoSuchElementException
exception
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.util.NoSuchElementException
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:948)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:838)
javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
root cause
java.util.NoSuchElementException
java.util.ArrayList$Itr.next(ArrayList.java:794)
com.springapp.mvc.domain.LocationManager.getLocation(LocationManager.java:52)
com.springapp.mvc.controller.HomeController.findDestination(HomeController.java:51)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:601)
org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:219)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:745)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:686)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:936)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:838)
javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
Empty html inputs when submitted are empty strings, this could be why your validation isn't working. You can try adding the #Size annotation, i.e. #Size(min=1)
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
Working on a Spring MVC based project, I am getting the following code while I try to save review (Bean). I am able to get the data into controller successfully but for some reason getting a NULL pointer exception while saving.
Here is the code
-- JSP--
<div class="col-md-12">
<div class="p-b">
<cf:form action="${pageContext.request.contextPath}/reviews/add" id="reviewAction" modelAttribute="review" method="post" accept-charset="utf-8">
<div style="display:none">
<cf:input path="tutorId" type="hidden" name="tutorId" id="tutorId" value="" />
<cf:input path="studentId" type="hidden" name="studentId" id="studentId" value="${sessionScope.user.userId}" />
</div>
<label>Your Comment / Review</label>
<cf:textarea path="reviewMessage" name="reviewMessage" required="required"/>
<p class="text-right"><input type="submit" class="btn btn-default btn-sm" name="submit" value="Post"> </p>
</cf:form>
</div>
</div>
<cf:hidden path="userId" id="userId"/>
<script type="text/javascript">
$(document).ready(function () {
console.log("Calling getTutorId()");
getTutorId();
});
function getTutorId()
{
$('#tutorId').attr('value',$('#userId').val());
}
</script>
-- Controller --
#RequestMapping (value = "/add" , method = RequestMethod.POST)
public String addReview(#Valid #ModelAttribute Review review , BindingResult bindingResult, Model model) {
try {
if (bindingResult.hasErrors()) {
System.out.println(bindingResult.getAllErrors().iterator().next().toString());
return "FindTutor";
}
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
Date date = new Date();
String newDate = dateFormat.format(date); //06/08/2016 15:59:48
review.setDate(newDate);
review.setReviewStatus("Disapproved");
//Just for testing purposes
System.out.println(review.getStudentId());
System.out.println(review.getTutorId());
System.out.println(review.getDate());
System.out.println(review.getReviewMessage());
System.out.println(review.getReviewStatus());
//Just for testing purposes
reviewBL.saveReview(review);
List<Subject> subjectList = subjectBL.getAllSubjects();
List<User> userList = manageUserBL.getAllUsers();
model.addAttribute("subjectList", subjectList);
model.addAttribute("userList", userList);
} catch (Exception e) {
e.printStackTrace();
}
return "FindTutor";
}
-- Business Logic Class --
#Service
public class ReviewBL {
private ReviewsMongoRepository reviewsMongoRepository;
public void saveReview(Review review)
{
if (StringUtils.isEmpty(review.getId())) {
review.setId(null);
}
reviewsMongoRepository.save(review);
}
}
-- Bean Class --
#Document (collection = "reviews")
public class Review {
#Id
private String Id;
private String tutorId;
private String studentId;
private String date;
private String reviewMessage;
private String reviewStatus;
// plus constructors also all of the getters and setters
}
I am getting the following error message, and as you can see the data (Model Attribute is successfully been captured in the controller but is not being saved in the database due to a NULL pointer exception error that I can't seem to find out why
2016-05-28 13:16:59 [http-bio-8080-exec-6] INFO e.b.fyp.stp.web.filter.SessionFilter - Filtering: /reviews/add
java.lang.NullPointerException
at edu.bnu.fyp.stp.bl.ReviewBL.saveReview(ReviewBL.java:23)
at edu.bnu.fyp.stp.web.controller.student.ReviewController.addReview(ReviewControll er.java:66)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:776)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:705)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:967)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:869)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:650)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:843)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at edu.bnu.fyp.stp.web.filter.SessionFilter.doFilter(SessionFilter.java:59)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:956)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:436)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1078)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:625)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:318)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
574939f19fcf9da523b63f8b // ID 1 (String)
57493a3e9fcf9da523b63f8c // ID 2 (String)
28/05/2016 13:16:59 //Date (String)
Great Tutor // Message (String)
Disapproved //Status (String)
2016-05-28 13:16:59 [http-bio-8080-exec-6] INFO e.b.fyp.stp.web.filter.SessionFilter - Filtering: /WEB-INF/jsp/FindTutor.jsp
I was able to resolve this issue. It was because I didn't apply #Autowired on reviewsMongoRepository so it wasn't linked with the review bean. I corrected this and now it is working. Thank you
Inside ReviewBL.saveReview you are calling reviewsMongoRepository.save(review)
But I can see you havent initialized reviewsMongoRepository, this is just a reference type reffering to "nothhing." It might be the cause of your Null Pointer exception
I'm using Hibernate. I used layerise architecture "Controller,Service,DAO" in this project. I tried to save data in db.These data pass DTO to DB. but I run project and filled form using complaint.jsp page.I getting following exception....
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.hibernate.exception.LockTimeoutException: could not execute statement
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:973)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:863)
javax.servlet.http.HttpServlet.service(HttpServlet.java:650)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
root cause
org.hibernate.exception.LockTimeoutException: could not execute statement
org.hibernate.dialect.MySQLDialect$1.convert(MySQLDialect.java:447)
org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49)
org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:126)
org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:112)
org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:190)
org.hibernate.engine.jdbc.batch.internal.NonBatchingBatch.addToBatch(NonBatchingBatch.java:62)
org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3124)
org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3587)
org.hibernate.action.internal.EntityInsertAction.execute(EntityInsertAction.java:103)
org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:453)
org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:345)
org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:350)
org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:56)
org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1218)
org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:421)
org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction.beforeTransactionCommit(JdbcTransaction.java:101)
org.hibernate.engine.transaction.spi.AbstractTransactionImpl.commit(AbstractTransactionImpl.java:177)
edu.ijse.tcd.dao.impl.ComplaintDAOImpl.addComplaint(ComplaintDAOImpl.java:35)
edu.ijse.tcd.service.impl.ComplaintServiceImpl.addComplaint(ComplaintServiceImpl.java:30)
edu.ijse.tcd.controller.ComplaintController.addComplaint(ComplaintController.java:42)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:497)
org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:749)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:689)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:938)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:870)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:863)
javax.servlet.http.HttpServlet.service(HttpServlet.java:650)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
root cause
java.sql.SQLException: Lock wait timeout exceeded; try restarting transaction
com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1094)
com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4226)
com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4158)
com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2615)
com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2776)
com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2840)
com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2082)
com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2334)
com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2262)
com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2246)
org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:187)
org.hibernate.engine.jdbc.batch.internal.NonBatchingBatch.addToBatch(NonBatchingBatch.java:62)
org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3124)
org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3587)
org.hibernate.action.internal.EntityInsertAction.execute(EntityInsertAction.java:103)
org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:453)
org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:345)
org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:350)
org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:56)
org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1218)
org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:421)
org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction.beforeTransactionCommit(JdbcTransaction.java:101)
org.hibernate.engine.transaction.spi.AbstractTransactionImpl.commit(AbstractTransactionImpl.java:177)
edu.ijse.tcd.dao.impl.ComplaintDAOImpl.addComplaint(ComplaintDAOImpl.java:35)
edu.ijse.tcd.service.impl.ComplaintServiceImpl.addComplaint(ComplaintServiceImpl.java:30)
edu.ijse.tcd.controller.ComplaintController.addComplaint(ComplaintController.java:42)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:497)
org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:749)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:689)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:938)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:870)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:863)
javax.servlet.http.HttpServlet.service(HttpServlet.java:650)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
complaint.jsp page
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<!-- jobNumber varchar(100),
complaint_id varchar(10) primary key,
nature varchar(200),
instruction varchar(200),-->
<form:form action="addComplaint" modelAttribute="ComplaintMap" method="POST">
<form:input path="jobNumber" placeholder="jobNumber ?"></form:input>
<form:input type="hidden" path="complaintId" value="0" placeholder="complaintId ?"></form:input>
<form:input path="nature" placeholder="nature ?"></form:input>
<form:input path="instruction" placeholder="instruction ?"></form:input>
<input value="SAVE" type="submit"/>
</form:form>
</table>
</body>
</html>
following code is Controller layer code
#Controller
#RequestMapping("/")
public class ComplaintController {
#Autowired
private ComplaintService complaintService;
#RequestMapping(value = "complaint", method = RequestMethod.GET)
public String loadComplaint(ModelMap map){
Complaint complaint = new Complaint();
ArrayList<Complaint> complaints = complaintService.getComplaints();
map.addAttribute("ComplaintMap", complaint);
map.addAttribute("ComplaintList", complaints);
return "complaint";
}
#RequestMapping(value = "addComplaint" , method = RequestMethod.POST)
public String addComplaint(#Valid Complaint complaint,ModelMap map){
complaintService.addComplaint(complaint);
ArrayList<Complaint> complaints = complaintService.getComplaints();
map.addAttribute("ComplaintMap", new Complaint());
map.addAttribute("ComplaintList", complaints);
return "complaint";
}
}
following code is DAO layer Code
#Repository
public class ComplaintDAOImpl implements ComplaintDAO{
#Autowired
private SessionFactory sessionFactory;
public Session getSession(){
return sessionFactory.openSession();
}
public boolean addComplaint(Complaint complaint) {
Session session = getSession();
session.beginTransaction();
session.save(complaint);
session.getTransaction().commit();
session.close();
return true;
}
}
}
Db.sql code
CREATE TABLE Complaint(
jobNumber varchar(100),
complaint_id varchar(10) primary key,
nature varchar(200),
instruction varchar(200),
constraint foreign key(jobNumber) references JobCard(jobNumber)
on delete cascade on update cascade
);
I am new to Spring MVC and I am having a problem in my application, I have been trying to populate a dropdown box with information from my database but I keep getting an error in the JSP, I get all the information in the controller but I cannot show it in the view, I have found similar cases in the site but none has an answer that I can use.
I keep getting the same error no matter what I try, the exception is the following:
org.springframework.beans.NotReadablePropertyException: Invalid property 'nombreEstado' of bean class [java.util.ArrayList]: Bean property 'nombreEstado' is not readable or has an invalid getter method: Does the return type of the getter match the parameter type of the setter?
org.springframework.beans.BeanWrapperImpl.getPropertyValue(BeanWrapperImpl.java:725)
org.springframework.beans.BeanWrapperImpl.getPropertyValue(BeanWrapperImpl.java:716)
org.springframework.web.servlet.support.BindStatus.<init>(BindStatus.java:149)
org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getBindStatus(AbstractDataBoundFormElementTag.java:168)
org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getPropertyPath(AbstractDataBoundFormElementTag.java:188)
org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getName(AbstractDataBoundFormElementTag.java:154)
org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.writeDefaultAttributes(AbstractDataBoundFormElementTag.java:117)
org.springframework.web.servlet.tags.form.AbstractHtmlElementTag.writeDefaultAttributes(AbstractHtmlElementTag.java:422)
org.springframework.web.servlet.tags.form.SelectTag.writeTagContent(SelectTag.java:194)
org.springframework.web.servlet.tags.form.AbstractFormTag.doStartTagInternal(AbstractFormTag.java:84)
org.springframework.web.servlet.tags.RequestContextAwareTag.doStartTag(RequestContextAwareTag.java:80)
org.apache.jsp.WEB_002dINF.views.home_jsp._jspService(home_jsp.java:141)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:209)
org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:267)
org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1225)
org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1012)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:876)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:852)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52
Right now I have this method in my controller:
#ModelAttribute("estados")
public List<Estado> obtenerEstados(){
logger.debug("buscando todos los estados");
for (int i = 0; i < this.estadoBo.obtenerEstados().size(); i++) {
System.out.println(this.estadoBo.obtenerEstados().get(i).getNombreEstado());
}
return this.estadoBo.obtenerEstados();
}
I used the cycle just to see if the values were coming right from the database
And the JSP
<form:form modelAttribute="estados">
<form:select path="nombreEstado" id="nombreEstado">
<form:option value="">Estado: </form:option>
<c:forEach items="${estados.getNombreEstado}" var="estado">
<form:option value="${estado}">${estado}</form:option>
</c:forEach>
</form:select>
I get the error in the line of the select path = "nombreEstado"
I don't know what I am doing wrong, any help will be welcomed
Thanks in Advance
The jsp stayed like this:
<form:form modelAttribute="searchForm">
<form:select path="nombreEstado" id="nombreEstado">
<form:option value="">Estado: </form:option>
<c:forEach items="${estados}" var="estado">
<form:option value="${estado}">${estado}</form:option>
</c:forEach>
</form:select>
I removed from items the getEstado property and from the controller I did the following changes:
#ModelAttribute("estados")
public List<String> obtenerEstados(){
logger.debug("buscando todos los estados");
int cantidadEstados = this.estadoBo.obtenerEstados().size();
ArrayList<String> estadoLista = new ArrayList<String>();
for (int i = 0; i < cantidadEstados; i++) {
estadoLista.add(this.estadoBo.obtenerEstados().get(i).getNombreEstado());
}
return estadoLista;
}
and this is where I had the problem:
#ModelAttribute("estados")
public List<String> obtenerEstados(){
logger.debug("buscando todos los estados");
int cantidadEstados = this.estadoBo.obtenerEstados().size();
ArrayList<String> estadoLista = new ArrayList<String>();
for (int i = 0; i < cantidadEstados; i++) {
estadoLista.add(this.estadoBo.obtenerEstados().get(i).getNombreEstado());
}
return estadoLista;
}
I added the attribute searchForm to the model with the new bean object and now it works fine
In a spring mvc application using hibernate, a JSP is not passing a populated value for an object called code of type CPTCode when the user clicks the submit button after selecting a value for code from the drop down list in the form. As a result, I am getting a null pointer exception when the controller method for the jsp runs. Can someone show me how to fix my code so that the null pointer error goes away and the controller can see the code which the user selected?
The code is selected from a preset of list of possible codes, and a reference to the code is then added to an arraylist property of an Encounter entity which has a ManyToMany relationship with CPTCode.
Here is the JSP:
<html lang="en">
<jsp:include page="../fragments/headTag.jsp"/>
<body>
<div class="container">
<jsp:include page="../fragments/bodyHeader.jsp"/>
<c:set var="method" value="put"/>
<h2>Codes</h2>
<form:form modelAttribute="code" method="${method}" class="form-horizontal">
<div class="control-group" id="patient">
<label class="control-label">Patient </label>
<c:out value="${encounter.patient.firstName} ${encounter.patient.lastName}"/>
${encounter.dateTime}
</div>
<div class="control-group">
<form:select path="${code}" items="${encountercodes}" size="5" style="min-width:600px"/>
</div>
<td></td>
<div class="form-actions">
<button type="submit">Add a Billing Code</button> <h3> Link to delete will go here.</h3>
</div>
</form:form>
</div>
</body>
</html>
Here is the controller method:
#RequestMapping(value = "/patients/{patientId}/encounters/{encounterId}/codes", method = RequestMethod.GET)
public String initUpdateCodesForm(#PathVariable("encounterId") int encounterId, Map<String, Object> model) {
System.out.println("--------------------------------- made it into initUpdateForm() method");
Encounter encounter = this.clinicService.findEncounterById(encounterId);
CPTCode code = new CPTCode();
model.put("code", code);
model.put("encounter", encounter);
return "encounters/createOrUpdateCodesForm";
}
#RequestMapping(value = "/patients/{patientId}/encounters/{encounterId}/codes", method = {RequestMethod.PUT, RequestMethod.POST})
public String processUpdateCodesForm(#ModelAttribute("code") CPTCode code, #PathVariable("encounterId") int eid, BindingResult result, SessionStatus status) {
Encounter encounter = this.clinicService.findEncounterById(eid);
System.out.println("-------- code.id and code.name are: "+code.getId()+", "+code.getName());//null error here
int maxId = 0;
for(int u=0;u<encounter.getCodes().size();u++){
if(encounter.getCodes().get(u).getId()>maxId){
maxId = encounter.getCodes().get(u).getId();
}
}
code.setId(maxId+1);
encounter.addCode(code);
System.out.println("... in processUpdateCodesForm() just did encounter.addCode(code)");
this.clinicService.saveEncounter(encounter);
System.out.println("..... encounter.id, encounter.codes.size are: "+encounter.getId()+", "+encounter.getCodes().size());
return "redirect:/encounters?encounterID={encounterId}";
}
Here is the complete stack trace:
java.lang.NullPointerException: null
at org.springframework.samples.knowledgemanager.model.CPTCode.getId(CPTCode.java:30) ~[CPTCode.class:na]
at org.springframework.samples.knowledgemanager.web.EncounterCodeController.processUpdateCodesForm(EncounterCodeController.java:104) ~[EncounterCodeController.class:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.6.0_29]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) ~[na:1.6.0_29]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) ~[na:1.6.0_29]
at java.lang.reflect.Method.invoke(Method.java:597) ~[na:1.6.0_29]
at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:219) ~[spring-web-3.2.5.RELEASE.jar:3.2.5.RELEASE]
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132) ~[spring-web-3.2.5.RELEASE.jar:3.2.5.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104) ~[spring-webmvc-3.2.5.RELEASE.jar:3.2.5.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:745) ~[spring-webmvc-3.2.5.RELEASE.jar:3.2.5.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:686) ~[spring-webmvc-3.2.5.RELEASE.jar:3.2.5.RELEASE]
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80) ~[spring-webmvc-3.2.5.RELEASE.jar:3.2.5.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925) [spring-webmvc-3.2.5.RELEASE.jar:3.2.5.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856) [spring-webmvc-3.2.5.RELEASE.jar:3.2.5.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:936) [spring-webmvc-3.2.5.RELEASE.jar:3.2.5.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.doPut(FrameworkServlet.java:849) [spring-webmvc-3.2.5.RELEASE.jar:3.2.5.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:650) [servlet-api.jar:na]
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812) [spring-webmvc-3.2.5.RELEASE.jar:3.2.5.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728) [servlet-api.jar:na]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305) [catalina.jar:7.0.42]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210) [catalina.jar:7.0.42]
at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:74) [spring-web-3.2.5.RELEASE.jar:3.2.5.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-3.2.5.RELEASE.jar:3.2.5.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243) [catalina.jar:7.0.42]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210) [catalina.jar:7.0.42]
at com.github.dandelion.datatables.core.web.filter.DatatablesFilter.doFilter(DatatablesFilter.java:73) [datatables-core-0.9.2.jar:na]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243) [catalina.jar:7.0.42]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210) [catalina.jar:7.0.42]
at com.github.dandelion.datatables.extras.servlet2.filter.DatatablesFilter.doFilter(DatatablesFilter.java:71) [datatables-servlet2-0.9.2.jar:na]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243) [catalina.jar:7.0.42]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210) [catalina.jar:7.0.42]
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88) [spring-web-3.2.5.RELEASE.jar:3.2.5.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-3.2.5.RELEASE.jar:3.2.5.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243) [catalina.jar:7.0.42]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210) [catalina.jar:7.0.42]
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222) [catalina.jar:7.0.42]
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123) [catalina.jar:7.0.42]
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502) [catalina.jar:7.0.42]
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171) [catalina.jar:7.0.42]
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99) [catalina.jar:7.0.42]
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953) [catalina.jar:7.0.42]
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118) [catalina.jar:7.0.42]
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408) [catalina.jar:7.0.42]
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023) [tomcat-coyote.jar:7.0.42]
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589) [tomcat-coyote.jar:7.0.42]
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312) [tomcat-coyote.jar:7.0.42]
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886) [na:1.6.0_29]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908) [na:1.6.0_29]
at java.lang.Thread.run(Thread.java:662) [na:1.6.0_29]
The code for the entities can be read at a file sharing site by clicking on the links below:
The code for the Encounter entity can be read at this link.
The code for the CPTCode entity can be read at this link.
The code for the Patient class can be found at this link.
The code for Person is at this link.
The code for BaseEntity is at this link.
NOTE:
Deleting the line <form:select path="${code}" items="${encountercodes}" size="5" style="min-width:600px"/> eliminates the error message, but also deletes the drop down list, which is central to this JSP. How can I get the drop down list to work?
From your stacktrace message :
java.lang.NullPointerException: null
at org.springframework.samples.knowledgemanager.model.CPTCode.getId(CPTCode.java:30) ~[CPTCode.class:na]
it means the id attribute of CPTCode is null, when you use it, that time will raise a NullPointerException.
So, To get work your code, change the following:
To add a select box with CPTCode in your form, modify like:
<form:form modelAttribute="encounter" method="post" class="form-horizontal" action="${actUrl}">
<div class="control-group">
<form:select path="codeSelected" items="${encountercodes}" size="5" style="min-width:600px"/>
</div>
<form:hidden path="id"/>
<td>
</td>
<div class="form-actions">
<button type="submit">Add a Billing Code</button> <h3> Link to delete will go here.</h3>
</div>
</form:form>
then, add a variable private Integer codeSelected; to your Encounter class, with getter and setter.
Populate encountercodes in your controller like:
#ModelAttribute("encountercodes")
public Map populateEncountercodes() {
Map<Integer, String> encCodes = new LinkedHashMap<Integer, String>();
for(CPTCode cpt: this.clinicService.findEncountercodes()){
encCodes.put(cpt.getId(), cpt.getName());
}
return encCodes;
}
And In your POST modify like:
#RequestMapping(value = "/patients/{patientId}/encounters/{encounterId}/codes", method = {RequestMethod.POST})
public String processUpdateCodesForm(#ModelAttribute("encounter") Encounter encounter,
#PathVariable("encounterId") int eid, BindingResult result, SessionStatus status) {
Encounter myencounter = this.clinicService.findEncounterById(eid);
CPTCode myCode = this.clinicService.findCPTCodeById(encounter.getCodeSelected());
myencounter.addCode(myCode);
return "redirect:/encounters?encounterID={encounterId}";
}
Spring MVC is trying to get values out of your CPTCode object
CPTCode.getId(CPTCode.java:30)
But they are null since you are passing in an emtpy object
CPTCode code = new CPTCode();
model.put("code", code);
Populate some values into code, have your class initialize values in the default constructor, or have your Class return defaults in the getters so you are not returning null.
I suggest you consider familiarizing yourself with the Null Object Pattern.
Remove the drop down and fist try with a
<form:form modelAttribute="code" method="${method}" class="form-horizontal">
<input type='text' name="id" name='id' value='100'>
<div class="form-actions">
<button type="submit">Add a Billing Code</button> <h3> Link to delete will go here.</h3>
</div>
</form:form>
try this and you it should work.. So you will able to follow this to lists too :)
How can i initialized Multipart request..? I am uploading file using multipart/form-data content type but i can't get multipart request in my controller.So how can i get multipart request in my controller ..
Thanks in Advance.
I am getting error like this..
Jun 13, 2012 2:01:05 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [appServlet] in context with path [/Login] threw exception [Request processing failed; nested exception is java.lang.IllegalStateException: Multipart request not initialized] with root cause
java.lang.IllegalStateException: Multipart request not initialized
at org.springframework.web.multipart.support.AbstractMultipartHttpServletRequest.initializeMultipart(AbstractMultipartHttpServletRequest.java:107)
at org.springframework.web.multipart.support.AbstractMultipartHttpServletRequest.getMultipartFiles(AbstractMultipartHttpServletRequest.java:97)
at org.springframework.web.multipart.support.AbstractMultipartHttpServletRequest.getFile(AbstractMultipartHttpServletRequest.java:60)
at com.mpm.common.controller.FileUploadController.create(FileUploadController.java:62)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:176)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:436)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:424)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:790)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:669)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:585)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:304)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:224)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:164)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:929)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:405)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:279)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:515)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:300)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at java.lang.Thread.run(Thread.java:722)
And my JSP code is :
<body>
<h1>Please upload a file</h1>
<form method="post" action="upload.action" enctype="multipart/form-data">
<input type="text" name="name"/></br>
<input type="file" name="file"/></br>
<input type="submit"/>
</form>
</body>
and my servlet-context.xml code is :
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- one of the properties available; the maximum file size in bytes -->
</bean>
<bean id="fileUploadController" class="com.mpm.common.controller.FileUploadController" ></bean>
You seem to use Spring. In that case, I usually manage multipart requests like this:
#RequestMapping("/url")
public String method(HttpServletRequest request) {
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
// do stuff with multipartRequest
return "/jsp";
}
You simply need to cast your HttpServletRequest request.
public void upload(HttpServletRequest request) {
File up = new File("C:\\temp"); // path where u need to upload
// Create object of MultipartRequest to upload file
MultipartRequest m;
try {
m = new MultipartRequest(request, up.toString());
Enumeration files = m.getFileNames();
// Get the files to be uploaded from enumeration
while (files.hasMoreElements()) {
String upload = (String) files.nextElement();
filename = m.getFilesystemName(upload);
// out.println("<br/><br/><br/><br/>");
}
} catch (IOException e) {
System.out.println("Error in Uploading files...");
}
xsdName = filename.substring(0, filename.lastIndexOf('.'));
}
it was my code to do the same in servlet. Hope it helps.