我已经看到了类似于此问题的其他问题,但没有一个问题帮助我解决了我的问题.基本上,我正在尝试将变量从servlet传递给JSP.
servlet代码.
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); } }
我的JSP代码
<%@ 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>
我已经使用forEach标签完成了一些测试,并正确设置了JSTL.我认为变量“data”没有到达JSP.知道为什么吗?
提前致谢.
编辑:澄清porpuses.我试过了
<c:forEach var="i" begin="1" end="5"> Item <c:out value="${i}"/><p> </c:forEach>
这有效,但是
<c:forEach var="item" items="${data}"> It worked!<p> </c:forEach>
不起作用.这使我相信可变数据由于某种原因没有到达JSP.
编辑2:为了运行它,我在Eclipse上配置了一个Tomcat服务器.我右键单击servlet并选择Run As – >在服务器上运行.服务器重新启动,我从浏览器启动http:// localhost:8080 / DataExtractor /.这是生成的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>
编辑3:这可能是发生这种情况的关键.当我转到http:// localhost:8080 / DataExtractor /(index.jsp)时,我得到了在Edit 2中发布的html,但如果我转到http:// localhost:8080 / DataExtractor / DataGetterServlet那么我确实得到了右页!知道为什么吗?