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

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?

Related

MyBatis error serialization into a List when 1 entity in DB

I have the request in my MyBatis xml mapper which should serialize got entities into a List:
<select id="findByClientAndPartnerWithAutoRenewal" resultType="java.util.List" resultMap="ClientAccessResult">
select * from client_access
where client_id = #{clientId}
and partner = #{partner}
<if test="autoRenewal != null">
and auto_renewal = #{autoRenewal}
</if>
order by id
</select>
This is the method signature from the connected interface:
List<ClientAccess> findByClientAndPartnerWithAutoRenewal(#Param("clientId") Long clientId,
#Param("partner") String partner,
#Param("autoRenewal") Boolean autoRenewal);
In case there is only 1 entity in my DB, I'll get the exception:
java.lang.ClassCastException: class com.test.bundle.core.model.entity.client.ClientAccess cannot be cast to class java.util.List (com.test.bundle.core.model.entity.client.ClientAccess is in unnamed module of loader org.springframework.boot.loader.LaunchedURLClassLoader #4520ebad; java.util.List is in module java.base of loader 'bootstrap')
at
com.test.bundle.service.security.impl.TokenServiceImpl$$EnhancerBySpringCGLIB$$d41bb384.findByClientAndPartnerWithAutoRenewal(<generated>)
How to fix the problem?

java.lang.ClassCastException: java.lang.Boolean cannot be cast to java.lang.String in Struts' logic:equal tag

I have an error when I want to acces my JSP page.
My bean:
public class BeChildren implements Serializable
{
...
private String isFilledChildren;
....
/**
* #param isFilledChildrenthe isFilledChildrento set
*/
public void setIsFilledChildren( String isFilledChildren)
{
this.isFilledChildren= isFilledChildren;
}
public String getIsFilledChildren( )
{
if ( getNom( ) != null )
{
return "true";
} else
{
return "false";
}
}
...
}
Error:
28/07/17-09:13:10,670 ERROR org.apache.struts.taglib.tiles.InsertTag - ServletException in '/pages/sub/dir/detail/body.jsp': javax.servlet.jsp.JspException: Invalid argument looking up property: "bean.enfant.isFilledChildren" of bean: "sub/dir/detail"
org.apache.jasper.JasperException: javax.servlet.ServletException: javax.servlet.jsp.JspException: Invalid argument looking up property: "bean.enfant.isFilledChildren" of bean: "sub/dir/detail"
javax.servlet.jsp.JspException: Invalid argument looking up property: "bean.children.isFilledChildren" of bean: "sub/dir/detail"
java.lang.ClassCastException: java.lang.Boolean cannot be cast to java.lang.String
My JSP:
https://pastebin.com/QmgtXBqA
...
<html:form action="/page/sub/dir/detail.do">
<html:hidden name="sub/dir/detail" property="modeCreation" styleId="modeCreation"/>
<html:hidden name="sub/dir/detail" property="bean.enfant.isFilledChildren"/>
....
<logic:equal name="sub/dir/detail" property="bean.enfant.isFilledChildren" value="true">
.....
</logic:equal>
...
<script language="javascript" type="text/javascript">
var f = document.forms[0];
function init(){
var isFilledChildren = document.forms[0].elements["bean.enfant.isFilledChildren"];
....
if (isFilledChildren!=null && "true"==isFilledChildren.value){
...
}
}
....
What is wrong ?
The error is ecause you pass boolean value to isFilledChildren property as parameter
<logic:equal name="sub/dir/detail" property="bean.enfant.isFilledChildren" value="true">
In your bean the property accepts String value
The property that is of String type should use the string value to avoid ClassCastException.
<logic:equal name="sub/dir/detail" property="bean.enfant.isFilledChildren" value="'true'">
Changing the type for isFilledChildren property to String would resolve this.
If it does not, try with <logic:match /> and <logic:notMatch /> (if it's feasible in this use case). See below for logic:match sample code"
<logic:match name="UserForm" property="favouriteFood" value="Pizza">

Exception in JSP when populating a table with list

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

HandlerInterceptorAdapter doesn't run for error page

There is class, who extends HandlerInterceptorAdapter, with method:
#Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
...
request.getSession().setAttribute("user", user);
}
This attribute is visible to all views, except error views :(
My ExceptionConfiguration:
#Bean
public SimpleMappingExceptionResolver simpleMappingExceptionResolver(){
SimpleMappingExceptionResolver r = new SimpleMappingExceptionResolver();
Properties mappings = new Properties();
mappings.setProperty("DatabaseException", "error/error");
r.setExceptionMappings(mappings);
r.setDefaultErrorView("error/defaultError");
return r;
}
Piece of my "error/error" page:
<h3 th:text="${user.name}" />
<p><h3 th:text="${exception.message}" /></p>
<h3>Please contact support.</h3>
And my exception is:
org.springframework.web.util.NestedServletException: Request processing failed
org.thymeleaf.exceptions.TemplateProcessingException: Exception evaluating SpringEL expression: "user.name"
org.springframework.expression.spel.SpelEvaluationException: EL1007E:(pos 0): Field or property 'name' cannot be found on null
How can I make attribute 'user' visible to error pages too?
Thank you in advance.

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

Categories