Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass data from Java Servlet to JSP? [duplicate]

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?

like image 905
huy Avatar asked Mar 24 '11 04:03

huy


1 Answers

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);
  }
}
like image 195
ashishjmeshram Avatar answered Sep 19 '22 03:09

ashishjmeshram