AndreaNobili
AndreaNobili

Reputation: 42967

How can I retrieve an array put in session from a JSP page?

I have the following problem.

Into the service() method of a custom servlet that implement the HttpServlet interface I put an array of custom object into the session, in this way:

// The collection that have to be shown in a table inside the JSP view:
SalDettaglio[] salDettaglio = this.getSalDettaglioList();

HttpSession session = req.getSession(false);
session.setAttribute("salDettaglio", salDettaglio);

Then I want to retrieve this array salDettaglio into my JSP page. So I am trying to do something like this:

<%@ page import="com.myproject.xmlns.EDILM.SalReport.SalDettaglio" %>
<!-- showSalwf.jsp -->
<html>
<head>
</head>
<body>

<%
    out.println("TEST SALWF");

    SalDettaglio[] salDettaglio = request.getParameter("salDettaglio");

%>

</body>
</html>

The problem is that an error occur on this line:

SalDettaglio[] salDettaglio = request.getParameter("salDettaglio");

The IDE say to me that:

Incompatible types. Required: com.myproject.xmlns.EDILM.SalReport.SalDettaglio[] Found: java.lang.String

Why? How can I solve this issue?

Upvotes: 0

Views: 5432

Answers (3)

Santhosh
Santhosh

Reputation: 8197

You have stored the object in the session,But you are accessing it from the request

HttpSession session = req.getSession(false);
SalDettaglio[]= (SalDettaglio) session.getAttribute("salDettaglio");

Also you need to use request#getAttribute. see Difference between getAttribute() and getParameter().

on the otherhand you can use simple EL expressions to access the elements from the request and session scopes,

 ${sessionScope.salDettaglio}

As using scriptlets is considered to be bad practice over the decades . Have a look at How to avoid Java code in JSP files?

Upvotes: 1

SMA
SMA

Reputation: 37033

You need to use like:

(SalDettaglio[]) request.getSession(false).getAttribute("salDettaglio");

OR You could directly use something like:

<h4>${salDettaglio}</h4> <!-- if its a string say for example -->

OR you could even print using core's out EL like:

<c:out value="${sessionScope.salDettaglio}"/> <!-- which again would be useless as its an array -->

Upvotes: 1

Junaid S.
Junaid S.

Reputation: 2642

You can use EL, which is prefered in JSP.

<c:out value="${sessionScope.salDettaglio}"/>

Or if the name value is HTML safe, you can use

${sessionScope.salDettaglio}

Make sure the JSP is allow access session.

<%@ page session="true" %>

To use core JSTL, make sure the following code is included.

<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

Upvotes: 1

Related Questions