Wednesday, August 4, 2010

Java Servlet Example / Sample code to read Request Information using HttpServletRequest from doGet, doPost or do* methods

Following Servlet sample code will demonstrate you how to extract request information within doGet, doPost or any other Sevlet methods. In the following example RequestInfo Servlet extends HttpSevlet and overrides its doGet and doPost methods, all the do* methods has 2 arguments (1) HttpServletRequest and (2) HttpServletResponse. We can extract request method, protocol, path, remote address from HttpServletRequest object as shown in the bellow example.

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class RequestInfo extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws IOException, ServletException
    {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<html>");
        out.println("<body>");
        out.println("<head>");
        out.println("<title>Request Information Example</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<h3>Request Information Example</h3>");
        out.println("Method: " + request.getMethod());
        out.println("Request URI: " + request.getRequestURI());
        out.println("Protocol: " + request.getProtocol());
        out.println("PathInfo: " + request.getPathInfo());
        out.println("Remote Address: " + request.getRemoteAddr());
        out.println("</body>");
        out.println("</html>");
    }


    /**
     * We are going to perform the same operations for POST requests
     * as for GET methods, so this method just sends the request to
     * the doGet method.
     */

    public void doPost(HttpServletRequest request, HttpServletResponse response)
    throws IOException, ServletException
    {
        doGet(request, response);
    }
}

No comments:

Post a Comment