Search This Blog

Servlet 2.0 for Interview

 Concepts :
  •       Error/exception handing in Servlet
  •       Session tracking in Servlet
  •       Redirecting, forwarding and including requests in servlets
  •       HTTP Tunneling using servlets
  •       JDBC with servlets
Error Handling
    When a servlet comes across an Error or Exception, the following things are to be done
  •   Make sure that it contains 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 Error Handling.
  •  The Error can also be logged in a log file using the log method of GenericServlet
  •  The log file can be found in a CATALINA_HOME\logs
  •  The name of the log file can be specified in server.xml
configuring errorpages
  •     we can configuring the web application using web.xml to customize an error page
  •     Now,404.html will be displayed whenever the status code is 404
Exception handling
  •     Any exception than 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
  •     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 and the destroy method cannot throw any exception
  •     Any other  Exception is to be handled by the servlet  itself
ServletException
  •    If we want the container handle other exceptions as well, the servlet may catch the actual exception and throw ServletException in turn
  •    Now , the container can catch this exception and handle it 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
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 from sometime 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 unavailable Exception which is a subclass of ServletException will help the programmer to communicate these to the container
  •     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
  •    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
UnavailableException
  •     If the servlet is throwing a temporary UnavailableException from the serice method , the container will handle further requests using SC_SERVICE_UNAVAILABLE(503) STATUS CODE TILL Servlet is available
  •     The methods is permanent() and getUnavailableseconds() of UnavailableException can be used by the container to check whether the Servlet is unavailable permenantly and if not the duration of unavailability
  •     If the Servlet is throwing a temporary unavailable exception from the init method the container will handle it just like it handles a permenant UnavailableException by trying to create a new instance of the Servlet for handling further requests
Configuring Exception pages
  •     Just like error pages, we can configuring Exception pages also to generate customized messages
  •     Now, ExceptionPages.html will be displayed, whenever ServletException is thrown by the Servlet

 Configuring Exception pages
Can you answer these questions?
  •     How can we handled errors in Servlets?
  •     How can we handled Exceptions in Servlets?
  •     What is the importance of ServletExceptionclasss?
  •     How can Servlet throw permanent and temporary unavailableException?
  •     How does the container handle permanent and temporary unavailableException?

Cookies
  •     A cookies is some information the web server sends to the browser
  •     The browser will accept this information and stores it
  •     The 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 cookies has a constructor that takes two String objects as parameters – name and value
Cookies Methods :
  •     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 method 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 cookies and so this may not work in all cases
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
Sessions Tracking
  •     A session starts, whenever a client accesses any one page in the application
  •     A session will end, if the client accesses any one page in the application
  •     By calling appropriate methods, the programmer can also end the session when the client logs out
  •     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 session, the web server has to take care of that
  •     There are several ways in which a web server can track sessions
Cookies and Session
  •     Cookies can be used for session tracking
  •     The server can store some information regarding the sessions, 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

Hidden Fields
  •     Hidden fields that store some information regarding the 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 seesion
  •     The disadvantage is that it work only for forms
Authentication
  •     HTTP provide 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
  •     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 ailable to Servlet through the method getRemoteUser() of HttpServletRequest
  • The Servlet can use this name to track the session
    But using authentication to solve some security issues, we do not have to think about any other session tracking mechansims

The HTTPSession interface
  •     Each web servers will have an internal mechanism for tracking sessions that would relieve the web application developer from some tasks in sessions tracking
  •     Mostly webservers 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
  •     HTTPSession makes session tracking vary easy
  •     The servlet programmer need not be bothered about the internal mechanism used by the webserver, as HTTPSession standardizes the way in which Servlet talks to the webserver for session tracking
  •     The getSessionmethodofHttpServletRequest will return HttpSession object for the current session
  •     The method getID() will return a unique String that will 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
  •     The method setMaxInactiveInterval(int) can be used to specify the time inseconds between the client requests before the sessions 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 usually called when the clients logs out
URL Rewriting
  •     If the server is internally using a Cookie for session tracking, HttpSession 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
  •     The method encodeURL(String url) of HttpServletResponse will return a re-written URL that contains some sessions information also
    For example, encodeURL(HelloWorldServlet) may return the following string
-    HelloWorldServlet;jsessionid=86106952376F852D6D206E0FB87E6571
    The unique value of the attached URL parameter jsessionid will be used for session tracking
    The disadvantage of URL rewriting is that each URL should be rewritten

Can you answer these questions?
    What is Session Tracking and why is it required?
    What are the different techniques used for tracking sessions in Servlets and what are the pros and cons of each of them?
-    Writing a cookie into the client’s machine
-    Reading a cookie from the client’s machine
-    Session tracking
-    Storing attributes in a session object
-    Retrieving attributes from a session object

Redirecting a Request
    A servlet can be 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
Redirecting a Request
    The method sendRequest(String url) of HttpServletResponse will redirect the client to the specified URL
    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

Redirected a URL
Forwarding a Request
  •     A Request can also be forwarded to another URL
  •     Unlike Redirect, the client will never know about the Redirection
  •     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 th first Servlet can be retrieved by the second Servlet using the getAttribute(String name) method of HttpServletRequest

Forwarding a Request
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
  •     Including a Request
Can you answer these answers?
    What are the different ways in which Servlets communication with each other?
    When do we Redirect, Forward or Include?

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
  •     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 side with the help of Input/Output Streams
  •     A Java Object that is Serializable also can be transferred to the client side using HTTP Tunneling
Can you answer these questions?    Why is HTTP Tunneling required?
    How can we do HTTP Tunneling required?
    How can we do HTTP Tunneling using Servlets?

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 employees from the emp table of Oracle
-    In which method will you open the connection?
-    In which method will you execute the query?
-    In which method will you close the connection?

JDBC Transactions
  • A simple web applications 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
  • The model in the previous example will not work here
  • Connection Pooling
  •  In such cases, 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, a different Connection object is available for each client
  • This technique is called Connection Pooling
Can you answer these questions?
    How do we decide the responsibilities of the methods in Servlet while using a JDBC connection?
    What are the advantages and disadvantages of using the same Connection object for all the requests?
    How can we use different Connection objects for each request and at the same time ensure good performance?
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

1 comment: