Pages

Sunday, 31 July 2022

Servlets

Servlet technology is used to create a web application (resides at server side and generates a dynamic web page). Servlet technology is robust and scalable because of java language. Before Servlet, CGI (Common Gateway Interface) scripting language was common as a server-side programming language.

There are many interfaces and classes in the Servlet API such as Servlet, GenericServlet, HttpServlet, ServletRequest, ServletResponse, etc.

Introduction to Servlets:

Servlet is a server-side Java program module that handles client requests and implements the servlet interface. Servlets can respond to any type of request, and they are commonly used to extend the applications hosted by web servers.


In this figure you can see, a client sends a request to the server and the server generates the response, analyses it and sends the response back to the client.
Servlet is a class that extends the capabilities of the servers and responds to the incoming requests. It can respond to any requests.
Servlet is a web component that is deployed on the server to create a dynamic web page.

What is a web application?
A web application is an application accessible from the web. A web application is composed of web components like Servlet, JSP, Filter, etc. and other elements such as HTML, CSS, and JavaScript. The web components typically execute in Web Server and respond to the HTTP request.
Google, Facebook, Twitter are examples of web applications.

CGI (Common Gateway Interface)
CGI technology enables the web server to call an external program and pass HTTP request information to the external program to process the request. For each request, it starts a new process.

Servlet Life Cycle:
The entire life cycle of a servlet is managed by the Servlet container which uses the javax.servlet.
Servlet interface to understand the Servlet object and manage it.
Servlet Life Cycle: The Servlet life cycle mainly goes through four stages:

Loading a Servlet
When a server starts up, the servlet container deploy and loads all the servlets.

Initializing the Servlet
Next, a servlet is initialized by calling the init() method. Servlet.init() method is called by the Servlet container to notify that this Servlet instance is instantiated successfully and is about to put into service.
public void init(ServletConfig config) throws ServletException  

Request handling
Then, servlet calls service() method to process a client’s request and is invoked to inform the Servlet about the client requests. If servlet is initialized, it calls the service method. Notice that servlet is initialized only once. The syntax of the service method of the Servlet interface is given below:
public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException
  
•Destroying the servlet
Finally, a servlet is terminated by calling the destroy(). The destroy() method runs only once during the lifetime of a Servlet and signals the end of the Servlet instance.init() and destroy() methods are called only once.
The syntax of the destroy method of the Servlet interface 
is given below:public void destroy()  

Example Program on Servlet:
 
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
  
// Extend HttpServlet class
public class MyServlet extends HttpServlet 
   private String output;
    
   // Initializing servlet 
   public void init() throws ServletException 
   {
      output = "Advance Java Concepts";
   }
  
   // Requesting and printing the output
   public void doGet(HttpServletRequest request, 
                    HttpServletResponse response)
      throws ServletException, IOException 
      {
         response.setContentType("text/html");
         PrintWriter out = response.getWriter();
         out.println(output);
      }
  
      public void destroy() 
      {
         System.out.println("Over");
      }
}

JSP : JSP technology is used to create web application just like Servlet technology. It can be thought of as an extension to Servlet because it provides more functionality than servlet such as expression language, JSTL, etc. A JSP page consists of HTML tags and JSP tags. The JSP pages are easier to maintain than Servlet because we can separate designing and development.

Advantages of JSP over Servlet:
•JSP codes are easy to write and maintain.
•Development speed becomes fast, and there is no need for recompilation and redeployment.
•It has high performance and scalability compared to other dynamic web development tools.
•JSP is constructed on Java technology, which makes it platform-independent.

JSP technology is used to create dynamic web Applications. JSP pages are easier to maintain then a Servlet. JSP pages are opposite of Servlets as a servlet adds HTML code inside Java code, while JSP adds Java code inside HTML using JSP tags. Everything a Servlet can do, a JSP page can also do it. JSP enables us to write HTML pages containing tags, inside which we can include powerful Java programs. Using JSP, one can easily separate Presentation and Business logic as a web designer can design and update JSP pages creating the presentation layer and java developer can write server side complex computational code without concerning the web design. And both the layers can easily interact over HTTP requests.

Why JSP is proffered over servlets?
•JSP provides an easier way to code dynamic web pages.
•JSP does not require additional files like, java class files, web.xml etc
•Any change in the JSP code is handled by Web Container(Application server like tomcat), and doesn't require re-compilation.
•JSP pages can be directly accessed, and web.xml mapping is not required like in servlets.

What is JSP LifeCycle?
JSP Life Cycle is defined as translation of JSP Page into servlet as a JSP Page needs to be converted into servlet first in order to process the service requests. The Life Cycle starts with the creation of JSP and ends with the disintegration of that.
The life cycle of a JSP page can be divided into the following phase:
1.Translation Phase
2.Compilation Phase
3.Initialization Phase
4.Execution Phase
5.Destruction(Cleanup) Phase
Let us understand these steps in detail.
1.Translation Phase
  • When a user navigates to a page ending with a .jsp extension in their web browser, the web browser sends an HTTP request to the webserver.
  • The webserver checks if a compiled version of the JSP page already exists.
  • If the JSP page's compiled version does not exist, the file is sent to the JSP Servlet engine, which converts it into servlet content (with .java extension). This process is known as translation.
  • The web container automatically translates the JSP page into a servlet. So as a developer, you don't have to worry about converting it manually.
2.Compilation Phase: 
In case the JSP page was not compiled previously or at any point in time, then the JSP page is compiled by the JSP engine.
In this compilation phase, the Translated .java file of the servlet is compiled into the Java servlet .class file.

3. Initialization Phase:  
In this Initialization phase: Here, the container will:
1.Load the equivalent servlet class.
2.Create instance.
3.Call the jspInit() method for initializing the servlet instance.
This initialization is done only once with the servlet's init method where database connection, opening files, and creating lookup tables are done.

4.Execution Phase:
This Execution phase is responsible for all JSP interactions and logic executions for all requests until the JSP gets destroyed. As the requested JSP page is loaded and initiated, the JSP engine has to invoke the jspService() method. This method is invoked as per the requests, responsible for generating responses for the associated requests, and responsible for all HTTP methods.

5.Destruction(Cleanup) Phase:
This destruction phase is invoked when the JSP has to be cleaned up from use by the container. The jspDestroy() method is invoked. You can incorporate and write cleanup codes inside this method for releasing database connections or closing any file.


No comments:

Post a Comment

Servlet - JSP Programs

JSP(Java Server Pages) Programs : JavaServer Pages (JSP) is a Java standard technology that enables you to write dynamic data-driven pages f...