Object Casting in a JSP

When getting data from the usual HttpSession object, I understand how the following (for simplicity) hypothetical line of code works:
AccountInfo someAccount = (AccountInfo) session.getAttribute( ... );
Here, assume that "AccountInfo" is a bean i.e., implements serializable and has standad getters and setters. So far nothing special but wait... What about the following variation:
AccountInfo someAccount = (AccountInfo) (List) session.getAttribute( ... );
The surprising thing was that the someAccount object has its data populated with items from the list! Why do I say such silly things? Well the code that follows leads me to that conclusion:
AccountInfo someAccount = (AccountInfo) (List) session.getAttribute( ... );
this.doSomething(accInfo);
It's not obvious to me when the getters and setters of accInfo were called?? Can someone provide an explanation? I was not aware of this mechanism. Should I get a new Java book?
Thanks!

EDITED VERSION OF THE ABOVE POST
When getting data from the usual HttpSession object, I understand how the following hypothetical line of code works:
AccountInfo someAccount = (AccountInfo) session.getAttribute( ... );
Here, assume that "AccountInfo" is a bean i.e., implements serializable and has standad getters and setters. So far nothing special but wait... What about the following variation (I saw something like this in some code at work)
AccountInfo someAccount = (AccountInfo) (List) session.getAttribute( ... );
So its just two sequential casts, right? What surprised me, was that the someAccount bean has its data populated with items from the list! Can someone provide an explanation? I was not aware of this mechanism. Should I get a new Java book?
Thanks

Similar Messages

  • Class Cast Exception in JSP of the component

    Hi,
      I am trying to call a web service from the JSP of the component.I have written the java code as a scriplets in the JSP. The problem i am facing is Class Cast Exception. The code is as follows
    String strKey = "wsclients/proxies/sap.com/CCMSContentBroker/com.sap.ccmscontentbroker.CCMSContentProxy";
    java.lang.Object obj ;
    obj = context.lookup(strKey);
    str1 = obj.getClass().getName();
    ContentBroker objCB= null; 
    objCB = (ContentBroker)obj; // getting error here
    ContentBroker is an web service interface. The same code is working if i write it in the component but not in the scriplet of the JSP.
    Can't we do the type cast in the JSP ?
    Cant we call the web services in the JSP?
    How to eliminate this Class cast Exception in my code?
    Thanks and Regards,
    Saravanan

    Hi Harini,
             Thanks for your reply. I have checked all the import statements in the JSP.The problem is in the Type casting of object <b>obj</b> to ContentBroker variable <b>objCB</b>.
    Are u saying typr casting is not possible in JSP or organising imports in the JSP.
    These are my imports statements in the JSP
    <%@ page import = "java.util.ResourceBundle" %>
    <%@ page import = "com.sapportals.htmlb.*" %>
    <%@ page import = "com.intel.ccmt.ccmscontentbroker.* "%>
    <%@ page import = "com.intel.ccmt.ccmscontentbroker.types.* "%>
    <%@ page import = "com.sapportals.portal.prt.contentconversion.XSLConverter" %>
    <%@ page import = "com.sapportals.portal.prt.component.IPortalComponentRequest" %>
    <%@ page import="java.io.File" %>
    <%@ page import="javax.naming.Context" %>
    <%@ page import="javax.naming.InitialContext" %>
    <%@ page import="javax.naming.NamingException" %>
    <%@ page import="java.util.StringTokenizer"%>
    Can u help me on rectifying this class cast Exception ?
    Thanks and Regards,
    Saravanan

  • How to get an ArrayList Object in servlet from JSP?

    How to get an ArrayList Object in servlet from JSP?
    hi all
    please give the solution for this without using session and application...
    In test1.jsp file
    i am setting values for my setter methods using <jsp:usebean> <jsp:setproperty> tags as shown below.
    After that i am adding the usebean object to array list, then using request.setAttribute("arraylist object")
    ---------Code----------
    <jsp:useBean id="payment" class="com.common.PaymentHandler" scope="request" />
    <jsp:setProperty name="payment" property="strCreditCardNo" param="creditCardNumber" />
    <%-- <jsp:setProperty name="payment" property="iCsc" param="securityCode" /> --%>
    <jsp:setProperty name="payment" property="strDate" param="expirationDate" />
    <jsp:setProperty name="payment" property="strCardType" param="creditCardType" />
    <%--<jsp:setProperty name="payment" property="cDeactivate" param="deactivateBox" />
    <jsp:setProperty name="payment" property="fAmount" param="depositAmt" />
    <jsp:setProperty name="payment" property="fAmount" param="totalAmtDue" /> --%>
    <jsp:useBean id="lis" class="java.util.ArrayList" scope="request">
    <%
    lis.add(payment);
    %>
    </jsp:useBean>
    <%
    request.setAttribute("lis1",lis);
    %>
    -----------Code in JSP-----------------
    In testServlet.java
    i tried to get the arraylist object in servlet using request.getAttribute
    But I unable to get that arrayObject in servlet.....
    So if any one help me out in this, it will be very helpfull to me..
    Thanks in Advance
    Edward

    Hi,
    Im also facing the similar problen
    pls anybody help..
    thax in advance....
    Litty

  • Using multiple instance variables or BPM objects in a single JSP

    In my screenflow, for an user activity, I've selected a BPM object variable for my JSP and using this BPM object variable within the JSP to display or accept values related to this BPM object.
    But in certain circumstances, I need access to some of the instance variables defined in my screenflow (which are not members of the BPM object), and to get these variable values displayed in my JSP. I don't want to overload my BPM object with all these instances as they do not logically fit as members in this BPM object.
    For example, if I need to capture and display the logged in user name across the JSPs in my web application, then how can I do that without specifying this user variable in all of my BPM objects.
    Is there any extensibility in using more than one BPM object variables in my JSPs? Why is it that a single BPM object variable is tied to a JSP? Or am I missing something else here?

    I'm with the same problem!

  • Object Casting

    hi ,i have a question for .Base on this example below , i need to understand some casting basic .I understand how premitives values widening rules works but not on object casting rules.
    Question 1.
    Okay ,base on the example below why 'c=(Test) a' will always give compile error while "a=b" does not .Let takes this example , b already extends A and should have information of A class while A only have it own .I know i was thinking another way round.Can any one help.
    Question 2.
    How to make " c = (Test) a to run without any problem ,as long as a is assign to a is ok.
    Question 3.
    I have a statement from Khalid book page 202 and i don't understand .
    First statement:=Conversion which preserve the inheritance is a relationship are allowed ,other conversion      require an explicit case or are illegal.
    Fecond statement:=There is no notion of promotion for reference values.
    Question 4.
    What is the benefit of using casting and when we need to use it .Can give a short example.??
    class A {int Athing = 1;}
    class B extends A {int Bthing = 2;}
    class Test extends A
    { int Cthing = 3;
    public static void main(String args[])
    A a = new A();
    B b = new B();
    Test c = new Test();
    //c = (Test) a; //runtime error
    a = b;

    Ron, does your mommy know you're here? Shoudn't you be out riding your bike or doing homework or watching X Men or something instead of interrupting the grown-ups?
    Wikey: The answer to your question is that you can always (and implicitly) cast to a subclass because the subclass is always a member of the class, but you can't always even explicitly cast to the parent or higher class. To give a concrete example, all Toyota Camries are cars, but not all cars are Toyota Camries. There are things you can do with a Toyota Camry that you can't do with all cars. In your code, if you had coded A a = new Test();, you woudn't have a runtime error.
    Doug

  • Hi i just to want to know when we use object casting..

    sorry about this newbie question i ve already asked to my tutor but
    didn't get it...
    i just wonder what will happen if we cast object..
    i just can't imagin..coz im just bit slow on creative thinking...
    my currently writing code is like this..
    Integer nextCustID = new Integer("123456");
    Customer customer = new Customer(nextCustID, "Fred");
    customers.put("First", customer);
    customer = (Customer) customers.get("First");
    System.out.println(customer);i don't know about object casting...............................

    You don't cast objects. You just cast references - widening or narrowing their "scope" along the inheritance hierarchy.
    String s = new String("Hello");
    Object o = (Object) s; // Explicit cast not necessary, just for clarification
    String s = (String) o;While "hello" might appear as a String, then as an Object, then again as a String, it is always a String. Only the reference type to it changes.

  • Object passing to weblogic JSP tags

    Hello everyone
              I was wondering if I can pass a java object to a weblogic jsp tag
              for example if I select a content object with id "newsItem"
              <cm:selectbyid contenthome="com.beasys.commerce.axiom.document.Document"
              contentid="<%= contentId %>"
              id="newsItem" />
              can I pass newsItem as a variable to the next tag
              i.e. instead of writing it
              <cm:printdoc id="newsItem" />
              I write it
              <cm:printdoc Id="<%= newsItem %>" />
              This results in an compiler error if the object is passed to Id that is
              waiting for a content instance, while if it is passed to contentid (as in
              the first
              script) then it works fine, as this is waiting for a string.
              Is it possible to pass an object to the "id" in the jsp script, and if not,
              is there a work around it that enables the content selection logic to be
              seperated from the display.
              Thank you
              May
              

    Oh...i put quotes around the values and that fixed it.
              <%@ page language="java" session="false" %>
              Happy Holidays,
              Brian
              "Brian Williams" <[email protected]> wrote in message
              news:[email protected]..
              > Hello,
              >
              > I have a JSP that does something strange: When I look
              > at it under Explorer it looks fine but under Netscape
              > it has this at the top of the page:
              >
              > <%@ page language=java session=false %>
              >
              > Actually, with Explorer you can see it in the view
              > source. What's up with Weblogic? It seems that
              > it failed to parse this JSP tag.
              >
              > Thanks,
              > Brian
              >
              >
              >
              

  • Class Cast exception in JSP

    Hi All,
    Softwares used : UI--> JSP/Flex Grid/Dojo framwork
    Spring MVC
    Back end : EJB 3.0
    application Server : Jboss 4.2.2
    i have one Ajax call witch will update my flex grid after getting the data from Backend.
    i am able to get responce object but i am getting the class cast exception in the jsp.
    This ajax call used for upload the file.i have filter witch contains the wrap the request like
    (HttpServletRequest) Proxy.newProxyInstance(
                        (javax.servlet.http.HttpServletRequest.class).getClassLoader(),
                        getInterfacesForObject(request), new HttpServletRequestProxy(
                                  request, entries));
    exception given below
    19:54:04,372 ERROR [[ifx]] Servlet.service() for servlet ifx threw exception
    java.lang.ClassCastException: $Proxy333
         at org.apache.catalina.core.ApplicationDispatcher.unwrapRequest(ApplicationDispatcher.java:776)
         at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:382)
         at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:292)
         at org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:240)
         at org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:258)
         at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1174)
         at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:901)
         at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:809)
         at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:571)
         at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:511)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:810)
         at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
    Can you help me out for resolve this issue.
    Regards,
    Ritesh Kumar K.

    riteshkumar wrote:
    but we are using copying and pasting the application related lib's in the jboss\lib folder along with default jboss lib'sI am not sure if I understand you.
    any way i tried but it's not resolving my problem.No other causes comes to mind. Sorry, can't help you further. Good luck with solving.

  • Casting Classes in jsp

    [att1.html]
              

    Use byte array output stream to serialize into. Ask it for the byte array.
              You now have an object (the byte array) that contains the serialized form of
              the object that you serialized.
              Pick a name to store that byte[] under. I assume if you encountered a class
              cast exception that you already have a name picked. Store the byte[]
              instead of the original object. Put it in using setAttribute.
              Now where you take the object out with getAttribute, you have to instead
              instantiate a byte array input stream and an object input stream on top of
              that and bring that object back to life.
              I suggest encapsulating all of this so you can get rid of it if deploying to
              other servers or when WL fixes the class loading. It's only about 20 lines
              of code total.
              Cameron Purdy
              http://www.tangosol.com
              "Suchak Jani" <[email protected]> wrote in message
              news:[email protected]...
              Also there is one more thing i wanted to ask,
              How do we put the objects in the session after serializing them ?
              Thanks and Regards
              Suchak Jani
              Cameron Purdy wrote:
              It might imply that WL was trying to build the necessary .class files in one
              of its tmp directories; that is all that comes to mind. I am very glad that
              you were able to solve it though!
              Cameron Purdy
              http://www.tangosol.com
              "Suchak Jani" <[email protected]> wrote in message
              news:[email protected]...
              Hi Cameron,
              You are right in saying that the soultions are :-
              To avoid this problem, you can serialize the objects that you store (instead
              of the object themselves). You can also take the classes out of the
              WAR/servletclasses directory and add them to the base classpath (not
              advised, but can work). You can also use "built in" classes (like
              java.lang.whatever) instead of your own, since they are loaded by the system
              class loader. I'd suggest searching the JSP and Servlet newsgroups here for
              "class loader" and "classloader". You'll find plenty of problems and some
              solutions.
              I do not know and maybe i have not researched enough how to put the
              objects after serializing them in the session where i get the hashtable
              from.
              But just to tell you how we solved the dreaded classcast or at least how
              we think we solved it is the follows :-
              We had .java files also in the classpath with the .class files. We deleted
              the
              .java files and it worked ??
              Does that make ay sense to you ??
              Thanks and Regards
              Suchak Jani
              PS : Thank you so much for your timely help in this matter .
              Cameron Purdy
              http://www.tangosol.com
              "Suchak Jani" <[email protected]> wrote in message
              news:[email protected]...
              Why do java objects need to be casted ?
              Why do objects not know who they are ???
              I mean what the point of having collection classes
              like Vectors, Hashtables store everything as an Object. WHY ???
              I would be very happy to know the answer.
              Coming from a smalltalk background and knowing that collection
              classes are so important to devloping large applications in OO,
              it is difficult to see why every object must be casted.
              I was doing this casting to get objects from collection classes for last
              several months ,though not appreciating it very much.
              Today one of my JSP fails with a ClassCastException.
              The scenario is this :-
              I have an object stored in a HashTable , let us call this "X".
              In the JSP i am getting the object from the hashtable and
              casting it like this :-
              X y = (X) hashtable.get(key);
              I get a ClassCastException.
              Now if i do like this: -
              System.out.println("Object :" +hashtable.get(key) )
              X y = (X) hashtable.get(key);
              It gives me this:-
              Object : X@234e
              ClassCastException
              Now , i am at a complete loss to understand why ??
              I would great appreciate if anyone has any answers.
              Thnaks and Regards
              Suchak Jani
              

  • How can I use the same object in the different jsp files?

    I am doing a project. I have finished my jave source files and compiled them successfully. And I also wrote a main method to test my classes, they also worked well. Now I am trying to use my jave code in the jsp files. But I meet a problem, in my method of java source file, I can generate a object of a class, and use it in the whole main method. But in the different jsp files, how can I do same thing?
    For example, in the .java file,
    Vector vl = new Vector();
    While ...{
    vl.add(...)
    In each of my .jsp file I want to do one loop of the above, meanwhile I want to do that in the same object.
    I hope you can understand what I mean. Really need your help!

    put your object into a session and you can the use it in all the jsps as long as the session is valid. Or you could create a static variable in the class that only creates one instance off an object and then create a static method to return this object.

  • Object casting: confusion in ABAP Objects: Complete Reference book

    Hi,
    During Object Assignments using casting, is a Type Test carried out during the syntax check or at runtime?
    A.5.2.2 (page 1008) of 'ABAP Objects: The Complete Reference' says about Widening Cast: "...you must check at runtime...". However on the next page under A.5.3.2 it says of Widening Cast in Data References: "The syntax check precludes...".
    A.5.4 (page 1010) concerns Assignments between Object Reference Variables, but makes no mention of whether checks are carried out by a syntax check or at runtime.
    Also nowhere does it mention when Type Tests for Narrow casting takes place. Can anyone clear my confusion please? Unfortunatly I don't know enough about this stuff to test by writing some code.
    Thanks.

    William,
    Your questions can be answered by the following rule for object references, which I found in the book "ABAP Objects" by Horst Keller and Sascha Krüger:
    "... that the static type of the target variable must be equal to or more general than the dynamic type of the source variable."
    Here "static type" means the type with which an object reference variable is declared. "Dynamic type" is the type that the object reference variable has at runtime. The dynamic type of an object reference is always more special than its static type, otherwise a runtime error occurs.
    With this rule all your questions can be answered:
    1. The Narrowing Cast is always checked during the syntax check. Example:
    DATA o_ref1 TYPE REF TO object.
    DATA o_ref2 TYPE REF TO class_1.
    o_ref1 = o_ref2.  
    Here the reference o_ref2 has a dynamic type "class_1" or a subclass of it, which is narrower than its static type "class_1", which is narrower than the static type "object" of the reference o_ref1. Therefore, the syntax check says that the assignment is OK.
    2. The Widening Cast is always checked at runtime and requires an assignment using the operator ?=. If you use the operator = in the assignment, a syntax error occurs. Therefore the following  example produces a syntax error (try it yourself):
    DATA o_ref1 TYPE REF TO object.
    DATA o_ref2 TYPE REF TO class_1.
    o_ref2 = o_ref1.  
    The correction for this syntax error is:
    DATA o_ref1 TYPE REF TO object.
    DATA o_ref2 TYPE REF TO class_1.
    o_ref2 ?= o_ref1.
    Now the syntax check is satified, and the correctness of the widening cast is checked at runtime.
    Kind regards,
    Michael Kraemer
    Message was edited by: Michael Kraemer

  • How to putput a property of an object in session? (jsp/struts)

    Guys,
    I have an object (myGroup) that consist of 2 properties: groupName and groupTitle. The object is in a session called group_session.
    On my jsp page, I would like to output the property groupName on the text field associated with the groupName:
                   <html:text      property="name"
                                                   value=???????????????
                                  size="45"
                                  maxlength="60" />
                                  <html:errors property="name" />Q: how can I output the value of the groupName in the value section?
    thanks

    Hi
    you can try something like this....
    <input type="text" name="any" property="<bean:write
    name="myGroup" property="groupName "
    scope="session"/> " >
    This snippet is closer to JSP coding rather than struts. Leverage the capabilities of struts by setting the values in ActionServlet instead.
    <html:text property="name" size="45"  maxlength="60" />                    -Rohit
    By the way why did you add this tag
    <html:errors property="name" /> ??
    Message was edited by:
    RohitKumar

  • Class cast exception in jsp plz help

    i have written a jsp where i displayed a text box with value given by user inside it
    when the user enters some other value in text box and clicks on update button then i forwarded reqeust to servlet which will some data base work
    servlet will forward again to the same jsp with the new value in text box.
    but i am getting CLASS CAST EXCEPTION when servlet is forwarding reqeust to same JSP
    help me what to do ........
    thanking you in advance ..cheers

    display cart.jsp file:
    <%@ page import="java.util.*,org.*" %>
    <html>
    <body>
    <%
    Vector cartupdate = (Vector)session.getAttribute("cartlist");
    for (int i = 0; i < cartupdate.size(); i++) {
    CartListBean clb = (CartListBean)cartupdate.elementAt(i);
    %>
    <form name="itemslist<%=i%>" action="updateCart" method="post">
    <input type="hidden" name="itemcode" value="<%=clb.getItemCode()%>">
         <input type="hidden" name="itemname" value="<%= clb.getItemName()%>">
    <input type="hidden" name="price" value="<%= clb.getPrice()%>">
    <%= clb.getItemName() %>
    <input type="text" name="qty" value="<%=clb.getQuantity()%>">
    <input type="submit" name="<%=clb.getItemCode()%>" value="update">
    </form>
    <br>
    <%
    %>
    <form name="tobuy" action="buysrv" method="post">
    <input type="submit" name="buy" value="BUY">
    </form>
    </body>
    </html>
    updatecart servlet code:
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.io.*;
    import org.*;
    import java.sql.*;
    import java.util.*;
    public class UpdateCart extends HttpServlet
    public void service(HttpServletRequest request,HttpServletResponse response) throws IOException,ServletException
    HttpSession session=request.getSession(false);
    Vector cartupdate = (Vector)session.getAttribute("cartlist");
    for (int i = 0; i < cartupdate.size(); i++) {
    org.CartListBean cart = (org.CartListBean)cartupdate.elementAt(i);
    if((cart.getItemCode()).equals(request.getParameter("itemcode")))
    org.CartListBean clb=new org.CartListBean();
    clb.setItemCode(request.getParameter("itemcode"));
         clb.setQuantity(request.getParameter("qty"));
         clb.setItemName(request.getParameter("itemname"));
    clb.setPrice(request.getParameter("price"));
    cartupdate.setElementAt(clb,i);
    session.setAttribute("cartlist",cart);
    ServletContext application=getServletContext();
    System.out.println("got finished");
              RequestDispatcher rd=application.getRequestDispatcher("/displaycart.jsp");
                   rd.forward(request,response);
    Message was edited by:
    143java

  • How to call the BPM objects in the child JSP?

    Hi,
    We are facing some problem, we are trying to use the JSP for the UI instead of BPM Presentation.
    In the JSP we are calling the child JSP(using JSP include), we need to pass the BPM objects from child to parent JSP.
    Can any one help me on how to pass the Object between the JSP's and BPM Obejcts.
    I will explain in the Example too,
    1. We are created the BPM objects with fields
    2. Created 2 JSP's 1. Main.JSP 2. Sub.JSP
    Now we need to call the sub.jsp into main.jsp,while we calling we need to pass the sub.jsp BPM Object.
    Regards,
    Anandh P

    Hi
    When you use <% include page="test.jsp" %> you can use the same object's name in child jsp like in parent file (this is static way to include another file).
    Hope this could solve the problem. regards.

  • Oracle BPM 10.3: Pass Object from Presentation to JSP

    Hi,
    I am using Oracle BPM 10.3 . Can anybody tell me that in the presentation when a user clicks a button
    then i call a method. This method have an object. How i can pass this object to a JSP Page so that
    jsp can access this object.
    Thanks
    Edited by: user9293762 on Sep 3, 2010 2:33 AM

    Hi user9293762,
    To pass the BPM object to the JSP page, please follow the below steps:
    1) Place an interactive activity after the method execution.
    2) Right click on the Interactive activity and select Main Task
    3) In the Main Task wizard select Implementation Type as BPM Object Interactive Call
    4) Select the BPM Object Variable, here you can pass your BPM object to the jsp page but make sure that the object you want to pass is an instance variable of type your BPM object
    5) Click on the Use JSP Presentation and choose for your jsp page you want to attach with the interactive activity.
    6) Finally click on OK
    Now you can access the BPM object in your jsp page.
    Bibhu

Maybe you are looking for

  • Print from mobile phone

    How can i print from my smart phone.  App already installed and computer is on

  • Null pointer exception in the morning

    Hi all, I have built a custom JSP DYN page application that for the most part works ok. However, I've found on occassion that when I arrive in the morning, the application errors out in our dev and qa portal environments with a null pointer exception

  • ICal Server Invitations

    I'm thinking of adding the iCal service to an OS-X server I presently have running. I've set up the service and started prototyping and noticed that when an invitation is sent to someone outside the realm of users the server is aware of (like a Yahoo

  • I cannot get bb attachment services back

    I cannot get bb attachment services back.  It is missing from apploader.  I think this is what I took off by mistake and it remove my external display.  Please help.  I have tried multiple suggestions to set to factory, but none worked for my BB Pear

  • Variance for a invoice document

    Hi Experts, How to get the variance details of a parked invoice document? Is there any function module to do the same? Thanks, Navya