Response redirection in Servlets

We can redirect the response of the servlet to another application resource.This resource may be another servlet, an HTML page, or a JSP. The resource (URL) must be available to the calling servlet, in the same servlet context.

There are two forms of response redirection that we discuss:

❑  Sending a standard redirect: Using a response.sendRedirect("myHtml.html")
page sends the HTML page as the response. If this page were another servlet, that servlet does not have access to the original request object, but its response would be sent. To have access to the request object, you must use the request dispatching technique discussed below.

❑ Sending a redirect to an error page: Here, an error code is sent as a parameter of the method, as in response.sendError(response.SC_NO_CONTENT). The error numbers are predefined constants of the response. The defined error page is displayed with the appropriate error message. What this page looks like is dependent on how this feature is configured for the application.Example 1 shows a servlet which redirects its response conditionally to either an error page, using the sendError method, or a standard HTML page, using the sendRedirect method, depending on the contents of the request. This servlet example is called from a form POST in an HTML page, generated by the servlet HTMLFormGeneratorRedirect (subclass of HTMLFormGenerator).

Example 1
package itso.servjsp.servletapi;
import javax.servlet.*;
import javax.servlet.http.*;
public class HTMLFormHandlerRedirect extends HTMLFormHandler {
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
PrintWriter out = res.getWriter();
out.println("<H2>Servlet API Example -
out.println("Hi <B>" + req.getParameter("firstname") + ",</B><P>");
String title = req.getParameter("title");
if (title.equals("Web Architect"))
res.sendError(res.SC_BAD_REQUEST, "Sorry, but Web architects can't
see the page");
else res.sendRedirect("HTMLFormHandlerRedirect.html");
out.println("And have worked with the following tools: <BR>");
Response redirection in Servlets Reviewed by 1000sourcecodes on 20:21 Rating: 5
Powered by Blogger.