SlideShare ist ein Scribd-Unternehmen logo
1 von 20
SERVLETS
Servlet

• Platform-    independent    Server   side
  components , written in Java which
  extends the standard web server and
  provide a general framework for services
  build on the Request –Response paradigm
• An Efficient and Powerful technology for
  creating dynamic content for the Web and
  fundamental part of all Java web
  technologies
Servlet Container
        The servlet container
is a part of a Web server or
application      server    that
provides       the     network
services        over     which
requests and responses
are sent, decodes MIME-
based requests, and formats
MIME-based responses. A
servlet      container     also
manages servlets through
their lifecycle.
Servlet API
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 gives a blueprint and makes writing
  servlet easier.
• 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
• HttpServlet defines a HTTP protocol specific servlet.
• HttpServlet gives a blueprint for Http servlet and makes
  writing them easier.
• HttpServlet extends the GenericServlet and hence
  inherits the properties GenericServlet.
Servlet Life Cycle
The Web container manages the life cycle of servlet instances

                                        New              Destroyed



                                              Running
                                 init(                      destroy(
                                 )                          )


                                                               ...(
                                              service(
                                                               )
                                              )
                               doGet(
                               )                              doDelete(
                                                              )
                                        doPost(     doPut(
                                        )           )
The init ( ) method
•    Called by the Web container when the servlet instance is first created
•    The Servlets specification guarantees that no requests will be processed by
     this servlet until the init method has completed
• Override the init() method when:
        i) You need to create or open any servlet-specific resources that you need
for processing user requests
        ii)You need to initialize the state of the servlet
//A simple servlet lifecycle counter
// int count ;
public void init(ServletConfig config) throws ServletException
     {
                    super.init(config);
                    getServletContext().log("init() called");
                    count=0;
         }
The service ( ) method
• Called by the Web container to process a user request
• Dispatches the HTTP requests to doGet(…),
  doPost(…), etc. depending on the HTTP request
  method (GET, POST, and so on)
   – Sends the result as HTTP response
• Usually we do not need to override this method

 protected void service(HttpServletRequest request, HttpServletResponse response) throws
 ServletException, IOException
      {
                        getServletContext().log("service() called");
                        count++;
                        response.getWriter().write("Incrementig the count: Count = "+count);

            }
The destroy() Method
•   Called by the Web container when the servlet instance is being eliminated ( All
    threads within the servlets service method have exited (or) Time-out period have
    passed )

•   The Servlet specification guarantees that all requests will be completely processed
    before this method is called
•   Override the destroy method when:
     – You need to release any servlet-specific resources that you had opened in the
        init() method
     – You need to persist the state of the servlet




     public void destroy() {
                       getServletContext().log("destroy() called");
              }
servletConfig
• Object of servletConfig used to pass initialization and
  context information to servlets
• getServletConfig ( ) method allows the servlet to retrieve
  the object and obtain configuration at anytime
• Init () method stores the servletConfig object in a private
  transient instance variable called config
ServletContext
• The javax.servlet.ServletContext interface provides a set of methods
  that the servlet can use to communicate with the web server.
• The       ServletContext      object     is     contained      within
  javax.servlet.ServletConfig Object which is provided to the servlet
  when it is initialized.
• Define URI to name mappings
• Allow Data to be shared between different servlets
• Contains a servlet log
• Access to global servlet config and other application servlet context
  are accessible
• It communicates with the server in a non request specific manner
Http Request and Response
            Structure
• HTTP is a stateless protocol.
• Server does not have the overhead of tracking client
  connections.
• HTTP transactions are either a request or response.
• Servlet can overcome the stateless nature of HTTP by
  tracking client state using session information stored in
  URL, hidden fields or cookies.
Http Transactions
A single request or response line
  – <HTTP Method>/<document address>HTTP/
    <Version No> e.g.
  – GET /index.html HTTP/1.1
  – Response line contains an HTTP status code.
  HTTP/1.1 200 OK
  Date:……………………….GMT
  Server:
  Last-modified:
  Content-type: text/html
  Content-length:….bytes
Http Servlet Methods
•   doGet()
•   doPost()
•   doHead()
•   doDelete()
•   doOptions()
•   doPut()
•   doTrace()
•   getLastModified()
•   service()
Http Servlet Request
• getMethod()
    – Returns get/post with which request was made.
•   getQueryString()
•   getRemoteUser()
•   getRequestSessionId()
•   getSession(boolean)
    – If FALSE returns current valid session otherwise
      creates a new session.
• isRequestedSessionIdValid()
• getCookies()
Http Servlet Response

• addCookie(Cookie)
  – Add cookie to response
• encodeUrl(String)
• sendRedirect(String)
• sendError(int)
Thread Safety
• Multithreaded = one servlet, multiple
  requests simultaneously
• Thread safe – not using class variables
  since one copy of these variables is
  shared by all threads
• Synchronized code blocks , all threads
  wait until they can enter, one at a time
• Servlet 2.4 deprecates SingleThreadModel
  interface – could not resolve all potential
  threading issues.

Weitere ähnliche Inhalte

Was ist angesagt?

Developing your own OpenStack Swift middleware
Developing your own OpenStack Swift middlewareDeveloping your own OpenStack Swift middleware
Developing your own OpenStack Swift middleware
Christian Schwede
 
Automation framework123
Automation framework123Automation framework123
Automation framework123
subbusjune22
 
Security and performance designs for client-server communications
Security and performance designs for client-server communicationsSecurity and performance designs for client-server communications
Security and performance designs for client-server communications
WO Community
 
Using Node.js to Build Great Streaming Services - HTML5 Dev Conf
Using Node.js to  Build Great  Streaming Services - HTML5 Dev ConfUsing Node.js to  Build Great  Streaming Services - HTML5 Dev Conf
Using Node.js to Build Great Streaming Services - HTML5 Dev Conf
Tom Croucher
 
Enterprise Guice 20090217 Bejug
Enterprise Guice 20090217 BejugEnterprise Guice 20090217 Bejug
Enterprise Guice 20090217 Bejug
robbiev
 
10 Cool Facts about Gradle
10 Cool Facts about Gradle10 Cool Facts about Gradle
10 Cool Facts about Gradle
Evgeny Goldin
 

Was ist angesagt? (20)

Commons Pool and DBCP
Commons Pool and DBCPCommons Pool and DBCP
Commons Pool and DBCP
 
SCWCD : Thread safe servlets : CHAP : 8
SCWCD : Thread safe servlets : CHAP : 8SCWCD : Thread safe servlets : CHAP : 8
SCWCD : Thread safe servlets : CHAP : 8
 
OpenStack API's and WSGI
OpenStack API's and WSGIOpenStack API's and WSGI
OpenStack API's and WSGI
 
How to build to do app using vue composition api and vuex 4 with typescript
How to build to do app using vue composition api and vuex 4 with typescriptHow to build to do app using vue composition api and vuex 4 with typescript
How to build to do app using vue composition api and vuex 4 with typescript
 
Custom deployments with sbt-native-packager
Custom deployments with sbt-native-packagerCustom deployments with sbt-native-packager
Custom deployments with sbt-native-packager
 
Developing your own OpenStack Swift middleware
Developing your own OpenStack Swift middlewareDeveloping your own OpenStack Swift middleware
Developing your own OpenStack Swift middleware
 
Automation framework123
Automation framework123Automation framework123
Automation framework123
 
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
 
Security and performance designs for client-server communications
Security and performance designs for client-server communicationsSecurity and performance designs for client-server communications
Security and performance designs for client-server communications
 
Indic threads pune12-java ee 7 platformsimplification html5
Indic threads pune12-java ee 7 platformsimplification html5Indic threads pune12-java ee 7 platformsimplification html5
Indic threads pune12-java ee 7 platformsimplification html5
 
Kamaelia Protocol Walkthrough
Kamaelia Protocol WalkthroughKamaelia Protocol Walkthrough
Kamaelia Protocol Walkthrough
 
Using Node.js to Build Great Streaming Services - HTML5 Dev Conf
Using Node.js to  Build Great  Streaming Services - HTML5 Dev ConfUsing Node.js to  Build Great  Streaming Services - HTML5 Dev Conf
Using Node.js to Build Great Streaming Services - HTML5 Dev Conf
 
Testing Your Application On Google App Engine
Testing Your Application On Google App EngineTesting Your Application On Google App Engine
Testing Your Application On Google App Engine
 
Structured concurrency with Kotlin Coroutines
Structured concurrency with Kotlin CoroutinesStructured concurrency with Kotlin Coroutines
Structured concurrency with Kotlin Coroutines
 
Enterprise Guice 20090217 Bejug
Enterprise Guice 20090217 BejugEnterprise Guice 20090217 Bejug
Enterprise Guice 20090217 Bejug
 
10 Cool Facts about Gradle
10 Cool Facts about Gradle10 Cool Facts about Gradle
10 Cool Facts about Gradle
 
Lecture11 b
Lecture11 bLecture11 b
Lecture11 b
 
java
javajava
java
 
Bring your infrastructure under control with Infrastructor
Bring your infrastructure under control with InfrastructorBring your infrastructure under control with Infrastructor
Bring your infrastructure under control with Infrastructor
 
Understanding greenlet
Understanding greenletUnderstanding greenlet
Understanding greenlet
 

Ähnlich wie Servlets

J2EE : Java servlet and its types, environment
J2EE : Java servlet and its types, environmentJ2EE : Java servlet and its types, environment
J2EE : Java servlet and its types, environment
joearunraja2
 
Dynamic content generation
Dynamic content generationDynamic content generation
Dynamic content generation
Eleonora Ciceri
 

Ähnlich wie Servlets (20)

Java Servlets.pdf
Java Servlets.pdfJava Servlets.pdf
Java Servlets.pdf
 
SERVIET
SERVIETSERVIET
SERVIET
 
Wt unit 3 server side technology
Wt unit 3 server side technologyWt unit 3 server side technology
Wt unit 3 server side technology
 
Wt unit 3 server side technology
Wt unit 3 server side technologyWt unit 3 server side technology
Wt unit 3 server side technology
 
Servlet ppt by vikas jagtap
Servlet ppt by vikas jagtapServlet ppt by vikas jagtap
Servlet ppt by vikas jagtap
 
J2EE : Java servlet and its types, environment
J2EE : Java servlet and its types, environmentJ2EE : Java servlet and its types, environment
J2EE : Java servlet and its types, environment
 
IP UNIT III PPT.pptx
 IP UNIT III PPT.pptx IP UNIT III PPT.pptx
IP UNIT III PPT.pptx
 
Servlet life cycle
Servlet life cycleServlet life cycle
Servlet life cycle
 
servlet_lifecycle.pdf
servlet_lifecycle.pdfservlet_lifecycle.pdf
servlet_lifecycle.pdf
 
Servlet
ServletServlet
Servlet
 
Servlet lifecycle
Servlet lifecycleServlet lifecycle
Servlet lifecycle
 
Introduction tomcat7 servlet3
Introduction tomcat7 servlet3Introduction tomcat7 servlet3
Introduction tomcat7 servlet3
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 
Lecture 2
Lecture 2Lecture 2
Lecture 2
 
Servlet
Servlet Servlet
Servlet
 
Lecture 3: Servlets - Session Management
Lecture 3:  Servlets - Session ManagementLecture 3:  Servlets - Session Management
Lecture 3: Servlets - Session Management
 
JAVA Servlets
JAVA ServletsJAVA Servlets
JAVA Servlets
 
Servlet and servlet life cycle
Servlet and servlet life cycleServlet and servlet life cycle
Servlet and servlet life cycle
 
Dynamic content generation
Dynamic content generationDynamic content generation
Dynamic content generation
 
Servlets
ServletsServlets
Servlets
 

Kürzlich hochgeladen

IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
Enterprise Knowledge
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 

Kürzlich hochgeladen (20)

08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 

Servlets

  • 2. Servlet • Platform- independent Server side components , written in Java which extends the standard web server and provide a general framework for services build on the Request –Response paradigm • An Efficient and Powerful technology for creating dynamic content for the Web and fundamental part of all Java web technologies
  • 3. Servlet Container The servlet container is a part of a Web server or application server that provides the network services over which requests and responses are sent, decodes MIME- based requests, and formats MIME-based responses. A servlet container also manages servlets through their lifecycle.
  • 4.
  • 5.
  • 7. 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 gives a blueprint and makes writing servlet easier. • GenericServlet implements the log method, declared in the ServletContext interface. • To write a generic servlet, it is sufficient to override the abstract service method.
  • 8. javax.servlet.http.HttpServlet • Signature: public abstract class HttpServlet extends GenericServlet implements java.io.Serializable • HttpServlet defines a HTTP protocol specific servlet. • HttpServlet gives a blueprint for Http servlet and makes writing them easier. • HttpServlet extends the GenericServlet and hence inherits the properties GenericServlet.
  • 9. Servlet Life Cycle The Web container manages the life cycle of servlet instances New Destroyed Running init( destroy( ) ) ...( service( ) ) doGet( ) doDelete( ) doPost( doPut( ) )
  • 10. The init ( ) method • Called by the Web container when the servlet instance is first created • The Servlets specification guarantees that no requests will be processed by this servlet until the init method has completed • Override the init() method when: i) You need to create or open any servlet-specific resources that you need for processing user requests ii)You need to initialize the state of the servlet //A simple servlet lifecycle counter // int count ; public void init(ServletConfig config) throws ServletException { super.init(config); getServletContext().log("init() called"); count=0; }
  • 11. The service ( ) method • Called by the Web container to process a user request • Dispatches the HTTP requests to doGet(…), doPost(…), etc. depending on the HTTP request method (GET, POST, and so on) – Sends the result as HTTP response • Usually we do not need to override this method protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { getServletContext().log("service() called"); count++; response.getWriter().write("Incrementig the count: Count = "+count); }
  • 12. The destroy() Method • Called by the Web container when the servlet instance is being eliminated ( All threads within the servlets service method have exited (or) Time-out period have passed ) • The Servlet specification guarantees that all requests will be completely processed before this method is called • Override the destroy method when: – You need to release any servlet-specific resources that you had opened in the init() method – You need to persist the state of the servlet public void destroy() { getServletContext().log("destroy() called"); }
  • 13. servletConfig • Object of servletConfig used to pass initialization and context information to servlets • getServletConfig ( ) method allows the servlet to retrieve the object and obtain configuration at anytime • Init () method stores the servletConfig object in a private transient instance variable called config
  • 14. ServletContext • The javax.servlet.ServletContext interface provides a set of methods that the servlet can use to communicate with the web server. • The ServletContext object is contained within javax.servlet.ServletConfig Object which is provided to the servlet when it is initialized. • Define URI to name mappings • Allow Data to be shared between different servlets • Contains a servlet log • Access to global servlet config and other application servlet context are accessible • It communicates with the server in a non request specific manner
  • 15. Http Request and Response Structure • HTTP is a stateless protocol. • Server does not have the overhead of tracking client connections. • HTTP transactions are either a request or response. • Servlet can overcome the stateless nature of HTTP by tracking client state using session information stored in URL, hidden fields or cookies.
  • 16. Http Transactions A single request or response line – <HTTP Method>/<document address>HTTP/ <Version No> e.g. – GET /index.html HTTP/1.1 – Response line contains an HTTP status code. HTTP/1.1 200 OK Date:……………………….GMT Server: Last-modified: Content-type: text/html Content-length:….bytes
  • 17. Http Servlet Methods • doGet() • doPost() • doHead() • doDelete() • doOptions() • doPut() • doTrace() • getLastModified() • service()
  • 18. Http Servlet Request • getMethod() – Returns get/post with which request was made. • getQueryString() • getRemoteUser() • getRequestSessionId() • getSession(boolean) – If FALSE returns current valid session otherwise creates a new session. • isRequestedSessionIdValid() • getCookies()
  • 19. Http Servlet Response • addCookie(Cookie) – Add cookie to response • encodeUrl(String) • sendRedirect(String) • sendError(int)
  • 20. Thread Safety • Multithreaded = one servlet, multiple requests simultaneously • Thread safe – not using class variables since one copy of these variables is shared by all threads • Synchronized code blocks , all threads wait until they can enter, one at a time • Servlet 2.4 deprecates SingleThreadModel interface – could not resolve all potential threading issues.