• Skip to main content
  • Skip to primary sidebar
  • Skip to secondary sidebar
  • Skip to footer

Computer Notes

Library
    • Computer Fundamental
    • Computer Memory
    • DBMS Tutorial
    • Operating System
    • Computer Networking
    • C Programming
    • C++ Programming
    • Java Programming
    • C# Programming
    • SQL Tutorial
    • Management Tutorial
    • Computer Graphics
    • Compiler Design
    • Style Sheet
    • JavaScript Tutorial
    • Html Tutorial
    • Wordpress Tutorial
    • Python Tutorial
    • PHP Tutorial
    • JSP Tutorial
    • AngularJS Tutorial
    • Data Structures
    • E Commerce Tutorial
    • Visual Basic
    • Structs2 Tutorial
    • Digital Electronics
    • Internet Terms
    • Servlet Tutorial
    • Software Engineering
    • Interviews Questions
    • Basic Terms
    • Troubleshooting
Menu

Header Right

Home » Servlet » introduction » Additional Capabilities of HTTP Servlets
Next →
← Prev

Additional Capabilities of HTTP Servlets

By Dinesh Thakur

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.

We’ll be covering the following topics in this tutorial:

  • Objects of the HttpServletRequest class
  • Objects of the HttpServlet Response class
  • Examples of GET and POST Requests

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
                  }
  }

You’ll also like:

  1. Servlets Client HTTP Request
  2. Types of Servlets
  3. Advantages of Servlets
  4. Creating and Executing Servlets
  5. Steps for Using Sessions in Servlets
Next →
← Prev
Like/Subscribe us for latest updates     

About Dinesh Thakur
Dinesh ThakurDinesh Thakur holds an B.C.A, MCDBA, MCSD certifications. Dinesh authors the hugely popular Computer Notes blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps.

Dinesh Thakur is a Freelance Writer who helps different clients from all over the globe. Dinesh has written over 500+ blogs, 30+ eBooks, and 10000+ Posts for all types of clients.


For any type of query or something that you think is missing, please feel free to Contact us.


Primary Sidebar

Servlet Tutorials

Servlet Tutorials

  • Servlet - Home
  • Servlet - Types
  • Servlet - Advantages
  • Servlet - Container
  • Servlet - API
  • Servlet - Chaining
  • Servlet - Life Cycle
  • Servlet - Developement Way
  • Servlet - Servlet Vs CGI
  • Servlet - Server Side
  • Servlet - HttpServletRequest
  • Servlet - Cookies Advantages
  • Servlet - JDBC Architecture
  • Servlet - HttpServlet
  • Servlet - HttpServletResponse
  • Servlet - Web Technology
  • Servlet - Applet Communication
  • Servlet - Html Communication
  • Servlet - HTTP POST Request
  • Servlet - HTTP GET Request

Other Links

  • Servlet - PDF Version

Footer

Basic Course

  • Computer Fundamental
  • Computer Networking
  • Operating System
  • Database System
  • Computer Graphics
  • Management System
  • Software Engineering
  • Digital Electronics
  • Electronic Commerce
  • Compiler Design
  • Troubleshooting

Programming

  • Java Programming
  • Structured Query (SQL)
  • C Programming
  • C++ Programming
  • Visual Basic
  • Data Structures
  • Struts 2
  • Java Servlet
  • C# Programming
  • Basic Terms
  • Interviews

World Wide Web

  • Internet
  • Java Script
  • HTML Language
  • Cascading Style Sheet
  • Java Server Pages
  • Wordpress
  • PHP
  • Python Tutorial
  • AngularJS
  • Troubleshooting

 About Us |  Contact Us |  FAQ

Dinesh Thakur is a Technology Columinist and founder of Computer Notes.

Copyright © 2023. All Rights Reserved.