Servlets


       AboutMe        MyCurrentLocation        Blog      GuestBook         Story of a Techie cum fighter in the Real World      HOME

Golden Rule : Servlets are suitable for coding the Business Layer of the Application and were basically made for Java Programmers

The General definition of Servlets is that they are bits of HTML included in Java Code.

<!-- ===============How to Deploy a Servlet=================== -->

<!-- ==================Request Headers=================== -->

The Request Header contain the client side information that may be useful for the web server to generate a response.Request Headers are directly sent by the browser and are send immediately following the GET or POST request line. The request contains the headers Host, Accept, Accept-Encoding, Cookie, Connection, Host, Referrer , User-Agent etc.

It is possible for a Developer to write a servlet which can access the Headers of the HTTP request.This can be done using some methods of the HttpServletRequest interface.These methods are getHeader(),getHeaderNames and getHeaders().

The Code written below prints the various Headers.Since i have used System.out.println the servlet will not print the headers on the page you see after deploying the servlet. You can see the O/P in the Servlet container Logs.Since i am using tomcat i could see the details of the headers in the stdout.log files...

CODE: 

package com.header;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
public class HeaderServlet extends HttpServlet {
    public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{
        response.setContentType("text/html");
        Enumeration e = request.getHeaderNames();
        //getHeaderNames() returns an enumeration of all the headernames this request contains
        while(e.hasMoreElements()){
            String h = (String)e.nextElement();
            //casting boolean type to a String
            Enumeration hval = request.getHeaders(h);
            while(hval.hasMoreElements()){
                System.out.println("Header : " +(String)hval.nextElement());
            }
        }
    }
}

Output

Header : localhost:8080
Header : Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.12) Gecko/20080219 Firefox/2.0.0.12 Navigator/9.0.0.6
Header : text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5
Header : en-us
Header : gzip,deflate
Header : ISO-8859-1,utf-8;q=0.7,*;q=0.7
Header : 300
Header : keep-alive
Header : max-age=0
Header : localhost:8080
Header : Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.12) Gecko/20080219 Firefox/2.0.0.12 Navigator/9.0.0.6
Header : text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5
Header : en-us
Header : gzip,deflate
Header : ISO-8859-1,utf-8;q=0.7,*;q=0.7
Header : 300
Header : keep-alive
Header : max-age=0

<!--===============Servlet Context==================-->

The servlet context defines the servlet's view of the web application within which the servlet is running.
The servlet context also allows access to resources available to it.
Always remember there is only one instance of ServletContext interface  associated with each web appplication deployed into a container.

<!-- =============Context Attributes===============-->
A servlet can bind a object into the context by name.
Any object bound to the context is available to any other servlet that is part of the same web application.
The methods of ServletContext interface that provide this functionality are setAttribute(),getAttribute(), removeAttribute() and getAttributeNames().

<!-- ==============Session Tracking and URL rewriting============= -->
 

These are two basic mechanisms of session tracking namely URL rewriting and Cookies.You can read about them in the corresponding sections.However before that you need to have some basic info about session methods.

1. getSession() :Returns the current session associated with the request or if the request does ot have a session creates one.
2. getSession(boolean tell) : Returns the current HttpSession associated with the request and returns a new session if in case the value of tell is true.
HttpSession session = request.getSession();
Say this and the Container Kicks Everything in Action

Another method of doing it is by the Listner Interface
public void sessionCreated(HttpSessionEvent event){
    HttpSession session = event.getSession();
    //Other Codent is in seconds as opposed to minutes
}

<!-- =======URL rewriting ======== -->

URL rewriting is done when cookies in the browser are disabled or the client doesn't accept an cookie.In it session id is encoded as a path parameter in the resultant URL string.The name of the parameter must be jsesionid.
For e.g http://www.guideofgreatness.com/catalog/index.html;jsessionid=1904To obtain a session object use HttpServletRequest Interface's method .
We make use of this if cookies are disabled.
URL rewriting adds the session ID at the end of all the URLs in the HTML you write to the response.
URL rewriting will happen automatically if cookies don't work with the client ,but you jave to explicitly encode all the URLs you write.
Note: URL encoding is all about response.You should always call it on a HttpResponse Object
To Encode a URL call response.encodeURL(aString)
    out.println("<a href=\"" +response.encodeURL("/beerTest.do"));
   
There is no way to get URL rewriting with static pages , so if you depend on sessions , you must use dynamically generated pages.

Two major methods 1. encodeURL(PASS URL AS ARGUMENT)  2. encodeRedirectURL(PASS URL AS ARGUMENT)

Key HttpSession Methods :
getCreationTime(), getLastAccessedTime(), getMaxInactiveInterval(), setMaxInactiveInterval(), invalidate()

There are 3 ways a session can die:
1.It times out  2.You cal the invalidate() method on session object        3.The application crashes or is undeployed

You can set the session in the Deployment Descriptor web.xml
<web-app>
    <session-config>
        <session-timeout>15</session-timeout>           Note: TheTime mentioned here is in minutes.In this case it is 15minutes
    </session-config>
</web-app>

If you want to change the session timeout for a particular session instance without affecting the other apps
You can do it by saying session.setMaxInactiveInterval(20*60)
But remember the time mentioned here in the arguments is in seconds as opposed to minutes in deployment descriptor

Always Remember : You cannot call any method on a session object once it has been invalidated :It will alwats result in a runtime exception .To be more precise the exception will be IllegalStateException


                                    <!-- =======COOKIES======== -->
A cookie is some information that the web server sends to the browser which is accepted and stored by the browser.The class Cookie in the package javax.servlet.http will help to create a cookie.The name and values of Cookies are stored on the client machine.Some of the information that is stored includes the cookie's name, value, Expiration date and path.Have a look at a cookie stored in Mozilla Firefox Browser

 

You can get cookie-related Headers outof the HTTP request and response , but DON'T.
Everything you need to do with cookies has been encapsulated in HttpServletRequest, HttpServletResponse and Cookie API's. 

API for Placing Cookies in the Response Headers
        – Method in HttpServletResponse –  void addCookie(Cookie cookie)
• API for Reading Cookies from the Client
        – Method in HttpServletRequest –    Cookies[] getCookies()

Note: There is no getCookie() method. You can only get cookies in a cookie array and then you have to loop over the array to find the one you want

Cookie cookie = new Cookie("username",name);
coookie.setmaxAge(30*60);
//Stay alive for the client for 30 minutes.The time is defined in minutes
reponse.addCookie(cookie);
//Sending cokie to the client

//Geting the cookie from client request

Cookie [] cookies = request.getCookies();
for(int i=0;i<cookies.length;i++){
    Cookie cookie = cookies[i];
    if(cookie.getname().equals("username")) {
        String username = cookie.getValue();
        out.println("Hi : " +username);
        break;
    }
}
 

<!-- =======Connection Pooling in Servlets ======== -->


One of the Biggest challenges in developing a Java Application is the Performance criteria. A database connection is a very costly resource .So it doesn't make sense to hit the database every time we need to perform an operation on the Database.So in order to deal with this what we do is that instead of using a Connection Pool for every servlet we place the Connection Pool as an Application Object which allows all servlets and JSPs to share the connection pool whenever required.

Must Read for enhancing knowledge about Connection Pooling 


<!-- =======Servlet Filters ======== -->
Filters are a server plug-in that work with any servlet container compliant with version 2.3 or later of servlet specification.Filters can be chained and plugged in to the system during deployment time.Examples that have been identified for design are :
 
1) Authentication Filters
2) Logging and Auditing Filters
3) Image conversion Filters
4) Data compression Filters
5) Encryption Filters
6) Tokenizing Filters
7) Filters that trigger resource access events
8) XSL/T filters
9) Mime-type chain Filter
 
To create a Filter the Developer must implement the javax.servlet.Filter interface and a public constructor taking no arguments.The filter is declared in the deployment descriptor and is to be instantiated just like a servlet through its init() method.Only one instance of Filter is instantiated per JVM.