by Dinesh Thakur Category: introduction to Servlet

Of these, HTTP servlets have some additional objects that provide session-tracking capabilities, the servlet writer can use the HttpSession interface to maintain the state of a client between client requests upto some time period. The capability of maintaining cookies is also provided by the HTTP servlets, The servlet writer uses the Cookie class to save small bits of information within the client machine, which can be retrieved at request processing time, Program illustrates the use of the HttpServlets.

public class Servlet_A extends HttpServlet

{

                  public void doGet (HttpServletRequest request, HttpServletResponse response)

                  throws ServletException, IOException

               {

                          PrintWriter pout;

                        String title = "Http Servlet Example";

                     // set content type and other response header fields first

                        response,setContent Type("text/html");

                       // then write the data of the response

                       pout = response,getWriter();

                       pout,println ("<html ><head><title> ");

                       pout,println(title);

                       pout,printl n("</title></head><body>");

                       pout,println("<h1 >" + title + "</h1 >");

                       pout,println("<P>This is output from Servlet_A");

                       for(int i=0;i<=5;1++)

                              pout,print(i+" ");

                              pout.println ("</body></html>");

                              pout.c1ose();

                }

}

Servlet_A extends the HttpServlet class which, in turn, implements the Servlet interface. Here the title of the tag is displayed as the name of the browser window. Servlet_A overrides the doGet method in the HttpServlet class. The doGet method is called when a client makes a GET request (which is the default HTTP request method), and this results in the simple HTML page being returned to the client.

If a request is made to HttpServlet then the container delegates the request to the public service method within the servlet. This method will cast the ServletRequest, ServletResponse object to their corresponding HttpServletRequest and HttpServletResponse. Then this method will delegate the call to the protected service method. In the protected service method we call the method getMethod() on the request object, which will return the string specifying the type request. If the request is get then the doGet() method is called. In case the request is post then the doPost() method is called.

Objects of the HttpServletRequest class

Within the doGet method, the user's request is represented by an HttpServletRequest object. An HttpServletResponse object represents the response to the user. Because text data is returned to the client, the reply is sent using the Writer object obtained from the HttpServletResponse object.

Objects of the HttpServlet Response class

An object of the class HttpServletResponse provides two ways of returning data to the user:

• The getWriter() method which returns a PrintWriter object.

• The getOutputStream() method which returns a ServletOutputStream object.

One way of handling this is to use the getWriter method to return text data to the user and the getOutputStream method for binary data. Closing the Writer or ServletOutputStream after the response is sent allows the server to know when the response is complete. The HTTP header data must be setbeforeaccessing the Writer or OutputStream. The HttpServletResponse class provides methods to set the header data. For example, the setContent Type() method is used to set the content type (This is the header used most by the developer). So, in general, it is preferable to set the content type before accessing the Writer object.

Examples of GET and POST Requests

To handle HTTP requests in a servlet, extend the Http5ervlet class and override the servlet methods that handle the HTTP requests made by the clients. Programs illustrate how to handle GET and POST requests. The methods that handle these requests are doGet and do Post.

HandlingGETrequestsHandling GET requests involves overriding the doGet method. Program illustrates the use of the GET request. The Get method, in general, sends requests to the servlet without passing any parameters. It is also possible to pass the parameter to the get method.

Program Using theGETrequest. 
import javax.servlet.*;
import javax.servlet.http*;
import java.util.*;
import java.io.*;
public class ServlecGet extends HttpServlet
{
             public void init(ServletConfig config) throws ServletException
            {
                    super.init(config);
             }
             public void doGet(HttpServletRequest request, HttpServletResponse response)
             throws ServletException, IOException
            {
                    response.setContent Type("text/html");
                    PrintWriter pout = response.getWriter();
                    pout.println("<html><head><title> Receipt </title>" );
                    String date = new Date().toString();
                    pout.println("<h3> To day's date is:"+date);
                    pout.println ("</h3></head></html>");
                    pout.close();
            }
            public void destroy( )
           {
                    // destroyall resource if any connected to the servlet
           }
}

The Servlet_Get class extends the HttpServlet class and overrides the doGet method. To respond to the client, the doGet method in Programuses a Writer from the HttpServletResponse object to return text data to the client. Before accessing the writer, the content-type header is set in this program. At the end of the doGet method, after the response has been sent, the Writer is closed.

Handling POSTrequestsHandling POST requests involves overriding the doPost method. Programillustrates the means of overriding the doPost method. The Post method is used when information is passed to the servlet. If the doPost() method is overridden then the information has to be passed to the servlet.

Program UsingPOSTrequests

import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
import java.io.*;
public class Servlet_Post extends HttpServlet
{
            public void init(ServletConfig config) throws ServletException
           {
                    super.init( config);
            }
            public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException. IOException
           {
                           response.setContent Type("text/html");
                           PrintWriter pout = response.getWriter();
                           pout.println("<html><head><title> Receipt </title>" );
                           String date = new Date().toString();
                           pout.println("<h3>" +date);
                           pout.println ("</h3></head></html>");
                           pout.c1ose();
            }
                      public void destroy( )
                 {
                                 // destroy allresource if any connected to the servlet
                  }
  }




About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.