SlideShare uma empresa Scribd logo
1 de 23
Servlet
Differences between Generic and Http
               Servlet
• javax.servlet.GenericServlet
  Signature: public abstract class GenericServlet
  extends java.lang.Object implements
  Servlet, ServletConfig, java.io.Serializable
javax.servlet.GenericServlet
Signature:
public abstract class GenericServlet extends java.lang.Object
   implements Servlet, ServletConfig, java.io.Serializable
• GenericServlet defines a generic, protocol-independent servlet.
• GenericServlet uses service() method to handle request
• GenericServlet gives a blueprint and makes writing servlet easier.
• GenericServlet provides simple versions of the lifecycle methods
   init and destroy and of the methods in the ServletConfig interface.
• GenericServlet implements the log method, declared in the
   ServletContext interface.
• To write a generic servlet, it is sufficient to override the abstract
   service method.
javax.servlet.http.HttpServlet
Signature:
 public abstract class HttpServlet extends GenericServlet
   implements java.io.Serializable
• http is protocol dependent
• HttpServlet defines a HTTP protocol specific servlet.
• HttpServlet uses doGet and doPost methods to handle
   requests.

• HttpServlet gives a blueprint for Http servlet and makes
  writing them easier.
• HttpServlet extends the GenericServlet and hence inherits
  the properties GenericServlet.
Package javax.servlet.http

Interface Summary

                                 Extends the ServletRequest interface to provide request
HttpServletRequest
                                 information for HTTP servlets.

                                 Extends the ServletResponse interface to provide HTTP-
HttpServletResponse
                                 specific functionality in sending a response.

                                 Provides a way to identify a user across more than one page
HttpSession                      request or visit to a Web site and to store information about
                                 that user.

                                 Objects that are bound to a session may listen to container
HttpSessionActivationListener    events notifying them that sessions will be passivated and
                                 that session will be activated.

                                 This listener interface can be implemented in order to get
HttpSessionAttributeListener     notifications of changes to the attribute lists of sessions
                                 within this web application.

                                 Causes an object to be notified when it is bound to or
HttpSessionBindingListener
                                 unbound from a session.

                                 Deprecated. As of Java(tm) Servlet API 2.1 for security
HttpSessionContext
                                 reasons, with no replacement.

                                 Implementations of this interface are notified of changes to
HttpSessionListener
                                 the list of active sessions in a web application.
Class Summary


                             Creates a cookie, a small amount of information sent by a servlet
Cookie                       to a Web browser, saved by the browser, and later sent back to
                             the server.


                             Provides an abstract class to be subclassed to create an HTTP
HttpServlet
                             servlet suitable for a Web site.


                             Provides a convenient implementation of the HttpServletRequest
HttpServletRequestWrapper    interface that can be subclassed by developers wishing to adapt
                             the request to a Servlet.


                             Provides a convenient implementation of the
HttpServletResponseWrapper   HttpServletResponse interface that can be subclassed by
                             developers wishing to adapt the response from a Servlet.


                             Events of this type are either sent to an object that implements
                             HttpSessionBindingListener when it is bound or unbound from a
HttpSessionBindingEvent      session, or to a HttpSessionAttributeListener that has been
                             configured in the deployment descriptor when any attribute is
                             bound, unbound or replaced in a session.


                             This is the class representing event notifications for changes to
HttpSessionEvent
                             sessions within a web application.


HttpUtils                    Deprecated. As of Java(tm) Servlet API 2.3.
Generic Servlet
• javax.servlet
  Class GenericServlet
• java.lang.Object javax.servlet.GenericServlet
  All Implemented Interfaces:
  java.io.Serializable, Servlet, ServletConfig
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
 import javax.servlet.ServletResponse;
public class GenericServletExample extends GenericServlet {
  public void init()
{ log("inside init() method"); }
  public void service(ServletRequest request, ServletResponse response)
    throws ServletException, IOException
{ log("Handling request");
 response.setContentType("text/html");
PrintWriter out = response.getWriter();
 out.write("<html><head><title>GenericServle example</title></head>");
    out.write("<body><h1>GenericServlet: Hallo world
    </h1></body></html>");
 out.close(); }
public void destroy()
{ log("inside destroy() method"); } }
HttpServlet
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Hello extends HttpServlet {
  public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws IOException, ServletException
  {
     response.setContentType("text/html");
     PrintWriter out = response.getWriter();
     out.println("<html>");
    out.println("<body>");
out.println("<h1>hello</h1>");
     out.println("</body>");
     out.println("</html>");
  }
}
Compiling Hello.java
C:Program FilesApache Software FoundationTomcat 5.5webappslalithaWEB-
    INFclasses>javac -classpath "C:Program FilesApache Software
    FoundationTomcat 5.5commonlibservlet-api.jar" Hello.java

Run
http://localhost:8080/lalitha/Hello
<web-app>
<servlet>
    <servlet-name>Hello</servlet-name>
    <servlet-class>Hello</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>Hello</servlet-name>
    <url-pattern>/Hello</url-pattern>
  </servlet-mapping>
</web-app>
Servlet Life Cycle
• A servlet is basically a small Java program that
  runs within a Web server.
• It can receive requests from clients and return
  responses.
• The whole life cycle of a servlet breaks up into 3
phases:
• Initialization: A servlet is first loaded and initialized
  usually when it is requested by the corresponding
  clients.
• Service: After initialization, the servlets serve clients
  on request, implementing the application logic of
  the web application they belong to.
• Destruction: When all pending requests are
  processed and the servlets have been idle for a
  specific amount of time, they may be destroyed by
  the server and release all the resources they
  occupy.
More specifically, the behavior of a servlet is described in javax.servlet.Servlet
   interface, in which the following methods are defined:
• public void init(ServletConfig config) throws ServletException
          This method is called once when the servlet is loaded into the servlet
   engine, before the servlet is asked to process its first request.
          The init method has a ServletConfig parameter. The servlet can read its
   initialization arguments through the ServletConfig object. How the initialization
   arguments are set is servlet engine dependent but they are usually defined in a
   configuration file.
• public void service(ServletRequest request, ServletResponse response) throws
ServletException, IOException
          This method is called to process a request. It can be called zero, one or many
   times until the servlet is unloaded.
          Once a servlet is loaded, it remains in the server’s memory as a single object
   instance.
• public void destroy()
          This method is called once just before the servlet is unloaded and taken out
   of service.
The following servlet presents information about how many times it has been
                                   accessed:


import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SimpleCounter extends HttpServlet {
int count = 0;
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/plain");
PrintWriter out = res.getWriter();
count++;
out.println("Since loading, this servlet has been accessed " +
count + " times.");
}
}
import java.io.*; import javax.servlet.*; public class
   HelloServlet extends GenericServlet {
public void init ( ServletConfig config ) {
 super.init ( config ); } public void service (
   ServletRequest req, ServletResponse res ) throws
   ServletException, IOException {
PrintStream out = new PrintStream (
   res.getOutputStream ( ) ); out.println ( "Hello,
   World!" ); } public void destroy ( ) {
super.destroy ( ); }
}

Mais conteúdo relacionado

Mais procurados

Mais procurados (20)

Java Programming for Designers
Java Programming for DesignersJava Programming for Designers
Java Programming for Designers
 
REST & RESTful Web Services
REST & RESTful Web ServicesREST & RESTful Web Services
REST & RESTful Web Services
 
Remote Method Invocation (RMI)
Remote Method Invocation (RMI)Remote Method Invocation (RMI)
Remote Method Invocation (RMI)
 
3 Tier Architecture
3  Tier Architecture3  Tier Architecture
3 Tier Architecture
 
Enterprise java unit-3_chapter-1-jsp
Enterprise  java unit-3_chapter-1-jspEnterprise  java unit-3_chapter-1-jsp
Enterprise java unit-3_chapter-1-jsp
 
Servlets
ServletsServlets
Servlets
 
Asynchronous programming in C#
Asynchronous programming in C#Asynchronous programming in C#
Asynchronous programming in C#
 
Advanced java
Advanced java Advanced java
Advanced java
 
Servlets
ServletsServlets
Servlets
 
Java Docs
Java DocsJava Docs
Java Docs
 
JDBC Architecture and Drivers
JDBC Architecture and DriversJDBC Architecture and Drivers
JDBC Architecture and Drivers
 
Introduction to Web Services
Introduction to Web ServicesIntroduction to Web Services
Introduction to Web Services
 
JMS-Java Message Service
JMS-Java Message ServiceJMS-Java Message Service
JMS-Java Message Service
 
Java rmi
Java rmiJava rmi
Java rmi
 
Web services
Web servicesWeb services
Web services
 
Jdbc ppt
Jdbc pptJdbc ppt
Jdbc ppt
 
C# REST API
C# REST APIC# REST API
C# REST API
 
Webservices
WebservicesWebservices
Webservices
 
3 Tier Architecture
3 Tier Architecture3 Tier Architecture
3 Tier Architecture
 
Collection Framework in java
Collection Framework in javaCollection Framework in java
Collection Framework in java
 

Destaque

Clase conexion java - Analisis de Sistemas
Clase conexion java - Analisis de SistemasClase conexion java - Analisis de Sistemas
Clase conexion java - Analisis de SistemasJose Bustamante Romero
 
Servlet and jsp interview questions
Servlet and jsp interview questionsServlet and jsp interview questions
Servlet and jsp interview questionsSujata Regoti
 
Do while, for y foreach
Do while, for y foreachDo while, for y foreach
Do while, for y foreachRogDer
 
Conexion mysql con java usando netbeans
Conexion mysql con java usando netbeansConexion mysql con java usando netbeans
Conexion mysql con java usando netbeansEmerson Garay
 
Diseño y validacion GUI con java usando Netbeans
Diseño y validacion GUI con java usando NetbeansDiseño y validacion GUI con java usando Netbeans
Diseño y validacion GUI con java usando NetbeansEmerson Garay
 
Introducción a la Programación con Java
Introducción a la Programación con JavaIntroducción a la Programación con Java
Introducción a la Programación con Javaflekoso
 

Destaque (10)

Clase conexion java - Analisis de Sistemas
Clase conexion java - Analisis de SistemasClase conexion java - Analisis de Sistemas
Clase conexion java - Analisis de Sistemas
 
Servlet and jsp interview questions
Servlet and jsp interview questionsServlet and jsp interview questions
Servlet and jsp interview questions
 
Java.sql.*
Java.sql.*Java.sql.*
Java.sql.*
 
Do while, for y foreach
Do while, for y foreachDo while, for y foreach
Do while, for y foreach
 
Conexion mysql con java usando netbeans
Conexion mysql con java usando netbeansConexion mysql con java usando netbeans
Conexion mysql con java usando netbeans
 
Diseño y validacion GUI con java usando Netbeans
Diseño y validacion GUI con java usando NetbeansDiseño y validacion GUI con java usando Netbeans
Diseño y validacion GUI con java usando Netbeans
 
Java servlets
Java servletsJava servlets
Java servlets
 
LibreríAs De Java
LibreríAs De JavaLibreríAs De Java
LibreríAs De Java
 
Introducción a la Programación con Java
Introducción a la Programación con JavaIntroducción a la Programación con Java
Introducción a la Programación con Java
 
2 tier and 3 tier architecture
2 tier and 3 tier architecture2 tier and 3 tier architecture
2 tier and 3 tier architecture
 

Semelhante a Javax.servlet,http packages

Http Server Programming in JAVA - Handling http requests and responses
Http Server Programming in JAVA - Handling http requests and responsesHttp Server Programming in JAVA - Handling http requests and responses
Http Server Programming in JAVA - Handling http requests and responsesbharathiv53
 
S E R V L E T S
S E R V L E T SS E R V L E T S
S E R V L E T Spatinijava
 
UNIT-3 Servlet
UNIT-3 ServletUNIT-3 Servlet
UNIT-3 Servletssbd6985
 
Servlet in java , java servlet , servlet servlet and CGI, API
Servlet in java , java servlet , servlet servlet and CGI, APIServlet in java , java servlet , servlet servlet and CGI, API
Servlet in java , java servlet , servlet servlet and CGI, APIPRIYADARSINISK
 
Java Servlet
Java ServletJava Servlet
Java ServletYoga Raja
 
Java Servlet Programming under Ubuntu Linux by Tushar B Kute
Java Servlet Programming under Ubuntu Linux by Tushar B KuteJava Servlet Programming under Ubuntu Linux by Tushar B Kute
Java Servlet Programming under Ubuntu Linux by Tushar B KuteTushar B Kute
 
Servlet ppt by vikas jagtap
Servlet ppt by vikas jagtapServlet ppt by vikas jagtap
Servlet ppt by vikas jagtapVikas Jagtap
 
Chapter 3 servlet & jsp
Chapter 3 servlet & jspChapter 3 servlet & jsp
Chapter 3 servlet & jspJafar Nesargi
 
HTTP, JSP, and AJAX.pdf
HTTP, JSP, and AJAX.pdfHTTP, JSP, and AJAX.pdf
HTTP, JSP, and AJAX.pdfArumugam90
 

Semelhante a Javax.servlet,http packages (20)

Chap4 4 1
Chap4 4 1Chap4 4 1
Chap4 4 1
 
Http Server Programming in JAVA - Handling http requests and responses
Http Server Programming in JAVA - Handling http requests and responsesHttp Server Programming in JAVA - Handling http requests and responses
Http Server Programming in JAVA - Handling http requests and responses
 
Java servlets
Java servletsJava servlets
Java servlets
 
S E R V L E T S
S E R V L E T SS E R V L E T S
S E R V L E T S
 
Servlet
Servlet Servlet
Servlet
 
UNIT-3 Servlet
UNIT-3 ServletUNIT-3 Servlet
UNIT-3 Servlet
 
Servlet in java , java servlet , servlet servlet and CGI, API
Servlet in java , java servlet , servlet servlet and CGI, APIServlet in java , java servlet , servlet servlet and CGI, API
Servlet in java , java servlet , servlet servlet and CGI, API
 
Java Servlet
Java ServletJava Servlet
Java Servlet
 
TY.BSc.IT Java QB U3
TY.BSc.IT Java QB U3TY.BSc.IT Java QB U3
TY.BSc.IT Java QB U3
 
Java servlets
Java servletsJava servlets
Java servlets
 
Weblogic
WeblogicWeblogic
Weblogic
 
Java Servlet Programming under Ubuntu Linux by Tushar B Kute
Java Servlet Programming under Ubuntu Linux by Tushar B KuteJava Servlet Programming under Ubuntu Linux by Tushar B Kute
Java Servlet Programming under Ubuntu Linux by Tushar B Kute
 
Servlet ppt by vikas jagtap
Servlet ppt by vikas jagtapServlet ppt by vikas jagtap
Servlet ppt by vikas jagtap
 
J2ee servlet
J2ee servletJ2ee servlet
J2ee servlet
 
J servlets
J servletsJ servlets
J servlets
 
gayathri.pptx
gayathri.pptxgayathri.pptx
gayathri.pptx
 
Lecture 2
Lecture 2Lecture 2
Lecture 2
 
Chapter 3 servlet & jsp
Chapter 3 servlet & jspChapter 3 servlet & jsp
Chapter 3 servlet & jsp
 
HTTP, JSP, and AJAX.pdf
HTTP, JSP, and AJAX.pdfHTTP, JSP, and AJAX.pdf
HTTP, JSP, and AJAX.pdf
 
Wt unit 3
Wt unit 3 Wt unit 3
Wt unit 3
 

Mais de vamsi krishna

Mais de vamsi krishna (14)

Software project management
Software project managementSoftware project management
Software project management
 
Network programming
Network programmingNetwork programming
Network programming
 
Mobile computing
Mobile computingMobile computing
Mobile computing
 
Data warehousing and data mining
Data warehousing and data miningData warehousing and data mining
Data warehousing and data mining
 
Advanced computer architecture
Advanced computer architectureAdvanced computer architecture
Advanced computer architecture
 
Web technologies
Web technologiesWeb technologies
Web technologies
 
Xml
XmlXml
Xml
 
Servletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,postServletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,post
 
Cookies
CookiesCookies
Cookies
 
Servletand sessiontracking
Servletand sessiontrackingServletand sessiontracking
Servletand sessiontracking
 
Unit4wt
Unit4wtUnit4wt
Unit4wt
 
Unit3wt
Unit3wtUnit3wt
Unit3wt
 
Unit2wt
Unit2wtUnit2wt
Unit2wt
 
Unit 1wt
Unit 1wtUnit 1wt
Unit 1wt
 

Javax.servlet,http packages

  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9. Differences between Generic and Http Servlet • javax.servlet.GenericServlet Signature: public abstract class GenericServlet extends java.lang.Object implements Servlet, ServletConfig, java.io.Serializable
  • 10. javax.servlet.GenericServlet Signature: public abstract class GenericServlet extends java.lang.Object implements Servlet, ServletConfig, java.io.Serializable • GenericServlet defines a generic, protocol-independent servlet. • GenericServlet uses service() method to handle request • GenericServlet gives a blueprint and makes writing servlet easier. • GenericServlet provides simple versions of the lifecycle methods init and destroy and of the methods in the ServletConfig interface. • GenericServlet implements the log method, declared in the ServletContext interface. • To write a generic servlet, it is sufficient to override the abstract service method.
  • 11. javax.servlet.http.HttpServlet Signature: public abstract class HttpServlet extends GenericServlet implements java.io.Serializable • http is protocol dependent • HttpServlet defines a HTTP protocol specific servlet. • HttpServlet uses doGet and doPost methods to handle requests. • HttpServlet gives a blueprint for Http servlet and makes writing them easier. • HttpServlet extends the GenericServlet and hence inherits the properties GenericServlet.
  • 12. Package javax.servlet.http Interface Summary Extends the ServletRequest interface to provide request HttpServletRequest information for HTTP servlets. Extends the ServletResponse interface to provide HTTP- HttpServletResponse specific functionality in sending a response. Provides a way to identify a user across more than one page HttpSession request or visit to a Web site and to store information about that user. Objects that are bound to a session may listen to container HttpSessionActivationListener events notifying them that sessions will be passivated and that session will be activated. This listener interface can be implemented in order to get HttpSessionAttributeListener notifications of changes to the attribute lists of sessions within this web application. Causes an object to be notified when it is bound to or HttpSessionBindingListener unbound from a session. Deprecated. As of Java(tm) Servlet API 2.1 for security HttpSessionContext reasons, with no replacement. Implementations of this interface are notified of changes to HttpSessionListener the list of active sessions in a web application.
  • 13. Class Summary Creates a cookie, a small amount of information sent by a servlet Cookie to a Web browser, saved by the browser, and later sent back to the server. Provides an abstract class to be subclassed to create an HTTP HttpServlet servlet suitable for a Web site. Provides a convenient implementation of the HttpServletRequest HttpServletRequestWrapper interface that can be subclassed by developers wishing to adapt the request to a Servlet. Provides a convenient implementation of the HttpServletResponseWrapper HttpServletResponse interface that can be subclassed by developers wishing to adapt the response from a Servlet. Events of this type are either sent to an object that implements HttpSessionBindingListener when it is bound or unbound from a HttpSessionBindingEvent session, or to a HttpSessionAttributeListener that has been configured in the deployment descriptor when any attribute is bound, unbound or replaced in a session. This is the class representing event notifications for changes to HttpSessionEvent sessions within a web application. HttpUtils Deprecated. As of Java(tm) Servlet API 2.3.
  • 14. Generic Servlet • javax.servlet Class GenericServlet • java.lang.Object javax.servlet.GenericServlet All Implemented Interfaces: java.io.Serializable, Servlet, ServletConfig
  • 15. import java.io.IOException; import java.io.PrintWriter; import javax.servlet.GenericServlet; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; public class GenericServletExample extends GenericServlet { public void init() { log("inside init() method"); } public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException { log("Handling request"); response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.write("<html><head><title>GenericServle example</title></head>"); out.write("<body><h1>GenericServlet: Hallo world </h1></body></html>"); out.close(); } public void destroy() { log("inside destroy() method"); } }
  • 16. HttpServlet import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class Hello extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<html>"); out.println("<body>"); out.println("<h1>hello</h1>"); out.println("</body>"); out.println("</html>"); } }
  • 17. Compiling Hello.java C:Program FilesApache Software FoundationTomcat 5.5webappslalithaWEB- INFclasses>javac -classpath "C:Program FilesApache Software FoundationTomcat 5.5commonlibservlet-api.jar" Hello.java Run http://localhost:8080/lalitha/Hello
  • 18. <web-app> <servlet> <servlet-name>Hello</servlet-name> <servlet-class>Hello</servlet-class> </servlet> <servlet-mapping> <servlet-name>Hello</servlet-name> <url-pattern>/Hello</url-pattern> </servlet-mapping> </web-app>
  • 19. Servlet Life Cycle • A servlet is basically a small Java program that runs within a Web server. • It can receive requests from clients and return responses.
  • 20. • The whole life cycle of a servlet breaks up into 3 phases: • Initialization: A servlet is first loaded and initialized usually when it is requested by the corresponding clients. • Service: After initialization, the servlets serve clients on request, implementing the application logic of the web application they belong to. • Destruction: When all pending requests are processed and the servlets have been idle for a specific amount of time, they may be destroyed by the server and release all the resources they occupy.
  • 21. More specifically, the behavior of a servlet is described in javax.servlet.Servlet interface, in which the following methods are defined: • public void init(ServletConfig config) throws ServletException This method is called once when the servlet is loaded into the servlet engine, before the servlet is asked to process its first request. The init method has a ServletConfig parameter. The servlet can read its initialization arguments through the ServletConfig object. How the initialization arguments are set is servlet engine dependent but they are usually defined in a configuration file. • public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException This method is called to process a request. It can be called zero, one or many times until the servlet is unloaded. Once a servlet is loaded, it remains in the server’s memory as a single object instance. • public void destroy() This method is called once just before the servlet is unloaded and taken out of service.
  • 22. The following servlet presents information about how many times it has been accessed: import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class SimpleCounter extends HttpServlet { int count = 0; public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/plain"); PrintWriter out = res.getWriter(); count++; out.println("Since loading, this servlet has been accessed " + count + " times."); } }
  • 23. import java.io.*; import javax.servlet.*; public class HelloServlet extends GenericServlet { public void init ( ServletConfig config ) { super.init ( config ); } public void service ( ServletRequest req, ServletResponse res ) throws ServletException, IOException { PrintStream out = new PrintStream ( res.getOutputStream ( ) ); out.println ( "Hello, World!" ); } public void destroy ( ) { super.destroy ( ); } }