Servlets lecture2


Published on

Published in: Technology, Education
1 Like
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Servlets lecture2

  1. 1. CS3002 Lecture 10 / Slide 1 CS3002 Software Technologies Lecture 10
  2. 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. 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. 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. 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. 6. CS3002 Lecture 10 / Slide 6 Error Handling Ex: ErrorHandlingServlet ErrorHandlingServletForm.html 404.html
  7. 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. 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. 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. 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. 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. 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. 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. 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. 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. 16. CS3002 Lecture 10 / Slide 16 Configuring Exception Pages Ex: ExceptionPage.html
  17. 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. 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. 19. CS3002 Lecture 10 / Slide 19 Cookies Ex: CookieServlet CookieServletForm.html Ex:ReadCookieServlet
  20. 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. 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. 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. 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. 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. 25. CS3002 Lecture 10 / Slide 25 Hidden Fields Ex: HiddenFieldServlet HiddenFieldServletForm.html Ex: WelcomeHiddenFieldServlet HelloHiddenFieldServlet
  26. 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. 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. 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. 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. 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. 31. CS3002 Lecture 10 / Slide 31 The HttpSession interface Ex: SessionTrackingServlet
  32. 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. 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. 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. 35. CS3002 Lecture 10 / Slide 35 URL Rewriting Ex: URLRewritingServletForm.html URLRewritingServlet Ex: WelcomeURLRewritingServlet HelloURLRewritingSerlvet
  36. 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. 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. 38. CS3002 Lecture 10 / Slide 38 Redirecting a URL Ex: Login.html SetSessionServlet RedirectTestServlet
  39. 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. 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. 41. CS3002 Lecture 10 / Slide 41 Forwarding a Request Ex: BusinessLogicServletForm.html BusinessLogicServlet PresentationServlet
  42. 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. 43. CS3002 Lecture 10 / Slide 43 Including a Request Ex: IncludeTestServlet IncludeMeServlet
  44. 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. 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. 46. CS3002 Lecture 10 / Slide 46 HTTP Tunneling Ex: TunnelServlet TunnelServletClient Ex: TunnelObjectServlet TunnelObjectServletClient
  47. 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. 48. CS3002 Lecture 10 / Slide 48 JDBC Ex: EmployeeServlet
  49. 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. 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. 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