我偶然发现了servlet,而与scriptlet相比,我只是喜欢它们,因为它们完美地划分了逻辑和视图。但是我在JSP页面中调用实例方法时遇到麻烦。

我有以下JSP页面:

<%@ 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>


和以下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
    }
}


为什么我的JSP页面中不能使用点分隔符来调用数组方法?

最佳答案

我认为您正在寻找以下内容:

<c:forEach var="stringElement" items="${stringarray}">
  ${stringElement}
  <br/>
</c:forEach>


c:forEach标记在${stringarray}中的每个元素上循环,但是要访问每个项目,必须定义一个变量。另请参见TLD docs

关于java - 如何在JSTL的JSP页面中调用数组方法?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12384146/

10-14 12:51