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 :)
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 have this jsp code .
<c:forEach var="item" items="${UsersList}">
<tr>
<td><c:out value="${item.userId}" /></td>
<td><c:out value="${item.userName}" /></td>
<td><c:out value="${item.car}" /></td> //Here , I am getting exception
</tr>
</c:forEach>
The UserList consists of an attribute called "car" of datatype "Car"
Pojo Class class for Users:
#Entity
#Table(name = "Users")
public class Users implements java.io.Serializable {
private int userId;
private Car car;
private Groups groupId;
private UserType userType;
private String userName;
//getters and setters
}
I am using Spring MVC Framework. On page load my app should show a table with the list of users . In controller I am querying for the list of users and I am adding it to the ModelAndView object
Controller code:
List<Users> userList = service.getUserList(); //this will get list of users
//System.out.println("Userlist ==" +userList.size());
mv.addObject("UsersList" , usersList);
//skipped remaining code
When I tried without car (tabledata tag) JSP is running without exception and showing the users list in the table . If I try to add car (tabledata tag) then I am getting an exception
HTTP Status 500 - An exception occurred processing JSP page /WEB-INF/pages/CreateUser.jsp at line 199
org.apache.jasper.JasperException: An exception occurred processing JSP page /WEB-INF/pages/CreateUser.jsp at line 199
196:<tr>
197:<td><c:outvalue="${item.userId}" /></td>
198:<td><c:out value="${item.userName}" /></td>
199:<!-- <td><c:out value="${item.car}" /></td> -->
200:<td><c:out value="${item.modifiedDate}" /></td>
201:</tr>
202:</c:forEach>
Stacktrace:
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWra pper.java:568)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:4 70)
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:51)
org.springframework.web.servlet.view.InternalResourceView.renderMergedOutput Model(InternalResourceView.java:168)
org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:3 03)
org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.j ava:1244)
org.springframework.web.servlet.DispatcherServlet.processDispatchResult(Disp atcherServlet.java:1027)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServl et.java:971)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServle t.java:893)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkSer vlet.java:970)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java :861)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.ja va:846)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)
root cause
org.hibernate.LazyInitializationException: could not initialize proxy - no Session
org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:149)
org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:195)
org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer.invoke(JavassistLazyInitializer.java:185)
com.bdp.pojo.Role_$$_javassist_11.toString(Role_$$_javassist_11.java)
org.apache.taglibs.standard.tag.common.core.OutSupport.out(OutSupport.java:178)
org.apache.taglibs.standard.tag.common.core.OutSupport.doStartTag(OutSupport.java:99)
org.apache.jsp.WEB_002dINF.pages.CreateUser_jsp._jspx_meth_c_005fout_005f2(CreateUser_jsp.java:667)
org.apache.jsp.WEB_002dINF.pages.CreateUser_jsp._jspx_meth_c_005fforEach_005f0(CreateUser_jsp.java:591)
org.apache.jsp.WEB_002dINF.pages.CreateUser_jsp._jspService(CreateUser_jsp.java:264)
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:51)
org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:168)
org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:303)
org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1244)
org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1027)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:971)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
org.springframeweb.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)
Since you are using hibernate lazy initialization, whenever you return the main object to the JSP it will try to fetch sub classes. And this wont happen because session would be closed.
Therefore change your fetching strategy to the Eager:
On your car's getter method:
#OneToOne(fetch=FetchType.EAGER)
This will cause fetching car immediatly when you fetch the main class.
To make it on query:
List<Users> items = session.createCriteria(Users.class)
.setFetchMode("car", FetchMode.JOIN).
.createAlias("car", "car").
.list();
You receive error LazyInitializationException. Users objects in a lazy Car object. service.getuserlist(); method can bring in by fetch the Car objects.
Fetching Strategies
FetchType.LAZY is on demand
FetchType.EAGER is immediate
#OneToOne(fetch=FetchType.EAGER) when you do want to take the user object as object the car all the time.
service.getUserList () please write.
EDIT :
Example getUserList method:
public List<Users> getUserList(){
String sql = " SELECT user from Users user left join fetch user.car ";
Query query = entityManager.createQuery(sql);
return query.getResultList();
}
I have Java Spring MVC application. I am trying to do CRUD on one table, say Employee.
When I am trying to create a new Employee, it saves and adds a new entry in database. But when I am trying to update an Employee, I am updating that row, and I am trying to add a new row, with the old values of the same employee and setting one field to false.
Here is my ServiceImpl
public class EmployeeServiceImpl extends
GenericManagerImpl<Employee, Long> implements
EmployeeService {
#Override
public void save(Employee employee) {
Employee newEmpl = employee;
Date date = new Date();
Long empKey = employee.getEmpKey();
if (empKey) != null) {
oldEmp = (Employee) employeeDao.get();
oldEmp.setActive(false);
oldEmp.setEmpKey(null);
employeeDao.save(oldEmp);
} else {
employee.setCreated(date);
}
employee.setUpdated(date);
employee.setActive(true);
employeeDao.save(employee);
}
}
When I am creating a new entry, it is working fine. But when I am trying to update one entry, then it showing the exception
org.springframework.orm.hibernate4.HibernateSystemException: identifier of an instance of com.table.model.Employee was altered from 4 to null; nested exception is org.hibernate.HibernateException: identifier of an instance of com.table.model.Employee was altered from 4 to null
at org.springframework.orm.hibernate4.SessionFactoryUtils.convertHibernateAccessException(SessionFactoryUtils.java:206)
at org.springframework.orm.hibernate4.HibernateTransactionManager.convertHibernateAccessException(HibernateTransactionManager.java:606)
at org.springframework.orm.hibernate4.HibernateTransactionManager.doCommit(HibernateTransactionManager.java:488)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:754)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:723)
at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:392)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:120)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
at com.sun.proxy.$Proxy77.save(Unknown Source)
at com.table.webapp.controllers.EmployeeController.saveEmployee(EmployeeController.java:164)
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.invoke(InvocableHandlerMethod.java:219)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:100)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:604)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:565)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:923)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:852)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:789)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:409)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1044)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:313)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:745)
Caused by: org.hibernate.HibernateException: identifier of an instance of com.table.model.Employee was altered from 4 to null
at org.hibernate.event.internal.DefaultFlushEntityEventListener.checkId(DefaultFlushEntityEventListener.java:82)
at org.hibernate.event.internal.DefaultFlushEntityEventListener.getValues(DefaultFlushEntityEventListener.java:194)
at org.hibernate.event.internal.DefaultFlushEntityEventListener.onFlushEntity(DefaultFlushEntityEventListener.java:156)
at org.hibernate.event.internal.AbstractFlushingEventListener.flushEntities(AbstractFlushingEventListener.java:225)
at org.hibernate.event.internal.AbstractFlushingEventListener.flushEverythingToExecutions(AbstractFlushingEventListener.java:99)
at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:51)
at org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1213)
at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:402)
at org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction.beforeTransactionCommit(JdbcTransaction.java:101)
at org.hibernate.engine.transaction.spi.AbstractTransactionImpl.commit(AbstractTransactionImpl.java:175)
at org.springframework.orm.hibernate4.HibernateTransactionManager.doCommit(HibernateTransactionManager.java:480)
... 43 more
I have checked this SO question, but they are using Query. My logic is in the Service Impl and not in DAO.
How can I alter the id and save as a new entry in database?
Thanks.
You shouldn't do that - it's in the JPA spec somewhere that one must not change a primary key.
What you could do is add a clone/copy method to your Employee class and use that to copy everything but the ID and then persist that new object.
Cheers,
I am trying to validate an input text component based on the value of a radio button component, however it throws a NullPointerException and I don't understand why.
Here's the view:
<h:form id="formId">
<p:inputText validator="#{searchBean.validate}" id="name"
required="true" requiredMessage="should contain only characters">
<f:validateRegex pattern="[a-zA-Z]*" />
<f:validator validatorId="inputValidator" />
</p:inputText>
<p:selectOneRadio value="#{searchBean.searchForm.selectedRadio}" id="customRadio">
<f:selectItem itemLabel="city" itemValue="1" />
<f:selectItem itemLabel="zipcode" itemValue="2" />
<f:selectItem itemLabel="state" itemValue="3" />
</p:selectOneRadio>
<p:commandButton value="Search" action="results.jsf" />
</h:form>
Here's the validator:
public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
UIViewRoot ui = new UIViewRoot();
UIInput radio = (UIInput) ui.findComponent("formId:customRadio");
boolean convertedAndValidatedValue = (Boolean) radio.getValue(); // This line is throwing the exception.
System.out.println("Validate"+convertedAndValidatedValue);
if (searchForm.selectedRadio.equals("city")) {
validateForCity(convertedAndValidatedValue);
} else if (searchForm.selectedRadio.equals("zipcode")) {
validateForZipcode(convertedAndValidatedValue);
} else {
validateForState(convertedAndValidatedValue);
}
}
Here's the exception:
javax.faces.FacesException
at com.sun.faces.lifecycle.ProcessValidationsPhase.execute(ProcessValidationsPhase.java:80)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:97)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:114)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:308)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
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:169)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:927)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:987)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:579)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:309)
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:679)
Caused by: java.lang.NullPointerException
at com.placessearch.action.SearchBean.validate(SearchBean.java:76)
at javax.faces.component.UIInput.validateValue(UIInput.java:1142)
at javax.faces.component.UIInput.validate(UIInput.java:960)
at javax.faces.component.UIInput.executeValidate(UIInput.java:1204)
at javax.faces.component.UIInput.processValidators(UIInput.java:693)
at javax.faces.component.UIForm.processValidators(UIForm.java:240)
at javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1081)
at javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1081)
at javax.faces.component.UIViewRoot.processValidators(UIViewRoot.java:1159)
at com.sun.faces.lifecycle.ProcessValidationsPhase.execute(ProcessValidationsPhase.java:72)
... 19 more
JSF components are converted and validated in the order as they appear in the component tree. Your validator is attached to an input text component which appears before the radio button component. However, you're trying to access the converted and validated value of the radio button component, while it is not been converted and validated at that point yet.
boolean convertedAndValidatedValue = (Boolean) radio.getValue();
It would only return null which you're in turn trying to autobox to boolean which would only cause NullPointerException.
You need to get the submitted value instead. Please note that the item values which you're specifying there are absolutely not booleans. It are numbers. Also note that the submitted value is always String (simply because that's exactly the type which request.getParameter() returns and also because at this moment it's not been converted by JSF/EL yet).
String submittedRadioValue = (String) radio.getSubmittedValue();
if (submittedRadioValue != null) {
int convertedRadioValue = Integer.valueOf(submittedRadioValue);
// ...
}
Update: another cause which I overlooked due to its unexpected nature is the following:
UIViewRoot ui = new UIViewRoot();
This is definitely also not right. You're supposed to retrieve the current one from the faces context instead of manually creating a completely empty one.
UIViewRoot ui = context.getViewRoot();
Otherwise radio would still be null and thus be another potential cause of the NullPointerException.
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.