Friday, October 16, 2009

ServletContext and ServletConfig

ServletConfig

  • The servlet gets the init params from the ServletConfig. Each servlet has a ServletConfig object.

  • When the container initializes a servlet, it makes a unique ServletConfig object for it.

  • The servlet init params are read only once and is available only for that particular servlet.

  • The init params are given in the DD within the < servlet> tag.
 <servlet>  
 <init-param>  
 <param-name> name </param-name>  
 <param-value> val </param-value >  
 </init-param>  
 </servlet>  
  • The container first reads the DD and gets the init-params.

  • Then the container creates a new ServletConfig instance for the servlet

  • Container creates a new name/value pair of Strings for each init parameter

  • Container gives the ServletConfig reference to name/value pair

  • Container creates a instance of the servlet class

  • Container calls the init(ServletConfig) method by passing the ServletConfig reference

  • The servlet can access the init params using getServletConfig().getInitParameter("name")

    ServletContext

    The ServletContext is for the webapp. The container makes a ServletContext when a web application is deployed and makes it available to all the servlets and JSPs of that application. Context init params are available to the entire webapp. Any servlet and JSP in the app has access to the context init params. The context params are given in the DD outside the < servlet > tag.

    < web-app .... >
    < context-param >
    < param-name > name < /param-name >
    < param-value > val < /param-value >
    < /context-param >
    < servlet > < /servlet>
    < /we-app >

    The container reads the DD and creates name/value String for each context-param.
    Container creates a instance of ServletContext.
    Container gives the ServletContext reference to each name/value pair of the context params.
    Every JSPs and servlets deployed in that webapp can access this context params through the ServletContext using the method getServletContext().getInitParameter("name")

    Servlet Life Cycle

    A Servlet is controlled by the Container. The servlet has only one state - Initialized.

    1. The web container first loads the Servlet (.class file).

    2. The web container creates an instance of the Servlet by calling the constructor

    3. The web container then calls the init() method of the servlet which initializes the servlet. It is called only once

    4. The web container then calls the service() method of the servlet which in turn calls the respective doGet() or doPost() depending on the type of request. For each request, a separate thread is used.

    5. Finally the container calls the destroy() method which cleans up and make it ready for garbage collection. It is also called only once.



    Servlet classes and life cycle methods:

    javax.servlet.GenericServlet implements javax.servlet.Servlet (interface)
    javax.servelt.http.HttpServlet extends javax.servlet.GenericServlet
    MyServlet extends javax.servelt.http.HttpServlet


    The init() method of the Generic Servlet is called if it is not overriden in the MyServlet. The init() can be used to initalize the database before processing the request.
    The service() method of the HttpServlet is called. We don't need to override it.
    The service() method in HttpServlet calls the overrriden doGet() or doPost() of MyServlet.


    Note:


    • There is only one servlet instance per JVM

    • Each request runs in a separate thread.

    • Servlet is loaded and initialized only once when the container starts up.

    • init() always completes before the first call to service()

    • The constructor of the servlet class just creats an ordinary object. It becomes a servlet when it is initalized after init().

    J2EE Server

    A J2EE server incorporates web container and EJB container. The web container has the web components
    (Servlet + JSP ).
    The EJB container has the business components.

    A web server has only Web container. Apache is the web server and Tomcat is the web container
    There is no stand alone EJB containers now a days.

    J2EE servers are WebService , JBoss which has both web and EJB containers.

    How to configure Tomcat 6 in Eclipse

    Steps for configuring Tomcat 6 in Eclipse


    • Download Eclipse and extract it into a folder. (I have downloaded Eclipse-Galileo [Eclipse IDE for Java EE developers] from http://www.eclipse.org/downloads/ and extracted in into D:\Eclipse )
    • Open eclispe by double clicking eclipse.exe
    • Create a workspace
    • In windows->Preferences->server -> run time environment
    • Click add, select the Tomcat v6, click Next
    • Set the Tomcat installation directory (for me it is D:\apache-tomcat-6.0.20)
    • Set the JRE by clicking Installed JREs -> Add -> Standard VM -> set the JRE home to JDK folder (path in step 3)
    • Click finish
    • Select the newly added JRE and click Ok
    • Select the newly added JRE from the drop down of JRE and click Finish
    • At the top right corner of eclipse there is a button 'Open perspective'. Select Java EE perspective.
    • If you can't see 'Server' tab at the bottom, select Windows->show view -> server
    • In the server tab at the bottom, Right click -> New Server -> Select the Tomcat v6 and click Finish


    • If you want to run the tomcat manually from command prompt then set the environment variable JAVA_HOME to jdk path ie the path in step 3

    web container

    Web Container


    Container is something that extends the functionality of a web server.Web server cannot alone handle the dynamic pages . The container does it.Tomcat is an eg: of a container. While apache is the web server.Servlets are deployed in the Container.

    Container provides -
    communication support - we dont have to worry about creating sockets, listners, streams
    lifecycle management - it controls the life and death of servlets
    multithreading support - automatically creats a new thread when a request comes
    provides security - it has a deployment descriptor DD which is an XML which helps to manage the security with out changing java source code.
    jsp support - translates the jsp to java

    When a request for a dynamic page comes, the web server hands over it to the container and then the container does the following:

    container creates two objects - HttpServletRequest and HttpServletResponse
    finds the correct servlet based on URL, creates/allocates a thread, passes the request and response object to the servlet thread
    calls the service() method
    based on the request type the service() method calls doGet() or doPost() method
    the doXxx() method generates the dynamic pages and put it into the respose object
    thread is completed
    container converts the response to Http response and sends it to the client
    deletes the request and response objects

    URL and Port

    URL

    Uniform Resource Locator - It is the unique address of each resource on the web.
    It is in the format:

    protocol:// server : port/path of the resource/resource name/[optional query string]

    eg: http://www.freshfruits.com/all/fruits/grapes.jsp

    Protocol (http):- tells the server which communication protocol is used
    Server (www.freshfruits.com) :- the unique name of server which maps to a unique IP address.
    IP address is numeric.
    Port (80):- port number is optional. By default the port number for web server is 80
    .
    Path (all/fruits/) :- the location of the resource in the server
    (unix syntax is used to describe the path)
    Resource name (grapes.jsp) :- the requested resource
    Optional query string:- the extra info in the GET request is appended to the end of URL as query string.
    It starts with ? followed by name/value pair separated by &


    TCP Port

    A 16 bit number that identifies a specific softare program on the server hardware. It is a logical
    connection to a software running on a server harware. A server has 65536 ports ranging from 0 - 65535.
    The port numbers from 0-1023 are reserverd for system services.
    It is possible to run different applications on the same port provided the applications are using different
    protocols.
    Some reserved ports:
    21 - FTP
    23 - Telnet
    25 - SMTP
    37 - Time
    80 - HTTP
    110 - POP3
    443- HTTPS
    Apache (the open source web server )directory structure:
    Apache_home -> htdocs -> index.html, root folders for the apps on the server -> sub folders and htm pages

    Http request and Http Response

    HTTP Request and Response

    The HTTP Request contains an HTTP method which tells the server the type of request that is being made. The HTTP adds a header to its request and response.

    GET and POST
    The common HTTP methods are GET and POST.

    The GET method is used to get a resource from the server. For eg: when the user clicks a link. The GET method can send limited quantity (depending on server) of data to the server. The data that is send via GET method is appended to the URL and is exposed to everyone. This data (called parameter) is separated by "?" in the URL. The GET request can be bookmarked. The GET is used for getting things and not making any changes to the server

    The POST method can request a resource from the server and also sends the form data (called payload) to the server.For eg: when the user enters some data and submits the form by clicking the submit button. The parameters are put in the payload. POST request can't be bookmarked. The POST is used for sending data to be processed and this data is used to change something on the server. (an update)


    Sample HTTP GET request:
    -----------------------------------------------------------------
    GET /fruits/grapes.jsp?color=green&type=seedless HTTP/1.1
    Host: www.freshfruits.com
    User-Agent: Mozilla
    Accept: text/html
    Accept-Language:en-us
    Keep-Alive:300
    Connection:keep-alive
    -----------------------------------------------------------------
    Sample HTTP POST request
    ------------------------------------------------------------------
    POST /fruits/grapes.jsp HTTP/1.1
    Host: www.freshfruits.com
    User-Agent: Mozilla
    Accept: text/html
    Accept-Language:en-us
    Keep-Alive:300
    Connection:keep-alive
    color=green&type=seedless --> This is the message body or Payload <--
    ----------------------------------------------------------------------
    The other HTTP methods are HEAD, TRACE, PUT, DELETE. OPTIONS and CONNECT.
    The HTTP Response contains the requested resource in the form of HTML. The response has a header and body. The requested resource is put in the body of the response.The header tells the browser the protocol that is used, whether the request is success or not, the type of the content in the body(MIME type).

    Sample HTTP Response:
    -----------------------------------------------------------
    HTTP/1.1 200 OK
    set-cookie: JSESSIONID=0B4587RT
    content-type:text/html
    content-length:242
    date: wed, 23 Sep 2009 02:45:09 GMT
    Server: Appache
    Connection: close
    < html >
    ...........the requested resource
    ..........
    < /html >
    -------------------------------------------------------------------

    web server and client

    Web Client
    A web client is a browser which lets the user to request resources. The resources can be an image, a text file, a sound file or anything. The web client sends request to the web server.

    Web Server
    A web server receives the request from the client, locates the requested resource and sends the response back to the client. If the requested resources is not available in the server it gives a '404 File not found error'

    How the client and server communicates?

    The web server and client communicates via HTTP (Hyper Text Transfer Protocol). The HTTP protocol runs on the top of TCP/IP.
    The TCP (Transmission Control Protocol) ensures that the file send from one host to another is received completely and correctly.
    The IP (Internet Protocol) routes the packets from one host to another.
    The web client must know HTML (Hyper Text Mark up Language). The HTML tells the browser how to display the contents send by the server.
    In short, the browser ie the web client sends HTTP request and the web server send back an HTTP response which contains HTML.

    Followers