2011-03-24 109 views
17

我一直是一名PHP開發人員,但最近需要在使用Google App Engine(Java)的某個項目上工作。在PHP中我可以做這樣的事情(在MVC模型中的術語):將數據從Java Servlet傳遞到JSP?

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

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

我看看使用Servlet和JSP谷歌應用程序引擎的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的方式?

+0

。另一位朋友建議我擺脫JSP。使用Java Servlet和Closure http://code.google.com/closure/ – huy 2011-03-27 05:45:11

回答

30

你需要使數據在JSP

提供你會在你的servlet以下行設置在請求範圍在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

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); 
    } 
} 
+3

也可以使用getServletContext()。getRequestDispatcher(url).forward(request,response); – tomasb 2012-09-18 19:48:18

2
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. 
2

這是我的你的問題的理解 - 要在Servlet的計算數據一起重定向或派遣到一個新的JSP頁面,對不對?爲此,您需要在分派請求之前設置請求屬性。

您可以使用HttpServletRequest對象(req.setAttribute("attribute name", "attribute value"))來設置屬性。屬性值可以是任何Java對象。

您可以通過req.getAttribute("attribute name")檢索值。您還需要在用戶getAttribute()函數中鍵入對象。

8

你想要做的是首先定義一個對象來表示來自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" /> 
+0

我認爲這是最好的解決方案..使用java bean比上面給出的方法更清潔。 – AJed 2014-03-16 17:45:09

1

您可以設置的Java bean裏面的數據和當控制轉到jsp時,可以輕鬆地將這些數據存取到jsp頁面上。使用setter在java 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類可以擁有的許多屬性。

5

除了上面提到的有關使用表達式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> 
       <% 
      } 
     } 
%>