Ninu
Ninu

Reputation: 35

send list data from jsp to servlet

I have a List and I want to pass it to the subsequent request as GET query string parameter:

<a href="servlet?list=<%=request.getAttribute("list")%>">link</a>

Inside the servlet I am trying to retrieve it as follows:

String[] list = req.getParameterValues("list");

It does not work. How can I get it to work?

Upvotes: 0

Views: 7913

Answers (2)

BalusC
BalusC

Reputation: 1108722

In order to be able to use getParameterValues(), multiple parameters has to be sent in the format:

list=item1&list=item2&list=item3

But the List#toString() prints the following format (rightclick page in browser and choose View Source to see it):

list=[item1,item2,item3]

This is obviously not going to work. There are several ways to solve this problem:

  1. As Bozho said, print it commaseparated (or keep it unchanged) and use request.getParameter() instead and split the string and repopulate the list using the usual String methods like split(), substring(), indexOf(), etc.

  2. Just print it in the expected format. Nicest would be to create an EL function for that.

  3. Store it in the session:

     request.getSession().setAttribute("list", list);
    

    so that you can just retrieve it from the same session in the next request:

     List list = (List) request.getSession().getAttribute("list");
    

    If necessary, you can pass the key as request parameter instead.

  4. If you already have the list in the server side (application scope, database, etc), then just don't pass the list around. Pass only those parameters around which gives enough information to reload/repopulate the list in the servlet. The query string has a limitation in maximum length which should preferably not exceed 255 ASCII characters. If the list contains over some hundred of items, you risk that they will be truncated anyway.

Upvotes: 2

Bozho
Bozho

Reputation: 597096

the list attribute is a List, and you should not rely on its toString(), which is called in your code (behind the scene).

Instead, you have to iterate the list and insert commas between the elements.

Upvotes: 1

Related Questions