In this, you learn how to perform the last step in a form processing controller: Dispatch the next view component. This requires learning two new concepts: passing objects between web components using the request scope and passing control between web components using a request dispatcher.

Request Scope:

  • Servlets must be able to communicate with one other, but you do not want your servlets to have intimate knowledge of each other’s data.
  • The servlet API provides a mechanism to store objects in the request object using a method called setAttribute. The object can then be retrieved by another servlet using the getAttribute method on the request object.

Using a Request Dispatcher:

  • One servlet cannot simple “call” the doPost method of another servlet. Servlets are components that are logically and physically independent of each other.
  • Therefore, the web container provides a mechanism for one servlet to pass the user’s request to another servlet.
  • In the MVC, a controller dispatches the request to an appropriate view servlet to generate the HTML response.

Developing the AddLeagueServlet Code:

Now that you have seen the request scope and the request dispatcher, you see how to apply these two concepts in the AddLeague servlet code.

 

  1. import java.io.IOException;
  2. import java.io.PrintWriter;
  3. import java.util.LinkedList;
  4. import java.util.List;
  5. import javax.servlet.RequestDispatcher;
  6. import javax.servlet.ServletException;
  7. import javax.servlet.http.HttpServlet;
  8. import javax.servlet.http.HttpServletRequest;
  9. import javax.servlet.http.HttpServletResponse;
  10. public class AddLeagueServlet extends HttpServlet {
  11. protected void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

  1. // keep a set of strings to record form processing errors.
  2. List errorMsgs = new LinkedList();
  3. // store this set in the request scope, in case we need to send the error Page view.
  4. setAttribute(“errorMsgs”, errorMsgs);
  5. try {
  6. // Retrieve form parameters
  7. String yearStr = request.getParameter(“year”).trim();
  8. String season = request.getParameter(“season”).trim();
  9. String title = request.getParameter(“title”).trim();
  10. // Perform data cob=nversion
  11. int year = -1;
  12. try {

year = Integer.parseInt(yearStr);

  1. } catch (NumberFormatException nfe) {

errorMsgs.add(“the year field must be positive integer.”);

  1. }

If there were any errors, then this servlet forwards to the ErrorPage view. The argument to the getRequestDispatcher method is errorPage.view. This is the logical name of the ErrorPage view component. This is actually a relative URL to the full logical name, which is /admin/errorPage.view(anything). The  getRequestRequestDispatcher method understands that the current request was for the logical controller /admin/add_league.do(anything). Therefore, the getRequestDispatcher method appends /admin/ to the relative URL errorPage.view to get the actual logical URL /admin/errorPage.view.

  1. // varify form parameter
  2. if ((year != -1) && (year < 2000) && (year > 2014)) {

errorMsgs.add(“the year field must within 2000 to 2014.”);

  1. }
  2. if (season.equals(“UNKNOWN”)) {

errorMsgs.add(“Please select a league season”);

  1. }
  2. if (title.length() == 0) {

errorMsgs.add(“Please enter the title of the league.”);

  1. }
  2. // send the error page view if there were errors
  3. if (!errorMsgs.isEmpty()) {

// dispatch to the error page

PrintWriter printWriter = response.getWriter();

printWriter.println(“Error Page”);

return;

  1. }

The business logic is successful, then this servlet forwards to the Success view. Furthermore, if any unexcepted errors occur, then the controller forwardstotheErrorPage view.

  1. // perform business logic
  2. League league = new League(year, season, title);
  3. setAttribute(“league”, league);
  4. // send the success view
  5. RequestDispatcher view = request.getRequestDispatcher(“sucess.view”);
  6. forward(request, response);
  7. return;
  8. // handle any unexpected exceptions
  9. } catch (RuntimeException re) {
  10. add(re.getMessage());
  11. // dispatch to the error page
  12. RequestDispatcher view = request.getRequestDispatcher(“errorPage.view”);
  13. forward(request, response);
  14. // Log stack trace
  15. printStackTrace(System.err);
  16. }
  17. }
  18. }

 

Dispatching From the Controller to a View

 

Developing the SuccessServlet Code:

This is a simple view, but it requires the title of the newly created league. This data is passed to the Success servlet using the request scope attribute called league. In this, it shows the SucceesServlet code.

The code given below shows the declaration of the SuccessServlet class. Notice that this servlet implements both of these methods simply call the shared, private method generateView. This is done because a forwarded servlet must respond to the HTTP method of the controller (forwarding) servlet.

  1. import java.io.IOException;
  2. import java.io.PrintWriter;
  3. import javax.servlet.ServletException;
  4. import javax.servlet.http.HttpServlet;
  5. import javax.servlet.http.HttpServletRequest;
  6. import javax.servlet.http.HttpServletResponse;
  7. public class SuccessServlet extends HttpServlet {
  8. protected void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

  1. generateView(request, response);
  2. }
  3. protected void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

  1. generateView(request, response);
  2. }
  3. protected void generateView(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

  1. // set page title
  2. String pageTitle = “Duke’s Soccer League: Add League Success”;
  3. // retrieve the ‘league’ from the request scope
  4. League league = (League) request.getAttribute(“league”);
  5. // specify the content type is HTML
  6. setContentType(“text/html”);
  7. PrintWriter out = response.getWriter();
  8. // generate the HTML response
  9. println(“<html>”);
  10. println(“<head>”);
  11. println(“<title>” + pageTitle + “</title>”);
  12. println(“</head>”);
  13. println(“<body bgcolor = ‘white’>”);
  14. // generating page heading
  15. println(“<!– Page Heading –>”);
  16. println(“<table border = ‘1’ cellpadding = ‘5’ cellspacing = ‘0’ width = ‘400’>”);
  17. println(“<tr bgcolor= ‘#CCCCFF’ align = ‘center’ valign = ‘center’ height = ’20’>”);
  18. println(“<td><h3>” + pageTitle + “</h3></td>”);
  19. println(“</tr>”);
  20. println(“</table>”);
  21. // generate main body
  22. println(“<p>”);
  23. println(“you request to add the”);
  24. println(“<i>”+ league.getTitle() +”</i>”);
  25. println(” league was successful.”);
  26. println(“</p>”);
  27. println(“</body>”);
  28. println(“</html>”);
  29. }

}

For more reading about technology news in singapore or from all over the world in all aspect from seo to online marketing do view more about other pages.

Written by Sourabh Bhunje

Sourabh Bhunje, B.E. IT from Pune University. Currently Working at Techliebe. Professional Skills: Programming - Software & Mobile, Web & Graphic Design, Localization, Content Writing, Sub-Titling etc. http://techliebe.com/about-us

Leave a Comment