SlideShare una empresa de Scribd logo
1 de 51
Descargar para leer sin conexión
CS3002
Lecture 10 / Slide 1




                              CS3002
                       Software Technologies
                            Lecture 10
CS3002
Lecture 10 / Slide 2




   Agenda
       Error/Exception Handling in Servlets
       Session Tracking in Servlets
       Redirecting, Forwarding and Including Requests in
       Servlets
       HTTP Tunneling using Servlets
       JDBC with Servlets
CS3002
Lecture 10 / Slide 3




   Error Handling
       When a Servlet comes across an Error or Exception,
       the following things are to be done
            Make sure that it causes minimum harm to the server
            Report to the client
            Log it in a log file for the server administrator
       Reporting to the client can be done using the
       sendError() method of HttpServletResponse
CS3002
Lecture 10 / Slide 4




   Error Handling - logging
        The error can also be logged in a log file using the log
        method of GenericServlet
        The log file can be found in CATALINA_HOMElogs
        The name of the log file can be specified in server.xml
        Eg:
        Log file :-
        C:Program FilesApache Software FoundationTomcat
        6.0logslocalhost.<date>.log
        date:-2009-03-12
CS3002
Lecture 10 / Slide 5




   Configuring Error Pages
       We can configure the web application using web.xml
       to customize an error page
           <error-
           <error-page>
                     <error-
                     <error-code>
                         404
                     </error-
                     </error-code>
                     <location>
                         /404.html
                     </location>
           </error-
           </error-page>

       Now, 404.html will be displayed whenever the status
       code is 404
CS3002
Lecture 10 / Slide 6




   Error Handling
      Ex: ErrorHandlingServlet
      ErrorHandlingServletForm.html
      404.html
CS3002
Lecture 10 / Slide 7




   Exception Handling
        Any exception that is thrown by the Servlet and not
        handled by itself will be handled by its container
        The container handles the exception in a container
        specific way
        Servlets that are designed to work on multiple
        containers cannot depend on this
        Such Servlets require their own exception handling
        techniques
CS3002
Lecture 10 / Slide 8




   Exception Handling
       However, Servlets can propagate only ServletException,
       IOException and unchecked exceptions to the container
       because of the way in which the methods are declared
       The service method can throw ServletException and
       IOException,
       The init method can throw ServletException
       The destroy method cannot throw any exception
       Any other exception is to be handled by the Servlet itself
CS3002
Lecture 10 / Slide 9




   ServletException
       If we want the container to handle other exceptions as
       well, the Servlet may catch the actual exception and
       throw ServletException in turn


               try{
                       //Some statements
               }
               catch(IOException exception){
                                ServletException();
                      throw new ServletException();
               }
CS3002
Lecture 10 / Slide 10




   ServletException
      The class ServletException is having a method
      getRootCause() that returns a Throwable object that will
      tell the container the root cause of the ServletException
      For example, in the above code snippet, IOException is
      the root cause
CS3002
Lecture 10 / Slide 11


   UnavailableException
       A Servlet may be unavailable permanently or temporarily
       Servlets that cannot recover from an error are
       permanently unavailable
       Servlets that cannot handle the requests for some time, for
       example due to insufficient disk space, can continue
       giving service once the administrator has cleared some
       disk space
       Such Servlets are temporarily unavailable
       The class UnavailableException which is a sub class of
       ServletException will help the programmer to
       communicate these to the container
CS3002
Lecture 10 / Slide 12




   UnavailableException
       The class UnavailableException has two constructors
       The one-argument constructor
       UnavailableException(String message) is used to create
       a permanent UnavailableException, where message is
       the explanation
       The two-argument constructor
       UnavailableException(String message, int seconds) is
       used to create a temporary UnavailableException,
       where message is the explanation and seconds is the
       estimated number of seconds, the Servlet is unavailable
CS3002
Lecture 10 / Slide 13


  UnavailableException
    If the unavailable time cannot be estimated, usually a
    positive integer is given
    If the Servlet is throwing a permanent
    UnavailableException from the init or service method, the
    container will try to create a new instance of the Servlet to
    handle further requests as the current object will be
    permanently unavailable
    If the attempt to create a new instance fails, the client will
    get an error message
CS3002
Lecture 10 / Slide 14


   UnavailableException
     If the Servlet is throwing a temporary UnavailableException from
     the service method, the container will handle further requests using
     SC_SERVICE_UNAVAILABLE (503) status code till the Servlet
     is available
     The methods isPermanent() and getUnavailableSeconds() of
     UnavailableException can be used by the container to check
     whether the Servlet is unavailable permanently and if not, the
     duration of unavailability
     If the Servlet is throwing a temporary UnavailableException from
     the init method, the container will handle it just like it handles a
     permanent UnavailableException by trying to create a new instance
     of the Servlet for handling further requests
CS3002
Lecture 10 / Slide 15


   Configuring Exception Pages
            Just like error pages, we can configure Exception
            pages also to generate customized messages
              <error-page>
               error-
                 <exception-
                 <exception-type>
                     javax.servlet.ServletException
                 </exception-
                 </exception-type>
                 <location>
                     /ExceptionPage.html
                 </location>
              </error
                error-
              </error-page>




            Now, ExceptionPage.html will be displayed,
            whenever ServletException is thrown by the
            Servlet
CS3002
Lecture 10 / Slide 16




   Configuring Exception Pages
       Ex: ExceptionHandlingSerlvet.java
       ExceptionPage.html
CS3002
Lecture 10 / Slide 17


   Cookies
       A cookie is some information the web server sends to
       the browser
       The browser will accept this information and stores it
       This information can be read back later by the web
       server
       The class Cookie in the package javax.servlet.http will
       help to create a cookie
       The class Cookie has a constructor that takes two
       String objects as parameters – name and value

              Cookie c = new Cookie(“UserName”, “abc”);
                             Cookie(“UserName”   abc”
CS3002
Lecture 10 / Slide 18


   Cookies
    The method addCookie(Cookie) of HttpServletResponse
    can be used to add a Cookie
    The method getCookies() of HttpServletRequest will return
    an array of Cookies that were stored earlier by this domain
    The methods getName() and getValue() of the Cookie class
    can be used to get the name and value of the Cookie
    The method setMaxAge(int) can be used to specify the
    maximum age of a Cookie in seconds
    By default, a Cookie will be deleted when the browser is
    closed
    Any how, some browsers may not support Cookies or want
    to block Cookies and so this may not work in all cases
CS3002
Lecture 10 / Slide 19




   Cookies
       Ex: CookieServlet
       CookieServletForm.html



       Ex:ReadCookieServlet
CS3002
Lecture 10 / Slide 20




   Sessions
      HTTP is a stateless protocol - All by itself, a request will
      not tell the server which client is making the request
      In some cases, a Servlet may want to know the specific
      client that asks for a service
      When a Servlet that takes care of an online shopping site
      gets a request for adding an item to the shopping cart, it
      should know which client is asking for the item
      From the time of accessing any one page in the
      application, till logging out, we may want to know the
      requests made by a client
      This is called Session Tracking
CS3002
Lecture 10 / Slide 21




   Session Tracking
       A session starts, whenever a client accesses any one
       page in the application
       A session will end, if the client is not responding for a
       predefined period of time
       By calling appropriate methods, the programmer can
       also end the session when the client logs out
CS3002
Lecture 10 / Slide 22




   Session Tracking
       In session tracking whenever a client sends a request to the
       server then server creates a unique id for that request and sends
       back the unique id to the client along with the response object,
       now whenever a client sends a request to the server it also sends
       a unique id with it so that the server can know from where the
       request is coming.
       After the end of a session, if the client accesses a page in the
       application again, it will be considered as a new session
       Since the protocol by itself is not tracking the sessions, the web
       server has to take care of that
       There are several ways in which a web server can track sessions
CS3002
Lecture 10 / Slide 23




   Cookies
       Cookies can be used for session tracking
       The server can store some information regarding the
       session, like the user name, in a cookie and this can be
       used to identify a request from a particular client
       But this technique may not work always, as the client
       can disable cookies in her machine
CS3002
Lecture 10 / Slide 24




   Hidden Fields
       Hidden fields that store some information about a
       session can be used in the FORM tags
       Since the field is hidden, the user will not see it on the
       screen
       But when the form is submitted, the server will get this
       information and can track the session
       The disadvantage is that it will work only for forms
CS3002
Lecture 10 / Slide 25




   Hidden Fields
       Ex: HiddenFieldServlet
       HiddenFieldServletForm.html



       Ex: WelcomeHiddenFieldServlet
       HelloHiddenFieldServlet
CS3002
Lecture 10 / Slide 26




   Authentication
       HTTP provides built in authentication support for
       taking care of the security issues
       Some resources can be protected with the help of
       authentication
       This can be used for session tracking also
       We can configure the server to use Authentication
       So the user will be asked to login with a username and
       password
CS3002
Lecture 10 / Slide 27




   Authentication
       Once the user has logged in, the browser will
       automatically send the username and password to all
       other pages of the site the user visits
       The user name is available to Servlet through the
       method getRemoteUser() of HttpServletRequest
       The Servlet can use this name to track the Session
       But using authentication just for session tracking is not
       a good idea
       If we are using authentication to solve some security
       issues, we do not have to think about any other session
       tracking mechanisms
CS3002
Lecture 10 / Slide 28




   The HttpSession interface
       Each web server will have an internal mechanism for
       tracking sessions that would relieve the web
       application developer from some tasks in session
       tracking
       Mostly web servers depend on Cookies for session
       tracking
       Servlet API has an interface called HttpSession,
       through which a Servlet can communicate with the web
       server for finding the details of a session
CS3002
Lecture 10 / Slide 29




   The HttpSession interface
       HttpSession makes session tracking very easy
       The Servlet programmer need not be bothered about
       the internal mechanism used by the web server, as
       HttpSession standardizes the way in which Servlet
       talks to the web server for session tracking
       The getSession() method of HttpServletRequest will
       return HttpSession object for the current session
CS3002
Lecture 10 / Slide 30




   The HttpSession interface
       The method getID() will return a unique String that
       will can be used for identifying a session
       The method setAttribute(String, Object) will help to
       store any Object that is represented by a String name as
       a session data
       The method getAttribute(String) will return the Object
       stored using the setAttribute method
CS3002
Lecture 10 / Slide 31




   The HttpSession interface
       Ex: SessionTrackingServlet
CS3002
Lecture 10 / Slide 32




   The HttpSession interface
       The method setMaxInactiveInterval(int) can be used to
       specify the time in seconds between the client requests
       before the session is invalidated
       If a negative number is passed to the method
       setMaxInactiveInterval, the session will never time out
       The method getMaxInactiveInterval() can be used to
       get the interval set by setMaxInactiveInterval
       The method invalidate() is used to invalidate a session
       and is usually called when the client logs out
CS3002
Lecture 10 / Slide 33




   URL Rewriting
       If the server is internally using a Cookie for session
       tracking, application will not work properly with a
       browser where Cookies are disabled
       URL rewriting is another way in which we can
       implement session tracking
       The URL for a page is rewritten to include some
       information about the session
       Thus some information can be passed to all the pages
       in an application to track the session
CS3002
Lecture 10 / Slide 34


    URL Rewriting
      The method encodeURL(String url) of
      HttpServletResponse will return a re-written URL that
      contains some session information also
      For example, encodeURL(HelloWorldServlet) may
      return the following string

           HelloWorldServlet;jsessionid=86106952376F852D6D206E0
           FB87E6571
      The unique value of the attached URLParameter
      jsessionid will be used for session tracking
      The disadvantage of URL rewriting is that each URL
      should be rewritten
CS3002
Lecture 10 / Slide 35




   URL Rewriting
       Ex: URLRewritingServletForm.html
       URLRewritingServlet



       Ex: WelcomeURLRewritingServlet
       HelloURLRewritingSerlvet
CS3002
Lecture 10 / Slide 36




   Redirecting a Request
       A Servlet can redirect a client to use another URL
       This may be done in the following cases
            if the page has moved
            for load balancing
            if the user comes to a wrong page violating a sequence
            required by the business logic
            for redirecting the client to a customized error page
CS3002
Lecture 10 / Slide 37




   Redirecting a Request
       The method sendRedirect(String url) of HttpServletResponse will redirect the
       client to the specified URL
       When we want that someone else (other servlet or jsp)should handle the
       response of our servlet, then there we should use sendRedirect() method.
       The servlet sends the status code to the browser
       Again the browser makes a new request, but with the name of that servlet
       which can now handle the request and the result will be displayed to you by
       the browser. The URL will have the address of the new servlet.
       The method encodeRedirectURL(String url) will rewrite the URL to include
       the session information also, in case cookies are disabled in the client
       So, the URL that is to be redirected should always pass through the
       encodeRedirectURL method
CS3002
Lecture 10 / Slide 38




   Redirecting a URL
       Ex: Login.html
       SetSessionServlet
       RedirectTestServlet
CS3002
Lecture 10 / Slide 39




   Forwarding a Request
       A request can also be forwarded to another URL
       Unlike Redirect, the client will never know about the
       redirection
       Ex: ForwardTestServlet

       RequestDispatcher requestDispatcher =
       request.getRequestDispatcher("PresentationServlet");
       requestDispatcher.forward(request,response);
CS3002
Lecture 10 / Slide 40


    Forwarding a Request
       Forwarding is used when two or more Servlets share
       some work
       One Servlet can do some processing, store the result in
       an Object and store it as an attribute of the request
       object using the setAttribute(String name, Object
       object) method of HttpServletRequest
       This Servlet can forward the request to the second
       Servlet
       As both of them are using the same request object, the
       attribute set by the first Servlet can be retrieved by the
       second Servlet using the getAttribute(String name)
       method of HttpServletRequest
CS3002
Lecture 10 / Slide 41




   Forwarding a Request
       Ex: BusinessLogicServletForm.html
       BusinessLogicServlet
       PresentationServlet
CS3002
Lecture 10 / Slide 42




   Including a Request
       A Servlet can include the output of another Servlet in
       its response
       Unlike forward, the calling Servlet retains the control
       and can write into the response before and after the
       output of the called Servlet
       RequestDispatcher requestDispatcher =
       request.getRequestDispatcher("IncludeMeServlet");
       requestDispatcher.include(request, response);
CS3002
Lecture 10 / Slide 43




   Including a Request
      Ex: IncludeTestServlet
      IncludeMeServlet
CS3002
Lecture 10 / Slide 44




   HTTP Tunneling
       Most of the corporate networks will be protected
       behind a firewall
       The client will be able to directly contact only the
       firewall
       The firewall will most often block the ftp access
       Usually the only exposed port will be 80 and
       acceptable protocol will be HTTP
       This would prevent even a legitimate user from
       accessing other services like ftp for transferring data
CS3002
Lecture 10 / Slide 45




   HTTP Tunneling
       HTTP Tunneling is a technique to overcome this
       difficulty
       Transferring bytes of data using the HTTP protocol
       through port number 80 is called HTTP Tunneling
       A Servlet can be programmed to read/write bytes of
       data from/to the client with the help of Input/Output
       Streams
       A Java Object that is Serializable also can be
       transferred to the client side using HTTP Tunneling
CS3002
Lecture 10 / Slide 46




   HTTP Tunneling
       Ex: TunnelServlet
       TunnelServletClient

       Ex: TunnelObjectServlet
       TunnelObjectServletClient
CS3002
Lecture 10 / Slide 47




   JDBC
       Most of the web applications require a database
       connection
       Servlets can make JDBC connections and access a
       database
       Assume a Servlet that should display the names of all
       customers from the customer table of MySql test
       database
            In which method will you open the connection?
            In which method will you execute the query?
            In which method will you close the connection?
CS3002
Lecture 10 / Slide 48




   JDBC
       Ex: EmployeeServlet
CS3002
Lecture 10 / Slide 49




   Transactions
             A simple web application can follow the previous
             model
             In some web applications, we may want to do
             some atomic transactions
             On success, we want to commit or else rollback
              try{
                        connection.setAutoCommit(false);
                        connection.setAutoCommit(false);
                        //Transactions
                        connection.commit();
                        connection.commit();
                  }
                  catch(Exception exception){
                       connection.rollback()
                       connection.rollback()
                  }


             The model in the previous example will not work
             here
CS3002
Lecture 10 / Slide 50


   Connection Pooling
       We require separate Connection objects for each client
       which are created, opened, used and closed in the
       service method itself
       Since opening a connection for each client is time
       consuming, it is better to have a pool of open
       connections from which we can pick a free connection
       object for each client
       This will increase the performance, as a new
       Connection object is not created and opened for each
       request, and at the same time, a different Connection
       object is available for each client
       This technique is called Connection Pooling
CS3002
Lecture 10 / Slide 51




   Summary
       In this module, we have learned the following
            Error/Exception Handling in Servlets
            Session Tracking in Servlets
            Redirecting Forwarding and Including Requests in Servlets
            HTTP Tunneling using Servlets
            JDBC with Servlets

Más contenido relacionado

Similar a Servlets lecture2

Similar a Servlets lecture2 (20)

Servlet session 2
Servlet   session 2Servlet   session 2
Servlet session 2
 
LIFE CYCLE OF SERVLET
LIFE CYCLE OF SERVLETLIFE CYCLE OF SERVLET
LIFE CYCLE OF SERVLET
 
UNIT-3 Servlet
UNIT-3 ServletUNIT-3 Servlet
UNIT-3 Servlet
 
IP UNIT III PPT.pptx
 IP UNIT III PPT.pptx IP UNIT III PPT.pptx
IP UNIT III PPT.pptx
 
servlet 2.5 & JSP 2.0
servlet 2.5 & JSP 2.0servlet 2.5 & JSP 2.0
servlet 2.5 & JSP 2.0
 
J2ee servlet
J2ee servletJ2ee servlet
J2ee servlet
 
WEB TECHNOLOGIES Servlet
WEB TECHNOLOGIES ServletWEB TECHNOLOGIES Servlet
WEB TECHNOLOGIES Servlet
 
Servlet and Servlet Life Cycle
Servlet and Servlet Life CycleServlet and Servlet Life Cycle
Servlet and Servlet Life Cycle
 
Java Servlet
Java ServletJava Servlet
Java Servlet
 
J servlets
J servletsJ servlets
J servlets
 
Wt unit 3
Wt unit 3 Wt unit 3
Wt unit 3
 
Servlet 01
Servlet 01Servlet 01
Servlet 01
 
Servlets
ServletsServlets
Servlets
 
Adv java unit 4 M.Sc CS.pdf
Adv java unit 4 M.Sc CS.pdfAdv java unit 4 M.Sc CS.pdf
Adv java unit 4 M.Sc CS.pdf
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 
Mvc interview questions – deep dive jinal desai
Mvc interview questions – deep dive   jinal desaiMvc interview questions – deep dive   jinal desai
Mvc interview questions – deep dive jinal desai
 
SCWCD : Handling exceptions : CHAP : 5
SCWCD : Handling exceptions : CHAP : 5SCWCD : Handling exceptions : CHAP : 5
SCWCD : Handling exceptions : CHAP : 5
 
java Servlet technology
java Servlet technologyjava Servlet technology
java Servlet technology
 
Servletand sessiontracking
Servletand sessiontrackingServletand sessiontracking
Servletand sessiontracking
 
Creating a MVC application hello world using tomcat 90 keep.pdf
Creating a MVC application hello world using tomcat 90 keep.pdfCreating a MVC application hello world using tomcat 90 keep.pdf
Creating a MVC application hello world using tomcat 90 keep.pdf
 

Último

04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
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?Antenna Manufacturer Coco
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
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.pdfEnterprise Knowledge
 
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 WorkerThousandEyes
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
[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.pdfhans926745
 
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...Miguel Araújo
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfhans926745
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
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 SolutionsEnterprise Knowledge
 
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 2024Rafal Los
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 

Último (20)

04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
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?
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
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
 
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
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
[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...
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
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
 
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
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 

Servlets lecture2

  • 1. CS3002 Lecture 10 / Slide 1 CS3002 Software Technologies Lecture 10
  • 2. CS3002 Lecture 10 / Slide 2 Agenda Error/Exception Handling in Servlets Session Tracking in Servlets Redirecting, Forwarding and Including Requests in Servlets HTTP Tunneling using Servlets JDBC with Servlets
  • 3. CS3002 Lecture 10 / Slide 3 Error Handling When a Servlet comes across an Error or Exception, the following things are to be done Make sure that it causes minimum harm to the server Report to the client Log it in a log file for the server administrator Reporting to the client can be done using the sendError() method of HttpServletResponse
  • 4. CS3002 Lecture 10 / Slide 4 Error Handling - logging The error can also be logged in a log file using the log method of GenericServlet The log file can be found in CATALINA_HOMElogs The name of the log file can be specified in server.xml Eg: Log file :- C:Program FilesApache Software FoundationTomcat 6.0logslocalhost.<date>.log date:-2009-03-12
  • 5. CS3002 Lecture 10 / Slide 5 Configuring Error Pages We can configure the web application using web.xml to customize an error page <error- <error-page> <error- <error-code> 404 </error- </error-code> <location> /404.html </location> </error- </error-page> Now, 404.html will be displayed whenever the status code is 404
  • 6. CS3002 Lecture 10 / Slide 6 Error Handling Ex: ErrorHandlingServlet ErrorHandlingServletForm.html 404.html
  • 7. CS3002 Lecture 10 / Slide 7 Exception Handling Any exception that is thrown by the Servlet and not handled by itself will be handled by its container The container handles the exception in a container specific way Servlets that are designed to work on multiple containers cannot depend on this Such Servlets require their own exception handling techniques
  • 8. CS3002 Lecture 10 / Slide 8 Exception Handling However, Servlets can propagate only ServletException, IOException and unchecked exceptions to the container because of the way in which the methods are declared The service method can throw ServletException and IOException, The init method can throw ServletException The destroy method cannot throw any exception Any other exception is to be handled by the Servlet itself
  • 9. CS3002 Lecture 10 / Slide 9 ServletException If we want the container to handle other exceptions as well, the Servlet may catch the actual exception and throw ServletException in turn try{ //Some statements } catch(IOException exception){ ServletException(); throw new ServletException(); }
  • 10. CS3002 Lecture 10 / Slide 10 ServletException The class ServletException is having a method getRootCause() that returns a Throwable object that will tell the container the root cause of the ServletException For example, in the above code snippet, IOException is the root cause
  • 11. CS3002 Lecture 10 / Slide 11 UnavailableException A Servlet may be unavailable permanently or temporarily Servlets that cannot recover from an error are permanently unavailable Servlets that cannot handle the requests for some time, for example due to insufficient disk space, can continue giving service once the administrator has cleared some disk space Such Servlets are temporarily unavailable The class UnavailableException which is a sub class of ServletException will help the programmer to communicate these to the container
  • 12. CS3002 Lecture 10 / Slide 12 UnavailableException The class UnavailableException has two constructors The one-argument constructor UnavailableException(String message) is used to create a permanent UnavailableException, where message is the explanation The two-argument constructor UnavailableException(String message, int seconds) is used to create a temporary UnavailableException, where message is the explanation and seconds is the estimated number of seconds, the Servlet is unavailable
  • 13. CS3002 Lecture 10 / Slide 13 UnavailableException If the unavailable time cannot be estimated, usually a positive integer is given If the Servlet is throwing a permanent UnavailableException from the init or service method, the container will try to create a new instance of the Servlet to handle further requests as the current object will be permanently unavailable If the attempt to create a new instance fails, the client will get an error message
  • 14. CS3002 Lecture 10 / Slide 14 UnavailableException If the Servlet is throwing a temporary UnavailableException from the service method, the container will handle further requests using SC_SERVICE_UNAVAILABLE (503) status code till the Servlet is available The methods isPermanent() and getUnavailableSeconds() of UnavailableException can be used by the container to check whether the Servlet is unavailable permanently and if not, the duration of unavailability If the Servlet is throwing a temporary UnavailableException from the init method, the container will handle it just like it handles a permanent UnavailableException by trying to create a new instance of the Servlet for handling further requests
  • 15. CS3002 Lecture 10 / Slide 15 Configuring Exception Pages Just like error pages, we can configure Exception pages also to generate customized messages <error-page> error- <exception- <exception-type> javax.servlet.ServletException </exception- </exception-type> <location> /ExceptionPage.html </location> </error error- </error-page> Now, ExceptionPage.html will be displayed, whenever ServletException is thrown by the Servlet
  • 16. CS3002 Lecture 10 / Slide 16 Configuring Exception Pages Ex: ExceptionHandlingSerlvet.java ExceptionPage.html
  • 17. CS3002 Lecture 10 / Slide 17 Cookies A cookie is some information the web server sends to the browser The browser will accept this information and stores it This information can be read back later by the web server The class Cookie in the package javax.servlet.http will help to create a cookie The class Cookie has a constructor that takes two String objects as parameters – name and value Cookie c = new Cookie(“UserName”, “abc”); Cookie(“UserName” abc”
  • 18. CS3002 Lecture 10 / Slide 18 Cookies The method addCookie(Cookie) of HttpServletResponse can be used to add a Cookie The method getCookies() of HttpServletRequest will return an array of Cookies that were stored earlier by this domain The methods getName() and getValue() of the Cookie class can be used to get the name and value of the Cookie The method setMaxAge(int) can be used to specify the maximum age of a Cookie in seconds By default, a Cookie will be deleted when the browser is closed Any how, some browsers may not support Cookies or want to block Cookies and so this may not work in all cases
  • 19. CS3002 Lecture 10 / Slide 19 Cookies Ex: CookieServlet CookieServletForm.html Ex:ReadCookieServlet
  • 20. CS3002 Lecture 10 / Slide 20 Sessions HTTP is a stateless protocol - All by itself, a request will not tell the server which client is making the request In some cases, a Servlet may want to know the specific client that asks for a service When a Servlet that takes care of an online shopping site gets a request for adding an item to the shopping cart, it should know which client is asking for the item From the time of accessing any one page in the application, till logging out, we may want to know the requests made by a client This is called Session Tracking
  • 21. CS3002 Lecture 10 / Slide 21 Session Tracking A session starts, whenever a client accesses any one page in the application A session will end, if the client is not responding for a predefined period of time By calling appropriate methods, the programmer can also end the session when the client logs out
  • 22. CS3002 Lecture 10 / Slide 22 Session Tracking In session tracking whenever a client sends a request to the server then server creates a unique id for that request and sends back the unique id to the client along with the response object, now whenever a client sends a request to the server it also sends a unique id with it so that the server can know from where the request is coming. After the end of a session, if the client accesses a page in the application again, it will be considered as a new session Since the protocol by itself is not tracking the sessions, the web server has to take care of that There are several ways in which a web server can track sessions
  • 23. CS3002 Lecture 10 / Slide 23 Cookies Cookies can be used for session tracking The server can store some information regarding the session, like the user name, in a cookie and this can be used to identify a request from a particular client But this technique may not work always, as the client can disable cookies in her machine
  • 24. CS3002 Lecture 10 / Slide 24 Hidden Fields Hidden fields that store some information about a session can be used in the FORM tags Since the field is hidden, the user will not see it on the screen But when the form is submitted, the server will get this information and can track the session The disadvantage is that it will work only for forms
  • 25. CS3002 Lecture 10 / Slide 25 Hidden Fields Ex: HiddenFieldServlet HiddenFieldServletForm.html Ex: WelcomeHiddenFieldServlet HelloHiddenFieldServlet
  • 26. CS3002 Lecture 10 / Slide 26 Authentication HTTP provides built in authentication support for taking care of the security issues Some resources can be protected with the help of authentication This can be used for session tracking also We can configure the server to use Authentication So the user will be asked to login with a username and password
  • 27. CS3002 Lecture 10 / Slide 27 Authentication Once the user has logged in, the browser will automatically send the username and password to all other pages of the site the user visits The user name is available to Servlet through the method getRemoteUser() of HttpServletRequest The Servlet can use this name to track the Session But using authentication just for session tracking is not a good idea If we are using authentication to solve some security issues, we do not have to think about any other session tracking mechanisms
  • 28. CS3002 Lecture 10 / Slide 28 The HttpSession interface Each web server will have an internal mechanism for tracking sessions that would relieve the web application developer from some tasks in session tracking Mostly web servers depend on Cookies for session tracking Servlet API has an interface called HttpSession, through which a Servlet can communicate with the web server for finding the details of a session
  • 29. CS3002 Lecture 10 / Slide 29 The HttpSession interface HttpSession makes session tracking very easy The Servlet programmer need not be bothered about the internal mechanism used by the web server, as HttpSession standardizes the way in which Servlet talks to the web server for session tracking The getSession() method of HttpServletRequest will return HttpSession object for the current session
  • 30. CS3002 Lecture 10 / Slide 30 The HttpSession interface The method getID() will return a unique String that will can be used for identifying a session The method setAttribute(String, Object) will help to store any Object that is represented by a String name as a session data The method getAttribute(String) will return the Object stored using the setAttribute method
  • 31. CS3002 Lecture 10 / Slide 31 The HttpSession interface Ex: SessionTrackingServlet
  • 32. CS3002 Lecture 10 / Slide 32 The HttpSession interface The method setMaxInactiveInterval(int) can be used to specify the time in seconds between the client requests before the session is invalidated If a negative number is passed to the method setMaxInactiveInterval, the session will never time out The method getMaxInactiveInterval() can be used to get the interval set by setMaxInactiveInterval The method invalidate() is used to invalidate a session and is usually called when the client logs out
  • 33. CS3002 Lecture 10 / Slide 33 URL Rewriting If the server is internally using a Cookie for session tracking, application will not work properly with a browser where Cookies are disabled URL rewriting is another way in which we can implement session tracking The URL for a page is rewritten to include some information about the session Thus some information can be passed to all the pages in an application to track the session
  • 34. CS3002 Lecture 10 / Slide 34 URL Rewriting The method encodeURL(String url) of HttpServletResponse will return a re-written URL that contains some session information also For example, encodeURL(HelloWorldServlet) may return the following string HelloWorldServlet;jsessionid=86106952376F852D6D206E0 FB87E6571 The unique value of the attached URLParameter jsessionid will be used for session tracking The disadvantage of URL rewriting is that each URL should be rewritten
  • 35. CS3002 Lecture 10 / Slide 35 URL Rewriting Ex: URLRewritingServletForm.html URLRewritingServlet Ex: WelcomeURLRewritingServlet HelloURLRewritingSerlvet
  • 36. CS3002 Lecture 10 / Slide 36 Redirecting a Request A Servlet can redirect a client to use another URL This may be done in the following cases if the page has moved for load balancing if the user comes to a wrong page violating a sequence required by the business logic for redirecting the client to a customized error page
  • 37. CS3002 Lecture 10 / Slide 37 Redirecting a Request The method sendRedirect(String url) of HttpServletResponse will redirect the client to the specified URL When we want that someone else (other servlet or jsp)should handle the response of our servlet, then there we should use sendRedirect() method. The servlet sends the status code to the browser Again the browser makes a new request, but with the name of that servlet which can now handle the request and the result will be displayed to you by the browser. The URL will have the address of the new servlet. The method encodeRedirectURL(String url) will rewrite the URL to include the session information also, in case cookies are disabled in the client So, the URL that is to be redirected should always pass through the encodeRedirectURL method
  • 38. CS3002 Lecture 10 / Slide 38 Redirecting a URL Ex: Login.html SetSessionServlet RedirectTestServlet
  • 39. CS3002 Lecture 10 / Slide 39 Forwarding a Request A request can also be forwarded to another URL Unlike Redirect, the client will never know about the redirection Ex: ForwardTestServlet RequestDispatcher requestDispatcher = request.getRequestDispatcher("PresentationServlet"); requestDispatcher.forward(request,response);
  • 40. CS3002 Lecture 10 / Slide 40 Forwarding a Request Forwarding is used when two or more Servlets share some work One Servlet can do some processing, store the result in an Object and store it as an attribute of the request object using the setAttribute(String name, Object object) method of HttpServletRequest This Servlet can forward the request to the second Servlet As both of them are using the same request object, the attribute set by the first Servlet can be retrieved by the second Servlet using the getAttribute(String name) method of HttpServletRequest
  • 41. CS3002 Lecture 10 / Slide 41 Forwarding a Request Ex: BusinessLogicServletForm.html BusinessLogicServlet PresentationServlet
  • 42. CS3002 Lecture 10 / Slide 42 Including a Request A Servlet can include the output of another Servlet in its response Unlike forward, the calling Servlet retains the control and can write into the response before and after the output of the called Servlet RequestDispatcher requestDispatcher = request.getRequestDispatcher("IncludeMeServlet"); requestDispatcher.include(request, response);
  • 43. CS3002 Lecture 10 / Slide 43 Including a Request Ex: IncludeTestServlet IncludeMeServlet
  • 44. CS3002 Lecture 10 / Slide 44 HTTP Tunneling Most of the corporate networks will be protected behind a firewall The client will be able to directly contact only the firewall The firewall will most often block the ftp access Usually the only exposed port will be 80 and acceptable protocol will be HTTP This would prevent even a legitimate user from accessing other services like ftp for transferring data
  • 45. CS3002 Lecture 10 / Slide 45 HTTP Tunneling HTTP Tunneling is a technique to overcome this difficulty Transferring bytes of data using the HTTP protocol through port number 80 is called HTTP Tunneling A Servlet can be programmed to read/write bytes of data from/to the client with the help of Input/Output Streams A Java Object that is Serializable also can be transferred to the client side using HTTP Tunneling
  • 46. CS3002 Lecture 10 / Slide 46 HTTP Tunneling Ex: TunnelServlet TunnelServletClient Ex: TunnelObjectServlet TunnelObjectServletClient
  • 47. CS3002 Lecture 10 / Slide 47 JDBC Most of the web applications require a database connection Servlets can make JDBC connections and access a database Assume a Servlet that should display the names of all customers from the customer table of MySql test database In which method will you open the connection? In which method will you execute the query? In which method will you close the connection?
  • 48. CS3002 Lecture 10 / Slide 48 JDBC Ex: EmployeeServlet
  • 49. CS3002 Lecture 10 / Slide 49 Transactions A simple web application can follow the previous model In some web applications, we may want to do some atomic transactions On success, we want to commit or else rollback try{ connection.setAutoCommit(false); connection.setAutoCommit(false); //Transactions connection.commit(); connection.commit(); } catch(Exception exception){ connection.rollback() connection.rollback() } The model in the previous example will not work here
  • 50. CS3002 Lecture 10 / Slide 50 Connection Pooling We require separate Connection objects for each client which are created, opened, used and closed in the service method itself Since opening a connection for each client is time consuming, it is better to have a pool of open connections from which we can pick a free connection object for each client This will increase the performance, as a new Connection object is not created and opened for each request, and at the same time, a different Connection object is available for each client This technique is called Connection Pooling
  • 51. CS3002 Lecture 10 / Slide 51 Summary In this module, we have learned the following Error/Exception Handling in Servlets Session Tracking in Servlets Redirecting Forwarding and Including Requests in Servlets HTTP Tunneling using Servlets JDBC with Servlets