0

Disclaimer: I've spent today researching this simple problem inside and out all across stachoverflow and beyond so please bear with me.

I have the following code on JSP:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@page import="com.contrast.db.Manager"%>
<%@page import="java.sql.Connection"%>
<%@page import="java.util.Map"%>


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



<%
    Integer age = Integer.valueOf(request.getParameter("age"));

%>    
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Test</title>


</head>
<body>


<%

    Manager db = new Manager();
    Connection conn = db.getConnection();


    if (null == conn) {
        out.println("Connection to MySQL failed");
    } else {
        out.println("Connection to MySQL succeeded");
    }

    Map<String, Integer> namesAndAge = db.findByAge(age);

%>

<h1>List of users older then <% out.println(age); %></h1>

<% out.println(namesAndAge); %>

<c:forEach items="${namesAndAge}" var="entry">
    Key = ${entry.key}, value = ${entry.value}<br>
</c:forEach>


</body>
</html>

This code for intents and purposes should print out the contents of the HashMap returned by db.findByAge(age) but it doesn't

Understandably one could assume that HashMap could be empty, but it's not (please see screen shot below)

Screenshot of the webpage

As you can see the HashMap is not empty but is not working

Any ideas what am I missing?

user1678312
  • 1,309
  • 3
  • 10
  • 11
  • Does this answer your question? [Iterating over an ArrayList with c:foreach (JSP/JSTL), Variable doesn't work](https://stackoverflow.com/questions/14625738/iterating-over-an-arraylist-with-cforeach-jsp-jstl-variable-doesnt-work) – Swati May 15 '20 at 04:03

1 Answers1

0

On the scriplets you declare objects, while in EL expressions what are referenced are attributes in a context (pageContext, request, session or application).

change this line:

Map<String, Integer> namesAndAge = db.findByAge(age);

For this:

request.setAttribute("namesAndAge", db.findByAge(age));
areus
  • 2,880
  • 2
  • 7
  • 17