image
Java Servlet Technology in Java EE 7
Servlet
Difficulty
Intermediate
Duration
1h 15m
Students
16
Description

In this course, we will learn the concepts of Java EE 7 with a focus on Servlet Technology.

Learning Objectives

  • Java Servlet Technology with Request, Filter and Listeners

Intended Audience

  • Anyone looking to get Oracle Java Certification
  • Those who want to improve Java 7 EE knowledge
  • Java developers

Prerequisites

  • Have at least 2 years of Java development experience 
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, produced 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 languag 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 life cycle 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 initialization 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 do GET or do POST 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 life cycle 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 HTTPServlet 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, doOption() forr 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 idempotent i.e., 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.IOException. 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 PrintWriter object to return the response, set the content type before accessing the PrintWriter 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, i.e., 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 idempotent, meaning that it can be safely repeated. Sometimes, making a method safe also makes it idempotent. For example, repeating queries is both safe and idempotent but buying a product online or modifying data is neither safe nor idempotent. 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 server response object that contains the response the servlet it sends to the client. Throws. If an input or output error is detected when the servlet handles the GET request, throws Java.IOException. 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.IOException. 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 PrintWriter object to return the response, set the content type before accessing the PrintWriter 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 idempotent. 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 idempotent. 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 an appropriate 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
3925
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