Search code examples
arraysjspservletsjstljsp-tags

Using JSTL tag in JSP to print array values from servlet


I am having problem printing(Displaying) array data from JSP page which is send from Servlet. Here are the code and the out of the JSP page. Kindly, help me to trace the error i am making.

MY SERVLET CODE:

//inside doGET method
String title="Reading cookies example";
String[] info={"What the hell!!","Nothing"};

request.setAttribute("title", title);
request.setAttribute("name", info);

RequestDispatcher rd=request.getRequestDispatcher("myjsp.jsp");
rd.forward(request, response);

MY JSP CODE:

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%-- 
    Document   : myjsp
    Created on : Apr 5, 2014, 1:19:35 PM
    Author     : sabin
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <c:forEach var="pagetitle" items="title">
            <h1>${title}</h1>
        </c:forEach>
        <c:forEach var="data" items="{name}" >
            <C:OUT value="${data}">  </C:OUT> 
            <h1>${name}</h1>

        </c:forEach>


   </body>
</html>

OUTPUT PAGE:

Reading cookies example [Ljava.lang.String;@195019d

Instead of printing "What the hell" and Nothing its printing [Ljava.lang.String;@195019d. What is the reason and what i am missing? Would be very thankful if someone could assist me with this problem. Thanking you in Advance.


Solution

  • try this ,

        ${title}
        <c:forEach var="temp" items="${name}">
            <c:out value="${temp}"></c:out>
        </c:forEach>
    

    Because title is not an array its just a string also read this to understand the functionality of for-each tag will print output like this ,

    Reading cookies example What the hell!! Nothing