Servlet - Servlet Container - Servlet Lifecycle - Types of Servlets - Advantages of Servlets - Servlet Example

You might also like

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 12

Topics

•Servlet

•Servlet container

•Servlet lifecycle

•Types of Servlets

•Advantages of servlets

•Servlet example
What is servlet?
• Servlets are server side components that provide a
powerful mechanism for developing server side
programs.

• Servlets provide component-based, platform-


independent methods for building Web-based
applications.

• Servlets run entirely inside the Java Virtual Machine.

• Servlets are controlled by container.


Servlet Container
• A servlet container is nothing but a
compiled, executable program. The main
function of the container is to load,
initialize and execute servlets.

• Tomcat is one of the example of a


container.
Servlet container
What does container do?
• It creates an instance of the servlet and calls its init()
method to initialize it.

• It constructs a request object to pass to the servlet.

• It constructs a response object for the servlet.

• It invokes the servlet service() method, The service


method dispatches requests to the servlet doGet() or
doPost() methods, depending on the HTTP header in the
request (GET or POST).

• It calls the destroy() method of the servlet to discard it,


when appropriate, so that it can be garbage collected.
Lifecycle of servlet
Servlet Types
Generic Servlets:
• It belongs to javax.servlet package 

• It is a protocol-independent servlet.  

• To write a GenericServlet you need


abstract service() to be overridden. 
Http servlet:

• It belongs to javax.servlet.http package 

• It’s direct subclass to GenericServlet

• A subclass of HttpServlet must override at least


one method of doGet(), doPost(),doPut(),
doDelete(), init(), destroy(), getServletInfo()

• Specifically designed for Http.


Advantages of Java Servlets

• Portability.
• Powerful
• Efficiency
• Safety
• Extensibilty
• Inexpensive
Servlet Example
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class HelloWorld extends HttpServlet
{
 public void doGet(HttpServletRequest request, HttpServletResponse 
response) throws ServletException,IOException
{
    response.setContentType("text/html");
    PrintWriter pw = response.getWriter();
    pw.println("<html>");
    pw.println("<head><title>Hello World</title></title>");
    pw.println("<body>");
    pw.println("<h1>Hello World</h1>");
    pw.println("</body></html>");
  }
}
Thank you

You might also like