Exception in JSP when populating a table with list - java

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();
}

Related

java.lang.ClassCastException: [Ljava.lang.Object; incompatible with com.spring.model.Instruction

public List<Instruction> listPAyment() {
Session session = this.sessionFactory.getCurrentSession();
List<Instruction> personsList = (List<Instruction>)session.createSQLQuery(
"SELECT INSTRUCTIONKEY, BASECURRENCY,STATUSPROC, WHENMODIFIED FROM MyDB.INSTRUCTION"
).list();
EXCEPTION HERE---> for(Instruction p : personsList){
System.out.println( "Payment::"+ p.toString());
}
return personsList;
}
I am getting java.lang.ClassCastException: [Ljava.lang.Object; incompatible with com.spring.model.Instruction exception at above mentioned point, I am unable to find out what's wrong with casting in below code.
I have added toString() correctly in model class Instruction
Please assist
[2016/09/05 15:05:01:991 GMT+02:00] 00000040 ServletWrappe E com.ibm.ws.webcontainer.servlet.ServletWrapper service SRVE0068E: An exception was thrown by one of the service methods of the servlet [/WEB-INF/views/instruction.jsp] in application [SpringMVCHibernate_war]. Exception created : [java.lang.NumberFormatException: For input string: "instructionKey"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:59)
at java.lang.Integer.parseInt(Integer.java:460)
at java.lang.Integer.parseInt(Integer.java:510)
at javax.el.ArrayELResolver.coerce(ArrayELResolver.java:166)
at javax.el.ArrayELResolver.getValue(ArrayELResolver.java:46)
at javax.el.CompositeELResolver.getValue(CompositeELResolver.java:55)
at org.apache.el.parser.AstValue.getValue(AstValue.java:174)
at org.apache.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:283)
at org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate(PageContextImpl.java:778)
at com.ibm._jsp._instruction._jspx_meth_c_forEach_0(_instruction.java:131)
at com.ibm._jsp._instruction._jspx_meth_c_if_0(_instruction.java:179)
at com.ibm._jsp._instruction._jspService(_instruction.java:95)
at com.ibm.ws.jsp.runtime.HttpJspBase.service(HttpJspBase.java:99)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:668)
at com.ibm.ws.cache.servlet.ServletWrapper.serviceProxied(ServletWrapper.java:307)
Jsp to iterate object:
<c:forEach items="${listPersons}" var="instruction">
<tr>
<td>${instruction.instructionKey}</td>
<td>${instruction.statusProc}</td>
<td>${instruction.baseCurrency}</td>
<td>${instruction.whenModified}</td>
</tr>
</c:forEach>
where model.addAttribute("instruction", new Instruction());
model.addAttribute("listPersons", this.personService.listPersons());
defined in controller.
You could pull from the DB into a class named :whatever: and give that class the variables that will be pulled from the DB and give it a toString method that you can call? Maybe?

Spring MVC: Bean property is not readable or has an invalid getter method Does the return type of the getter match the parameter type of the setter

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

java method can't run in a jsp file

I have a problem.
I have configured in eclipse hibernate with a database in mysql.
I have created a file java, and if I try to save some data to database works perfectly.
The problem is, if I create a jsp file, and try to call the same method it doesn't work, I guess it doesn't connect with hibernate.
public class CreateData {
public int age;
public static void main(String[] args) throws Exception {
SessionFactory sessFact = HibernateUtil.getSessionFactory();
Session session = sessFact.getCurrentSession();
org.hibernate.Transaction tr = session.beginTransaction();
Employee emp = new Employee();
emp.setEmpName("Deepak Kumar");
emp.setEmpMobileNos("000000");
emp.setEmpAddress("Delhi - India");
session.save(emp);
tr.commit();
System.out.println("Successfully inserted");
sessFact.close();
}
public void insert() throws Exception {
SessionFactory sessFact = HibernateUtil.getSessionFactory();
Session session = sessFact.getCurrentSession();
org.hibernate.Transaction tr = session.beginTransaction();
Employee emp = new Employee();
emp.setEmpName("Deepak Kumar");
emp.setEmpMobileNos("000000");
emp.setEmpAddress("Delhi - India");
session.save(emp);
tr.commit();
System.out.println("Successfully inserted");
sessFact.close();
}
public int getAge(){return this.age;}
}
So, if a run the main of this class java ,everything works fine.
but I can't run insert() method in this jsp file (obviously does the some thing as the main )
JSP FILE example:
jsp:useBean id= "user" class= "javabean.CreateData" scope="session"
<% user.getAge();%> // THIS WORKS
<% user.insert();%> // THIS DOESN'T WORK
when I run the jsp gives me an error
Stacktrace:
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:568)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:455)
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)
javax.servlet.ServletException: java.lang.NoClassDefFoundError: org/hibernate/HibernateException
org.apache.jasper.runtime.PageContextImpl.doHandlePageException(PageContextImpl.java:912)
org.apache.jasper.runtime.PageContextImpl.handlePageException(PageContextImpl.java:841)
org.apache.jsp.savesclient_jsp._jspService(savesclient_jsp.java:121)
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)
java.lang.NoClassDefFoundError: org/hibernate/HibernateException
javabean.insertClient.inserisci2(insertClient.java:61)
org.apache.jsp.savesclient_jsp._jspService(savesclient_jsp.java:101)
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)
java.lang.ClassNotFoundException: org.hibernate.HibernateException
org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1714)
org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1559)
javabean.insertClient.inserisci2(insertClient.java:61)
org.apache.jsp.savesclient_jsp._jspService(savesclient_jsp.java:101)
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)

attribute not sent to controller from view

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 :)

why my spring validation annotations doesnt work

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)

Categories