Xi Chen
Xi Chen

Reputation: 101

How could i print after i used request.getAttribute in a jsp?

In my servlet, i have:

List list = new ArrayList();
....
request.getSession().setAttribute("list",list);
        RequestDispatcher dispatcher=request.getRequestDispatcher("result.jsp");
        dispatcher.forward(request,response);

And in my result.jsp file, i wanted to print out the checks on website, so i tried :

String[] str = (String[])request.getAttribute("list");

But there is a error said

org.apache.jasper.JasperException: java.lang.ClassCastException: java.util.ArrayList cannot be cast to [Ljava.lang.String;

So what should i do to print the list?

Thank you.

Upvotes: 1

Views: 1922

Answers (1)

Mouad EL Fakir
Mouad EL Fakir

Reputation: 3749

Actually list is of type ArrayList not an Array, so try this instead :

<% 

ArrayList<String> list = (ArrayList<String>) request.getSession().getAttribute("list") ;

//do something ...

%>

And make sure you are allowing your jsp to access to the Session using : <%@ page session="true" %>


However as @JBNizet said it's so preferable to use jstl expression over than Java code in the jsp pages :

  1. in the servlet :
List<String> list = new ArrayList<>();

request.setAttribute("list" , list);

RequestDispatcher dispatcher=request.getRequestDispatcher("result.jsp");
dispatcher.forward(request,response);
  1. In the Jsp :
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>

<c:forEach items="${list}" var="element">

    //use the element here...
    ${element}

</c:forEach>

Upvotes: 1

Related Questions