Friday 5 September 2014

forward( ServletRequest request, ServletResponse response ) : forward the request

public void forward(ServletRequest request, ServletResponse response) throws ServletException, IOException
forward the request from a servlet to another resource in the server. Another resource can be a servlet/jsp/html file. This method must be called before committing any response to client. Calling of this method after committing the response cause IllegalStateException.

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(urlPatterns = {"/ProcessRequest"})
public class ProcessRequest extends HttpServlet {
 @Override
    public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException{
        PrintWriter out = res.getWriter();
        
        out.println("<html><body><h1>");
        out.println("Processed dispatching request");
        out.println("</h1></body></html>");
        
        out.close();
    }    
}

import java.io.IOException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;

@WebServlet(urlPatterns = {"/RequestProcess"})
public class RequestProcess extends HttpServlet {
    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException{
        RequestDispatcher dispatch = req.getRequestDispatcher("ProcessRequest");
        dispatch.forward(req, res);
    }
   
}

Run the servlet 'RequestProcess', output will be like below.


RequestDispatcher dispatch = req.getRequestDispatcher("ProcessRequest");
dispatch.forward(req, res);

getRequestDispatcher method of ServletRequest class returns the object of RequestDispatcher. 

Prevoius                                                 Next                                                 Home

No comments:

Post a Comment