wood burning stoves 2.0*
The moose likes Servlets and the fly likes Reading an ArrayList from JSP to Servlet Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Servlets
Bookmark "Reading an ArrayList from JSP to Servlet" Watch "Reading an ArrayList from JSP to Servlet" New topic
Author

Reading an ArrayList from JSP to Servlet

vjy chin
Ranch Hand

Joined: Feb 17, 2005
Posts: 279
Hi,
I have an object (ArrayList) in my JSP page and I need the ArrayList to be sent to a servlet. I have tried request.getAttribute in the servlet after I use request.setAttribute in my jsp.

Also I dont want to use session. What are the ways it can be done?

Thanks

Also, I apologize if I posted this qus. in wrong forum.
[ April 27, 2005: Message edited by: vjy chin ]
ramprasad madathil
Ranch Hand

Joined: Jan 24, 2005
Posts: 489


I have an object (ArrayList) in my JSP page and I need the ArrayList to be sent to a servlet.


1. Request attribute provided the jsp and the servlet are part of the same request flow. You have said that you tried this. What happened, dint work ? Whats the error you get ?

2. Session Attribute

3. Application attribute (the ServletContext object)

4. You could serialize the object from the jsp and deserialize and read it back in the servlet. (not recommended)

ram.
Ben Souther
Sheriff

Joined: Dec 11, 2004
Posts: 13410

First, I could have sworn this exact question was asked not too long ago.

Back to the point:
I have an object (ArrayList) in my JSP page and I need the ArrayList to be sent to a servlet.
What that is really saying is "I want to pass an array list from the browser to the server" which can't be done.
A browser passes a string of text to the server which get's parsed into a series of name/value pairs.
If you bind an object to request scope in a JSP, it dissapears as soon as that request is over (right away).
Then, when the user submits the form that you've just built a new request object is created.

What is your reason for not wanting to use sessions?


Java API J2EE API Servlet Spec JSP Spec How to ask a question... Simple Servlet Examples jsonf
ramprasad madathil
Ranch Hand

Joined: Jan 24, 2005
Posts: 489


What that is really saying is "I want to pass an array list from the browser to the server" which can't be done.


Really! Why, there's nothing in the original post which says that
But then, I guess you were privy to some other info (or thread where the OP had posted a similar question) that I wasnt

ram.
Adeel Ansari
Ranch Hand

Joined: Aug 15, 2004
Posts: 2874

What that is really saying is "I want to pass an array list from the browser to the server" which can't be done.


Cent percent agreement.
[ April 28, 2005: Message edited by: Adeel Ansari ]
Adeel Ansari
Ranch Hand

Joined: Aug 15, 2004
Posts: 2874
Originally posted by ramprasad madathil:
Really! Why, there's nothing in the original post which says that
But then, I guess you were privy to some other info (or thread where the OP had posted a similar question) that I wasnt


No. It was not by mistake. Ben's post really belongs to the same thread. Just apply a little of common sense, and then you will know.

Thanks.
vjy chin
Ranch Hand

Joined: Feb 17, 2005
Posts: 279
Guys,
Thanks for the reply.
I was told not to use sessions by my Senior and I don't know the reason and if I use session it works a charm.

But when I used request.setAttribute from the jsp and submit the page, i get a null value in the servlet.
But when I use the same thing and forward the jsp page to the servlet using <jsp:forward page="/ctrl?do=TEST"/> it works, I am able to get the values.

But I feel as Ben said the scope would be over.

Also please let me know which would be the way I should use.

Thanks again
ramprasad madathil
Ranch Hand

Joined: Jan 24, 2005
Posts: 489


Originally posted by Adeel.
Just apply a little of common sense, and then you will know.


That was uncalled for.
The OP was that an object need to be passed from a jsp to a Servlet.
To imagine that the post meant that the jsp (which contained the array list object) sent a response to the browser and to think that the OP thought that the object would be sent back to the Servlet from the browser requires more than common sense.
Probably Ben and you know enough to deduce as much from the post, but that's more due to experience and knowledge and less attributable to common sense.

ram.
Adeel Ansari
Ranch Hand

Joined: Aug 15, 2004
Posts: 2874
Originally posted by ramprasad madathil:
Probably Ben and you know enough to deduce as much from the post, but that's more due to experience and knowledge and less attributable to common sense.


Its Ok. May be I took your words wrong.
Actually I really got a negative impression from your previous post.

Thanks.
ramprasad madathil
Ranch Hand

Joined: Jan 24, 2005
Posts: 489


Originally posted by Adeel
Its Ok. May be I took your words wrong.


Ok by me too. I dint mean to sound rude in my original post, that was not my intention. Apologies if it came out that way.

Cheers,
Ram
Ben Souther
Sheriff

Joined: Dec 11, 2004
Posts: 13410

Really! Why, there's nothing in the original post which says that
But then, I guess you were privy to some other info (or thread where the OP had posted a similar question) that I wasnt


The flow for a request, in an app that uses a combination of servlets and JSPs, generally looks something like this:

1.) Browser makes a request to server (this is handled by a servlet).
2.) Servlet does some processing (often using beans).
3.) Servlet, using a requestDispatcher, passes the control flow to a JSP.
4.) JSP does some formatting using HTML, EL, and/or custom tags or scriptlets. The JSP still has access to the original request object and can use objects bound to it in the servlet.
5.) JSP sends it's output back to the browser.
6.) Request is Done.

At this point the user sees something on their screen and may or may not initiate another request.

This is the typical pattern employed in J2EE web apps.
If you are using a different pattern that involves sending the control flow back to a servlet from a JSP, without a trip to the browser, then I am mistaken and it would be reasonable for you to expect to be able to bind an object to the session and retrieve it in the servlet.

vjy,
Please, explain the nature of your problem in a little more detail and, perhaps, we can help.
[ April 28, 2005: Message edited by: Ben Souther ]
ramprasad madathil
Ranch Hand

Joined: Jan 24, 2005
Posts: 489


This is the typical pattern employed in J2EE web apps.


I realize that.
But I have seen lots of post on this and other forums where people trying to learn the concepts, tried to do it the other way (either due to academic interest or plain curiosity) and have asked similar questions.
Again, I apologize if my comments that were quoted by both Ben and Adeel caused offence. As I said earlier, that wasnt my intention.

ram.
David Harkness
Ranch Hand

Joined: Aug 07, 2003
Posts: 1646
It's interesting how assumptions affect us so much. With my background (familiar enough with JSPs only to modify existing ones as I've been sheltered by web frameworks), I assumed that since vjy wanted to pass an object from a JSP to a servlet and had tried request.setAttribute, clearly s/he was forwarding the request on to the servlet (server-side redirect, no browser involved).

Ram, from your posts I suspect you assumed the same thing.

Ben and Adeel, from yours it looks like you made the assumption that the JSP was returning control to the browser. That seems logical since if the JSP wasn't going to send the response to the browser, a servlet would make more sense (or not, here's where my experience may fall short).

In any case, in an attempt to salvage some value from this post I'll point out that similar to how our technical assumptions inform our suggested solutions, so to our cultural assumptions affect what we infer about a person's intent from their words. I've found that I'm a happier person by employing the default assumption that people mean well and are genuinely trying to help.

Being wrong on that assumption only costs me an opportunity to make a witty sarcastic quip, which really is no great loss. Assuming the opposite and being wrong can have a higher social cost. Thus, I go with the former and practice my wit elsewhere.

Wow, um, okay...

mode.get("soapbox").terminate();
Ben Souther
Sheriff

Joined: Dec 11, 2004
Posts: 13410

ramprasad madathil,

The number One, biggest obstacle that beginning Servlet/JSP programmers run into is a failure to grasp what code gets executed on the server, what gets sent back to the browser, and what code gets interpreted within the browser.

That misconception usually leads to questions just like this. Again, I may have misread the question and made my assumptions too soon but it looks, from the original poster's response that I was right (it also looks like he suspected as much and has had his suspicion confirmed).

I've seen Mr, Ansari try to help people grasp this concept dozens of time as well. I'm certain that his intent was not to belittle or insult either the original poster or yourself.
David Harkness
Ranch Hand

Joined: Aug 07, 2003
Posts: 1646
Originally posted by vjy chin:
But when I used request.setAttribute from the jsp and submit the page, i get a null value in the servlet.
As Ben said and you found, request attributes are cleared at the end of the request, and letting the JSP complete the response to the browser ends the request.
But when I use the same thing and forward the jsp page to the servlet using <jsp:forward page="/ctrl?do=TEST"/> it works, I am able to get the values.
I assume this method uses RequestDispatcher to forward the request to the servlet (server-side redirect). If so, the JSP and servlet processing both occur in the same request. Thus, the attribute makes it.
Also please let me know which would be the way I should use.
I think the critical factor is whether or not server-side redirect will satisfy the other requirements of your application.
  • Does the user need to see the JSP's output and actively submit a new request to the servlet?
  • Do you need to control the URL displayed in the browser (show servlet's URL vs. JSP's URL), necessitating client-side redirect?
  • Those are the only two reason I can think of immediately that would require using two separate requests. If either of those hold, you'll need to store the ArrayList somewhere other than the request attribute map. In addition to the methods Ram proposed, you could encode it into a hidden form field or a cookie.

    On the other hand, if you don't have either of the two above requirements, using server-side redirect seems like the best choice.
    Ben Souther
    Sheriff

    Joined: Dec 11, 2004
    Posts: 13410

    Originally posted by David Harkness:
    Ben and Adeel, from yours it looks like you made the assumption that the JSP was returning control to the browser. That seems logical since if the JSP wasn't going to send the response to the browser, a servlet would make more sense (or not, here's where my experience may fall short).


    Yes, it would be extremely rare, for the JSP to be anywhere but at the end of the processing chain in an app where both servlets and JSPs are concerned.
    It is, however, extremely common for people who are just starting out to be a little confused about how the request/response cycle works in an environment where the server side code exists, intermingled with (and is made to look almost identical to) the client side code in the same file.

    That said, people such as Mr. Ansari and myself, who spend a lot of time on this and the JSP forum are probably conditioned (maybe over conditioned) to jump to this conclusion.

    Bear with us.
    Adeel Ansari
    Ranch Hand

    Joined: Aug 15, 2004
    Posts: 2874
    Originally posted by vjy chin:
    But when I used request.setAttribute from the jsp and submit the page, i get a null value in the servlet.


    This statement automatically leads us to assume the same. No matter if it appeared after our assumption.

    One more reason for that assumption is, we usually take MVC automatically.
    [ April 28, 2005: Message edited by: Adeel Ansari ]
    ramprasad madathil
    Ranch Hand

    Joined: Jan 24, 2005
    Posts: 489

    David, that was a lovely post on 'assumptions' , thank you.

    Ben, I agree with what you said about the original poster's confusion and what he actually meant.

    Probably I too, suspected as much and probably I was not brave enough to call it. However you were and Iam sure it takes a lot of experience and knowledge (as I remarked to Adeel) to do that.

    Infact it was precisely this that I was amazed at - knowing enough to understand that the question was perhaps not rightly framed, to guess correctly what the original poster meant and answer to that - and i meant my first post (that was repeatedly quoted) to convey this awe and respect , it turned up conveying the contrary (Adeel said it conveyed a negative impression ). Not my day I think .

    Cheers,
    Ram.
    David Harkness
    Ranch Hand

    Joined: Aug 07, 2003
    Posts: 1646
    Sweet. It seems we're all on the same page and understand each other.

    All we need now is for vjy to chime in with a little more details and we might be able to help.
    Adeel Ansari
    Ranch Hand

    Joined: Aug 15, 2004
    Posts: 2874
    Originally posted by ramprasad madathil:
    i meant my first post (that was repeatedly quoted) to convey this awe and respect , it turned up conveying the contrary (Adeel said it conveyed a negative impression ). Not my day I think .


    Forget all that mate. It all up after David's post on assumptions.
    Now cheers
    ramprasad madathil
    Ranch Hand

    Joined: Jan 24, 2005
    Posts: 489



    Cheers,
    ram.
    Ben Souther
    Sheriff

    Joined: Dec 11, 2004
    Posts: 13410

    First one to suggest a "group hug" gets shot.
    This IS a saloon.
    David Harkness
    Ranch Hand

    Joined: Aug 07, 2003
    Posts: 1646
    You know what I love best about working as part of a good team?

    ...

    wait for it

    ...

    Group bugs!

    Ben Souther
    Sheriff

    Joined: Dec 11, 2004
    Posts: 13410

    Dude....



    That was really bad.
    Bear Bibeault
    Author and ninkuma
    Marshal

    Joined: Jan 10, 2002
    Posts: 60741
        
      65

    Bear with us


    Yeah, I'm here. <ducks>


    [Asking smart questions] [Bear's FrontMan] [About Bear] [Books by Bear]
    Ben Souther
    Sheriff

    Joined: Dec 11, 2004
    Posts: 13410

    That's it... Where's my six shooter?
    vjy chin
    Ranch Hand

    Joined: Feb 17, 2005
    Posts: 279
    Hey guys,
    that was a really good and entertaining discussion.

    I am describing my application.

    I am having a login.jsp. After I enter my login details the control passes to the servlet, it picks up all the user information and sends an arraylist as a return object. Using that arraylist I am displaying the response page(CustomerDetails.jsp). There the user has some more options to add apart from the displayed ones. So I must take all the new details which the user entered to save it in the database. So I need the original arraylist, since I will be again saving them in a different table. So instead of using a database connection we are using the same arraylist which I got from the response of the login page. Thats the reason I need to get the arraylist in the servlet which passes the request object to the next action class.

    Hope I made things clear.

    Also being a newbie, it would be really great if anyone can point me to pages where its mentioned about which code being executed where. As Ben said

    The number One, biggest obstacle that beginning Servlet/JSP programmers run into is a failure to grasp what code gets executed on the server, what gets sent back to the browser, and what code gets interpreted within the browser.


    it will be great if anyone can point me to right place. Thanks once again for all the help
    Adeel Ansari
    Ranch Hand

    Joined: Aug 15, 2004
    Posts: 2874
    As Servlet and JSP are the serverside technologies, all JSPs and servlets get executed on server.

    If you dont want to use session you can go for hidden fields and use request.getParameter() in your servlet to get the values.
    vjy chin
    Ranch Hand

    Joined: Feb 17, 2005
    Posts: 279
    Does request.getParameter work for arraylist or other objects. I know it works for Strings and I also read somewhere that the return type of request.getParameter is String. If its the case how can I get the arrayList.

    Am I wrong or missing something.
    Thanks
    Adeel Ansari
    Ranch Hand

    Joined: Aug 15, 2004
    Posts: 2874
    Originally posted by vjy chin:
    Does request.getParameter work for arraylist or other objects. I know it works for Strings and I also read somewhere that the return type of request.getParameter is String. If its the case how can I get the arrayList.

    Am I wrong or missing something.


    Vjy, No it doesn't work with arraylist, but it works with hidden fields.

    Why you are not using session? Just inform your senior it cant be done without using session.
    [ April 29, 2005: Message edited by: Adeel Ansari ]
    Ben Souther
    Sheriff

    Joined: Dec 11, 2004
    Posts: 13410

    Originally posted by vjy chin:
    Does request.getParameter work for arraylist or other objects. I know it works for Strings and I also read somewhere that the return type of request.getParameter is String. If its the case how can I get the arrayList.

    Am I wrong or missing something.
    Thanks


    The getParameter method only returns strings.
    This is because a browser can only send text to the server.
    In order to get an ArrayList from getParameter, you would need to, somehow, ship the arrayList off of the server and down to the user's browser. The browser would then need to ship the array list back to the server in the user's next request.

    If there is a small amount of data in the arrayList, you could do what Adeel suggested and ship it down to the browser as hidden input fields.








    The build a new list using request.getParameterValues("list_values") which returns a String[].
    This, of course, won't be very effcient if you have dozens or hundreds of entries in the list.

    You could also use the same logic that built the arrayList in the first place but that might not be very efficient either.

    If you want to keep the original arrayList alive, in memory, on the server, you could bind it to the servletContext with some kind of unique string as the key and then retrieve it in subsequent requests. Of course, then what you are doing is implementing your own form of session handling which is absurd when the container already provides a perfectly good session handling implementation for you.

    I would press your management for a good explanation as to why they don't want you using sessions. There are valid reasons but often it's just because someone read somewhere that they're 'bad' and decided to ban them.


    Also, the wording of this question hints that you still don't have a full grasp on the request/response model that is used in web programming.
    I would recommend that you do two things while your coding your Servlets/JSPs

    1.) Look at the HTML source for every page you write. Do this from the browser's view -> view source menu items. This source is what your server side code is generating -- it's 'output'.

    2.) Get Firefox and install the LiveHttpHeaders plugin.
    With it you can see how a browser sends form data to a server.
    Here is a typical POST request:


    The last line shows how the name/value pairs of the form are encoded.

    Without sessions, you either have to recreate the arraylist from scratch with each request, or, you need to pass all of it's contents down to the browser as hidden form fields, then read all of the values when the user submits the next request and re-create the list from those values.

    [ April 29, 2005: Message edited by: Ben Souther ]
    [ April 29, 2005: Message edited by: Ben Souther ]
    vjy chin
    Ranch Hand

    Joined: Feb 17, 2005
    Posts: 279
    I will try to convince my senior about sessions, since he told that session can only hold 8000 bytes, thats the reason I posted a question regarding the topic some days ago. But even after seeing the answers, hes still not accepting. May be next week I am going to try using a profiler and show the results to him.

    Thanks for your detailed answer Ben, I will try that in the weekend.
    Ben Souther
    Sheriff

    Joined: Dec 11, 2004
    Posts: 13410

    A session is a map that holds references to objects living on the heap.
    It is not a container with a finite capacity.

    How much you can hold in session depends on the overall resources available to the JVM and the number of sessions that will exist simultaneously.
    Neeraj Dheer
    Ranch Hand

    Joined: Mar 30, 2005
    Posts: 225
    Wow! what a thread! But we do finally have some technology in here!!

    As has been said earlier, Transforming the ArrayList into a String and sending it across and then re-shipping it is not the most efficient way of doing it. more traffic over the network plus the additional time required(no matter how little) to do the transformations.

    isnt this the root reason for sessions to have been 'invented' though?

    is it true that a session can only hold 8k of data? i knew bout limitations on cookies, but on sessions as well?? i always thought that the only memory limitation on sessions was the total memory available.

    and if this is true, when one says a session can hold 8k of data, my interpretation(or assumption??) is this :

    if i store the ArrayList in the session, what actually gets stored in the session is the key by which it is stored and the name of the ArrayList, which in effect is only the reference to the actual object while the actual object is not stored 'in' the session so to say.

    am i wrong in that interpretation?
    David Harkness
    Ranch Hand

    Joined: Aug 07, 2003
    Posts: 1646
    Note that the session is nothing magical; it's merely a Map. The session no more "contains" objects "put into" it than an ArrayList "contains" the objects put into it. Instead, it holds references to the keys and values, just like all other Collection classes.

    The only way the container could enforce some arbitrary limit on the size of all objects reachable by the session would be to serialize the entire graph to a byte array. Of course, this won't match the actual memory on the heap taken up by those objects, but it would be "close enough."

    Not only would it be a major performance drain to serialize the entire session on every setAttribute() call, but it wouldn't notice changes made to objects already in the session. You could call setAttribute() after modifying any attribute already in the session, but that's hardly enforceable by the container.

    The end result is that it would be flawed at best and quite pointless. The container is already limited by the memory available to the JVM, and it can be used more efficiently if you allow some sessions to be big and others to be small.

    Bah, that was a long-winded way to say "sessions don't have a maximum size."

    In any case, vjy, to ease your senior's mind, make sure to remove the ArrayList from the session in the servlet that needs it, assuming it's only needed by that one servlet. How big is the ArrayList anyway? If you're talking about a few kilobytes, your senior is stressing over minute details. Just think about all the temporary objects that are created in handling a single request. The ArrayList is peanuts to all that churn!
    Neeraj Dheer
    Ranch Hand

    Joined: Mar 30, 2005
    Posts: 225
    Thanks for that David!

    So, i can still call myself a budding programmer with Java. what you said was what my understanding was. that limit on the session had thrown me off totally
    [ April 29, 2005: Message edited by: Neeraj Dheer ]
    vjy chin
    Ranch Hand

    Joined: Feb 17, 2005
    Posts: 279
    Yes David,

    Thanks for the detailed answer. The arraylist is just needed in one and only servlet and it contains 3 objects in it. But they are not really larage or something. My senior for some reason hates sessions, he thinks it may be hijacked. I would say that even if its hijacked it doesnt contain anything useful for the hackers. it just contains some details, not even names or address kind of stuff.

    Anyway thanks once again for all
    Ben Souther
    Sheriff

    Joined: Dec 11, 2004
    Posts: 13410

    Life is always interesting when people who don't understand the technology (and don't seem to want to learn it) are the ones dictating how it will be used.

    Good-Luck
    vjy chin
    Ranch Hand

    Joined: Feb 17, 2005
    Posts: 279
    I totally agree with you, but the reason those people give is they lost their coding knowledge, hence the mishaps. But really some bascis should be there in everyone, isn't it?

    But world is a funny place and funny things can happen.

    Anyway thanks for all the replies
     
    I agree. Here's the link: http://aspose.com/file-tools
     
    subject: Reading an ArrayList from JSP to Servlet
     
    Similar Threads
    Unable to pass request objects from one page to another
    Using attributes
    I can't use application and session to store data
    ArrayList in JSP
    Passing an arrayList of JavaBean Object as hidden variables