小编典典

将数据从Java Servlet传递到JSP?

jsp

我曾经是PHP开发人员,但最近需要使用Google App Engine(Java)从事某些项目。在PHP中,我可以执行以下操作(就MVC模型而言):

// controllers/accounts.php
$accounts = getAccounts();
include "../views/accounts.php";

// views/accounts.php
print_r($accounts);

我看一些使用Servlet和JSP的Google App Engine Java演示。他们正在做什么:

// In AccountsServlet.java
public class AccountsServlet extends HttpServlet {

  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String action = req.getParameter("accountid");
    // do something
    // REDIRECT to an JSP page, manually passing QUERYSTRING along.
    resp.sendRedirect("/namedcounter.jsp?name=" + req.getParameter("name"));
  }
}

基本上在Java情况下,它是2个不同的HTTP请求(第二个是自动强制执行的),对吗?因此,在JSP文件中,我无法利用Servlet中计算出的数据。

有什么方法可以类似于PHP?


阅读 267

收藏
2020-06-08

共1个答案

小编典典

您将需要在请求范围内设置在servlet中检索的数据,以便在JSP中可以使用该数据。

您的servlet中将包含以下行。

List<Account> accounts = getAccounts();  
request.setAttribute("accountList",accounts);

然后在JSP中,您可以使用如下所示的表达语言访问此数据

${accountList}

我将使用请求调度代替sendRedirect如下

  RequestDispatcher rd = sc.getRequestDispatcher(url);
  rd.forward(req, res);

如果可以使用,RequestDispatcher则可以将这些值存储在requestsessionobject中,并获取其他JSP。

有使用的特定目的request.sendRedirect吗?如果不使用RequestDispatcher

有关更多详细信息,请参见此链接

public class AccountServlet extends HttpServlet {

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    List<Account> accounts = getAccountListFromSomewhere();

    String url="..."; //relative url for display jsp page
    ServletContext sc = getServletContext();
    RequestDispatcher rd = sc.getRequestDispatcher(url);

    request.setAttribute("accountList", accounts );
    rd.forward(request, response);
  }
}
2020-06-08