将数据从 Java Servlet 传递到 JSP?

发布于 2024-10-26 04:23:19 字数 890 浏览 1 评论 0原文

我曾经是一名 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 那样做到这一点吗?

I've been a PHP developer but recently need to work on some project using Google App Engine (Java). In PHP I can do something like this (in term of MVC model):

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

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

I take a look at some demos of Google App Engine Java using Servlet and JSP. What they're doing is this:

// 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"));
  }
}

Basically in the Java case it's 2 different HTTP requests (the second one being automatically forced), right? So in JSP file I can't make use of the data calculated in the Servlet.

Is there some way I can do it similar to the PHP way?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

哆啦不做梦 2024-11-02 04:23:19

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

。您的 servlet 中将包含以下行。

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

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

${accountList}

我将使用请求分派而不是 sendRedirect ,如下所示

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

如果您可以使用 RequestDispatcher 那么您可以存储这些值在 requestsession 对象中并获取其他 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);
  }
}

You will need to set the data retrieved in the servlet in request scope so that the data is available in JSP

You will have following line in your servlets.

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

Then in JSP you can access this data using the expression language like below

${accountList}

I would use request dispatches instead of the sendRedirect as follows

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

If you can use RequestDispatcher then you can store these values in request or session object and get in other JSP.

Is there any specific purpose of using request.sendRedirect?. If not use RequestDispatcher.

See this link for more details.

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);
  }
}
森林散布 2024-11-02 04:23:19

您要做的就是首先定义一个对象来表示 getAccounts() 中的信息 - 类似于 AccountBean。

然后在您的 servlet doPost 或 doGet 函数中,使用请求信息来填充您的 AccountBean 对象。

然后,您可以使用 setAttribute 方法将 AccountBean 对象存储在请求、会话或 servlet 上下文中,并将请求转发到 JSP 页面。

jsp 页面中的 AccountBean 数据是使用 和 标记提取的。

下面可能是您的 servlet 的示例:

protected void doPost(HttpServletRequest req, HttpServletResponse resp) {

  // get data from request querystring
  String accountId = req.getParameter("accountid");

  // populate your object with it (you might want to check it's not null)
  AccountBean accountBean = new AccountBean(accountId);

  // store data in session
  HttpSession session = req.getSession();
  session.setAttribute("accountBean", accountBean);

  // forward the request (not redirect)
  RequestDispatcher dispatcher = req.getRequestDispatcher("account.jsp");
  dispatcher.forward(req, resp);
}

然后您的 JSP 页面将具有以下内容来显示帐户信息:

<jsp:useBean id="accountBean" type="myBeans.AccountBean" />
Your account is <jsp:getProperty name="accountBean" property="status" />

What you want to do is first define an object to represent the information from getAccounts() - something like AccountBean.

Then in your servlets doPost or doGet function, use the request info to populate your AccountBean object.

You can then store the AccountBean object either in the request, session, or servlet context by using the setAttribute method, and forward the request to the JSP page.

The AccountBean data in your jsp page is extracted using the and tags.

Here might be an example of your servlet:

protected void doPost(HttpServletRequest req, HttpServletResponse resp) {

  // get data from request querystring
  String accountId = req.getParameter("accountid");

  // populate your object with it (you might want to check it's not null)
  AccountBean accountBean = new AccountBean(accountId);

  // store data in session
  HttpSession session = req.getSession();
  session.setAttribute("accountBean", accountBean);

  // forward the request (not redirect)
  RequestDispatcher dispatcher = req.getRequestDispatcher("account.jsp");
  dispatcher.forward(req, resp);
}

Then your JSP page would have the following to display the account information:

<jsp:useBean id="accountBean" type="myBeans.AccountBean" />
Your account is <jsp:getProperty name="accountBean" property="status" />
爱情眠于流年 2024-11-02 04:23:19

除了上面提到的使用表达式 lang 之外,您还可以通过请求本身传递属性。在 Servlet 的 doGet() 中,我们这样写:

Account[] accounts = AccountManager.getAccountList();
request.setAttribute("accountList", accounts );
RequestDispatcher rd = req.getRequestDispatcher(nextJSPurl);
rd.forward(req, resp);

在 JSP 中,我们可以从请求中检索属性:

 <%
    Account[] accounts= (Account[])request.getAttribute("accountList");

       if (accounts.length>0) {       
       for (Account account: accounts) {            
                %>
                <blockquote>account name: <%= account.getName() %></blockquote>
                <%
            }
        }
 %>

Besides what's mentioned above about using expression lang, you can also pass attributes via request itself. In Servlet's doGet(), we write something like:

Account[] accounts = AccountManager.getAccountList();
request.setAttribute("accountList", accounts );
RequestDispatcher rd = req.getRequestDispatcher(nextJSPurl);
rd.forward(req, resp);

In JSP, we can retrieve the attribute from request:

 <%
    Account[] accounts= (Account[])request.getAttribute("accountList");

       if (accounts.length>0) {       
       for (Account account: accounts) {            
                %>
                <blockquote>account name: <%= account.getName() %></blockquote>
                <%
            }
        }
 %>
窝囊感情。 2024-11-02 04:23:19
import javax.servlet.http.*;

public class AccountsServlet extends HttpServlet {

    public void doGet (HttpServletRequest request, HttpServletResponse response) {

        try {
            // Set the attribute and Forward to hello.jsp
            request.setAttribute ("somename", "someValue"); // to save your temporary calculations. 
            getServletConfig().getServletContext().getRequestDispatcher("/namedcounter.jsp?name=" + req.getParameter("name")).forward(request, response);
        } catch (Exception ex) {
            ex.printStackTrace ();
        }
    }

}

在上面的代码中,servlet 不会创建 2 个不同的请求。它将转发,还将保留原始请求中的所有数据。

request.setAttribute ("somename", "someValue"); // to save your temporary calculations. 
import javax.servlet.http.*;

public class AccountsServlet extends HttpServlet {

    public void doGet (HttpServletRequest request, HttpServletResponse response) {

        try {
            // Set the attribute and Forward to hello.jsp
            request.setAttribute ("somename", "someValue"); // to save your temporary calculations. 
            getServletConfig().getServletContext().getRequestDispatcher("/namedcounter.jsp?name=" + req.getParameter("name")).forward(request, response);
        } catch (Exception ex) {
            ex.printStackTrace ();
        }
    }

}

In the above code servlet will not create 2 different requests. It will forward, also will retain all data from original request.

request.setAttribute ("somename", "someValue"); // to save your temporary calculations. 
故人的歌 2024-11-02 04:23:19

这是我对你的问题的理解 - 你想重定向或分派到一个新的 JSP 页面以及 Servlet 中计算的数据,对吧?为此,您需要在分派请求之前设置请求属性。

您可以使用 HttpServletRequest 对象 (req.setAttribute("attribute name", "attribute value")) 设置属性。属性值可以是任何Java对象。

您可以通过req.getAttribute("attribute name")检索该值。您还需要在使用 getAttribute() 函数时对对象进行类型转换。

This is my understanding of your question - you want to redirect or dispatch to a new JSP page along with the data calculated in Servlet, right? To do so you need to set request attributes before dispatching the request.

You can set attributes using HttpServletRequest object (req.setAttribute("attribute name", "attribute value")). Attribute value can be any Java object.

You can retrieve the value by req.getAttribute("attribute name"). You'll also need to type cast the object while user getAttribute() function.

简美 2024-11-02 04:23:19

您可以在 java beans 中设置数据,并在控制权转到 jsp 时轻松访问 jsp 页面上的数据。使用setter在java bean中设置日期通过将该bean包含到jsp中来访问jsp页面上的这些数据。

<%@page contentType="text/html"%>
<jsp:useBean id="man" class="beans.Person"/>
<jsp:setProperty name="man" property="*"/>    
First Name: <jsp:getProperty name="man" property="firstName"/>

这样你就可以访问你的 bean 类可以拥有的尽可能多的属性。

You can set the data inside java beans and easily access that data onto jsp page when control goes to jsp. set the date in java beans using setters get access those data onto jsp page by including that bean into jsp.

<%@page contentType="text/html"%>
<jsp:useBean id="man" class="beans.Person"/>
<jsp:setProperty name="man" property="*"/>    
First Name: <jsp:getProperty name="man" property="firstName"/>

like this you can access as many properties your bean class can have.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文