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?
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);
}
}
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" />
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>
<%
}
}
%>
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.
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.
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.
精彩评论