Passing variable from servlet to JSP
Asked Answered
S

3

6

I've seen other questions similar to this asked but none of them have helped me solve my problem. Basically, I'm trying to pass a variable from a servlet to a JSP.

The servlet code.

package com.servlets;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.annotation.WebServlet;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.dao.DataGetter;

@WebServlet("/DataGetterServlet")
public class DataGetterServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    ArrayList<String[]> data;
    private DataGetter dg;

    public void init() throws ServletException {
        try {
            dg = new DataGetter();
            data = dg.getData();
        } catch (Exception e) {
            throw new ServletException("An exception occurred in DataGetterServlet: " 
                + e.getClass().getName());
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
        throws ServletException, IOException {

        request.setAttribute("data", data);
        RequestDispatcher rd = request.getRequestDispatcher("index.jsp");
        rd.forward(request, response);
    }
} 

My JSP code

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" 
    pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
    "http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>Data extractor</title>
</head>

<body>
    Data table:

    <table boder="1">
        <c:forEach var="item" items="${data}" >
            <tr>
                <c:forEach var="column" items="${item}">
                    <td>${column}</td> 
                </c:forEach>
            </tr> 
        </c:forEach>
    </table>
</body>
</html> 

I have done some tests with the forEach tag and JSTL is setup properly. I think the variable "data" is not reaching the JSP. Any idea why?

Thanks in advance.

EDIT: For clarification porpuses. I have tried

<c:forEach var="i" begin="1" end="5">
   Item <c:out value="${i}"/><p>
</c:forEach>

And that works, but

<c:forEach var="item" items="${data}">
   It worked!<p>
</c:forEach>

doesn't work. This is what has led me to believe that that variable data is not reaching the JSP for some reason.

EDIT 2: To run it, I configured a Tomcat server on Eclipse. I right click on the servlet and choose Run As -> Run on Server. The server restarts and I launch http://localhost:8080/DataExtractor/ from my browser. Here's the resulting html:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>Data extractor</title>
</head>

<body>
Data table:
    <table border="1">

    </table>
</body>
</html> 

EDIT 3: This might be the key of why this is happening. When I go to http://localhost:8080/DataExtractor/ (index.jsp), I get the html posted in Edit 2, but if I go to http://localhost:8080/DataExtractor/DataGetterServlet then I do get the right page! Any idea why?

Socle answered 13/6, 2013 at 21:52 Comment(4)
Are you sure that the "data" array variable in the servlet actually has values when you are adding it to the request?Unbidden
Yes, I've checked and I can say for sure that the ArrayList is properly populated.Socle
Are you sure your arrayList is not empty list? If it is empty, then the loop won't iterateIridaceous
100% sure. I threw Exceptions in my servlet init() method with values such as data.get(0)[0] to check and the ArrayList and internal arrays are populated correctly.Socle
L
4

This might be a typo, $(item) should be ${item} in the following -

<c:forEach var="column" items="$(item)" >

Update

http://localhost:8080/DataExtractor/ that doesn't map to the servlet, while http://localhost:8080/DataExtractor/DataGetterServlet does. If the servlet isn't invoked then it's obvious that data is not going to be the request. In other words, the first url is not invoking the servlet, but directly talking you to the page. (You probably have as welcome-page in web.xml)

Lester answered 13/6, 2013 at 22:2 Comment(3)
Can update your question with the full definition of the servlet and also can you show how are you firing the request?Lester
Have you also been checking the tomcat's log file?Lester
@fpele: Updated it with the comment. Took a while but you nailed it anyway. Great effort and good job. +1.Lester
L
2

In the jsp, you need to include this in the header:

<jsp:useBean id="data" class="java.util.ArrayList" scope="request"/>
Losel answered 13/6, 2013 at 21:56 Comment(3)
That has to work. Just, make sure to have ArrayList<String> instead of ArrayList<String[]>.Losel
This is not required - In any case, if you're using a servlet, you should not be using <jsp:useBean> ...Lester
Exactly @BheshGurung, I'm following a different MVC model, where my servlet is instantiating a DAO and then dispatching the data to the JSP. As I understand, if you are using beans, you can remove the servlet altogether. Am I right?Socle
I
2

I think your problem was because of typo only.

<c:forEach var = "column" items = "${data}">

and

<c:forEach var = "column" items = "${requestScope.data}">

worked well for me because requestScope holds the map of request objects.

Iridaceous answered 13/6, 2013 at 22:37 Comment(1)
Thank you for noticing. I did have that typo in my code, but that's not the real problem. Please see the edit I made for clarification.Socle

© 2022 - 2024 — McMap. All rights reserved.