Reputation: 5414
I stumbled upon servlets and I just love them compared to scriptlets since they perfectly divide logic and view. But I'm having trouble calling instance methods in my JSP page.
I have the following JSP page:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!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>Insert title here</title>
</head>
<body>
<c:forEach items="${stringarray}">
${stringarray}
<br/>
</c:forEach>
</body>
</html>
And the following Servlet:
package controller;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class Servlet
*/
@WebServlet("/Servlet")
public class Servlet extends HttpServlet
{
private static final long serialVersionUID = 1L;
/**
* Default constructor.
*/
public Servlet()
{
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
String[] strarray = new String[5];
strarray[0] = "zero";
strarray[1] = "one";
strarray[2] = "two";
strarray[3] = "three";
strarray[4] = "four";
request.setAttribute("stringarray", strarray);
request.getRequestDispatcher("index.jsp").forward(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
// TODO Auto-generated method stub
}
}
Why can't I call the arrays methods with the dot separator in my JSP page?!
Upvotes: 0
Views: 567
Reputation: 35008
I think what you're looking for is the following:
<c:forEach var="stringElement" items="${stringarray}">
${stringElement}
<br/>
</c:forEach>
The c:forEach
tag loops over each element in the ${stringarray}
, but to access each item, you have to define a variable. See also the TLD docs
Upvotes: 1