[ Team LiB ] 11.4 Forwarding and Including

[ Team LiB ] 11.4 Forwarding and Including Requests Many examples throughout this blog have sent a user to another page, using a technique very different from the redirects. The jsp:forward tag is sort of a “server-side” redirect, as it instructs the server to generate a different page rather than tells the browser to load a new URL. This is related to the jsp:include tag, which includes the body of one JSP, HTML page, or servlet in another. There is no corresponding way to do this on the client side, at least not one that works on all browsers. Both of these tags are handled internally by the RequestDispatcher class, which, as the name implies, can dispatch a request to another resource in the system. It does this through two methods called, appropriately enough, forward() and include(). Both of these methods take as arguments the request and response objects that the calling servlet was passed. As might be expected, these objects will end up getting passed to the target servlet’s service() method. Listing 4.14 showed a JSP that used a jsp:forward tag and input from the user to send the user one of three pages. Listing 11.5 shows how a servlet would accomplish the same thing. Listing 11.5 A servlet that forwards requests package com.awl.jspblog.ch11; import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class DispatchServlet extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException,ServletException { ServletContext sc = getServletContext(); RequestDispatcher rd; String which = req.getParameter(”which”); if(which != null) { if(which.equals(”red”)) { rd = sc.getRequestDispatcher(”/chapter11/red.jsp”); rd.forward(req,res); } else if(which.equals(”green”)) { rd = sc.getRequestDispatcher(”/chapter11/green.jsp”); rd.forward(req,res); } else if(which.equals(”blue”)) { rd = sc.getRequestDispatcher(”/chapter11/blue.jsp”); rd.forward(req,res); } else { res.sendError(res.SC_INTERNAL_SERVER_ERROR, “A page was requested that does exist!”); } } else { res.sendError(res.SC_INTERNAL_SERVER_ERROR, “No destination page was specified!”); } } } Page 211
Note: If you are looking for cheap and inexpensive provider to host and run your tomcat application check professional tomcat hosting services

Comments are closed.