簡體   English   中英

如何在JSTL的JSP頁面中調用數組方法?

[英]How do I call an arrays methods from the JSP page in JSTL?

我偶然發現了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文檔

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM