0

I was wondering if it is possible to send a string array from jsp to servlet class. Actually this situation is that I'm sending an string array from servlet to jsp, then I want to send this string array to another servlet class. For instance,

   <table border="1">
     <tr>
        <th>Target Names</th>
    </tr>
        <c:forEach items="${targetarray}" var="drugtarget">
        <tr>
        <td>${fn:escapeXml(drugtarget)}</td>
        </tr>
        </c:forEach>
</table>

Here , targetarray is my string array. I need to send it to another servlet class now. Or is there another method to do that? Thank you.

ch4nd4n
  • 4,110
  • 2
  • 21
  • 43
Ahmet Tanakol
  • 849
  • 2
  • 20
  • 40
  • 1
    I think you got your basics wrong, JSP is evaluated on server side. This kind of question has been asked several times and possible duplicate of http://stackoverflow.com/questions/4253660/passing-object-from-jsp-to-servlet – ch4nd4n Nov 23 '12 at 10:58
  • Actually, I was planning to send the data by using hidden input, I just wondered if there is another way but ok. Thanks – Ahmet Tanakol Nov 23 '12 at 11:09
  • 1
    @AhmetTanakol yes there are other ways. ever heard of session.setAttribute() and session.getAttribute()? also there are same functions in request objects – Bhavik Shah Nov 23 '12 at 11:12
  • 1
    You may want to update your question by rephrasing your requirement. IMO, right now it looks as if you want to pass Java Object from JSP to Servlet. – ch4nd4n Nov 23 '12 at 11:13

1 Answers1

1

HTML can only contain character sequences. HTTP request parameters can only represent character sequences. You definitely can't pass around Java objects around. You'd need to convert them to a character sequence which uniquely represents the Java object first based on a specified format, so that it can be converted back to the Java object after retrieving it back in the server side. Character sequences are in Java represented by the String class.

So, basically, you need to convert String[] to String before printing it in HTML. You can use the HTML <input type="hidden"> to represent a hidden request parameter. You need to convert the submitted String value back to String[] after obtaining it as HTTP request parameter. At its simplest you can choose the comma separated values (CSV) format as String representation, or maybe XML or JSON.

A completely different alternative, for sure if the Java object is rather complex (e.g. a Javabean, possibly with more nested Javabean properties, etc) is to store the object along an unique and autogenerated key (e.g. by java.util.UUID) in the session. Then you just have to pass exactly that unique key around as request parameter so that it can afterwards be obtained (removed) from the session based on the key.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555