image
Working with Servlets
Intro to Servlet
Difficulty
Intermediate
Duration
1h 4m
Students
14
Description

This course provides a comprehensive overview of servlets. We'll work through the main components and then show you a couple of examples of servlets in use.

Learning Objectives

  • Understand the basics of servlets
  • Learn about servlet requests, servlet filters and listeners, as well as servlets context and listeners

Intended Audience

This course is intended for anyone who already has basic knowledge of Java and now wants to learn about Java EE 6.

Prerequisites

Basic knowledge of Java programming.

Transcript

Hello dear friends. In this video, we will begin to examine servlet technology. Before we begin, I'd like to clarify that we'll be looking at servlets in two videos. In this video, I will theoretically explain all necessary servlet topics. And in the following video, we will apply these topics to an application. So, let us get started. Servlets are the Java programs that run on the Java enabled web server or application server. They are used to handle the request obtained from the web server, process the request, produce the response and then send a response back to the web server. Servlets work on the server side. Servlets are capable of handling complex requests obtained from the web server. Although servlets can respond to any type of request, they are commonly used to extend the applications hosted by web servers. For such applications, Java servlet technology defines HTTP specific servlet classes.

Servlet technology is robust and scalable because of Java language. Before servlet, CGI, also known as common gateway interface scripting language was common as a server-side programming language. However, there were many disadvantages to this technology. There are many interfaces and classes in the servlet API, such as Servlet, GenericServlet, HttpServlet, ServletRequest, ServletResponse, etc. Now, let's examine this image. This image shows us the lifecycle of a servlet. A servlet lifecycle can be defined as the entire process from its creation till the destruction. The servlet is initialized by calling the init method. After that, servlet calls service method to process a client's request. After operations, servlet is terminated by calling the destroy method.

Finally, servlet is garbage collected by the garbage collector of the JVM. Let's examine these steps in detail. The servlet init method is called by the servlet container to indicate that this servlet instance is instantiated successfully and about to be put into service. The init method is called only once. It's called only when the servlet is created and not called for any user requests afterwards. So, it's used for one time initializations, just as with the init method of applets. The servlet is normally created when a user first invokes a URL corresponding to the servlet, but you can also specify that the servlet be loaded when the servlet is first started. When a user invokes a servlet, a single instance of each servlet gets created with each user request resulting in a new thread that is handed off to doGet or doPost as appropriate. The init method simply creates or load some data that will be used throughout the life of the servlet.

The service method of the servlet is invoked to inform the servlet about the client requests. The service method is the main method to perform the actual task. The servlet container as web server calls the service method to handle requests coming from the client and to write the formatted response back to the client. Each time the server receives a request for a servlet, the server spawns a new thread and calls service. The service method checks the HTTP request type and calls doGet, doPost, doPut doDelete, etc, methods as appropriate that we will examine one by one. The destroy method is called only once at the end of the lifecycle of a servlet. This method gives you your servlet a chance to close database connections, halt background threads, write cookie lists or hit counts to disk, and perform other such cleanup activities.

This method performs various tasks, such as closing connection with the database, releasing memory allocated to the servlet, releasing resources that are allocated to the servlet and other cleanup activities. When this method is called, the garbage collector comes into action. After the destroy method is called, the servlet object is marked for garbage collection. Now let's look up the HTTP request types. The HTTP servlet abstract subclass adds additional methods beyond the basic servlet interface, that are automatically called by the service method in the HTTP servlet class to aid in processing HTTP-based requests. These methods are; doHead for handling HTTP head requests, doGet for handling HTTP get requests, doPut for handling HTTP put requests, doPost for handling HTTP post requests, doDelete for handling HTTP delete requests, doOptions for handling HTTP options requests, doTrace for handling HTTP trace requests.

The doGet and doPost are more frequently used methods within each service request. We will create a project which includes doGet and doPost methods in the following video. Now, let's examine both of these in detail. doHead receives an HTTP head request from the protected service method and handles the request. The client sends a head request when it wants to see only the headers of a response, such as content type or content length. The HTTP head method counts the output bytes in the response to set the content length header accurately. If you override this method, you can avoid computing the response body and just set the response headers directly to improve performance. Make sure that the doHead method you write is both safe and item potent, that is, protects itself from being called multiple times for one HTTP head request. If the HTTP head request is incorrectly formatted, doHead returns an HTTP bad request message. There are two parameters, the request object that is passed to the servlet, the response object that the servlet uses to return the headers to the client.

There are two exceptions. If an input or output error occurs, throw java.io exception. And if the request for the head could not be handled, throw servlet exception. Overriding this method to support a Get request also automatically supports an HTTP head request. A head request is a Get request that returns no body in the response, only the request header fields. When overriding this method, read the request data, write the response headers, get the responses writer or output stream object, and finally write the response data. It's best to include content type and encoding. When using a print writer object to return the response, set the content type before accessing the print writer object. The servlet container must write the headers before committing the response, because in HTTP the headers must be sent before the response body.

Where possible, set the content length header to allow the servlet container to use a persistent connection to return its response to the client, improving performance. The content length is automatically set if the entire response fits inside the response buffer. The Get method should be safe, that is, without any side effects for which users are held responsible. For example, most form queries have no side effects. If a client request is intended to change stored data, the request should use some other HTTP method. The Get method should also be item potent, meaning that it can be safely repeated. Sometimes making a method safe also makes it item potent. For example, repeating queries is both safe and item potent, but buying a product online or modifying data is neither safe nor item potent. If the request is incorrectly formatted, doGet returns an HTTP bad request message.

There are two parameters: An HTTP servlet request object that contains the request the client has made of the servlet, and an HTTP servlet response object that contains the response the servlet sends to the client. Throws. If an input or output error is detected when the servlet handles the Get request, throws java.io exception. If the request for the Get could not be handled, throw servlet exception. doPut called by the server to allow a servlet to handle a Put request. The Put operation allows a client to place a file on the server, and is similar to sending a file by FTP. When overriding this method, leave intact any content headers sent with the request. If your method cannot handle a content header, it must issue an error message as HTTP 501 not implemented and discard the request. Operations that doPut performs can have side effects for which the user can be held accountable. When using this method, it may be useful to save a copy of the affected URL in temporary storage.

If an input or output error occurs while the servlet is handling the Put request, throws java.io exception. If the request for the Put cannot be handled, throws servlet exception. The HTTP Post method allows the client to send data of unlimited length to the web server a single time, and is useful when posting information such as credit card numbers. When overriding this method, read the request data, write the response headers, get the responses writer or output stream object, and finally write the response data. It's best to include content type and encoding. When using a print writer object to return the response, set the content type before accessing the print writer object. The servlet container must write the headers before committing the response, because in HTTP the headers must be sent before the response body. Where possible, set the content length header to allow the servlet container to use a persistent connection to return its response to the client, improving performance.

The content length is automatically set if the entire response fits inside the response. This method does not need to be either safe or item potent. Operations requested through Post can have side effects for which the user can be held accountable. For example, updating stored data or buying items online. The delete operation allows a client to remove a document or web page from the server. This method does not need to be either safe or item potent. Operations requested through delete can have side effects for which users can be held accountable. When using this method, it may be useful to save a copy of the affected URL in temporary storage. The options request determines which HTTP methods the server supports and returns inappropriate header. There's no need to override this method unless the servlet implements new HTTP methods. A trace returns the header sent with the trace request to the client, so that they can be used in debugging. There's no need to override this method. Now I think that's enough for this video. In the next video, we will examine servlet request. See you in the next video.

 

About the Author
Students
3984
Courses
64
Learning Paths
5

OAK Academy is made up of tech experts who have been in the sector for years and years and are deeply rooted in the tech world. They specialize in critical areas like cybersecurity, coding, IT, game development, app monetization, and mobile development.

Covered Topics