Introduction to Web Technologies

Web consist of billion of clients and server connected through wires and wireless networks. The web clients makes request to web server. The web server receives the request, finds the resources and return response to the client. When a server answers a request the server usually sends some type of content to the client. The client uses web browser to send request to the server. The server often send responds to the browser with a set of instructions written in HTML(HyperText Markup Language). All browser know how to display HTML page to the client.

client and server


Web Application

A web site is a collection of static files such as HTML pages, images, graphics etc. A Web application is a web site with dynamic functionality on the server. Google,Facebook,Twitter are examples of web application.


HTTP

HTTP protocol


HTTP method

HTTP request can be made using a variety of methods, but the ones you will use most often are Get and Post. The method name tells the server the kind of request that is being made, and how the rest of the message will be formated.

HTTP Method and Descriptions

Method
Description
OPTIONSRequest for communication options available on the request/response chain.
GETRequest to retrieve information from server
HEADIdentical to GET except that it does not return a message-body, only the headers
POSTRequest for server to accept the entity enclosed in the body of HTTP method.
DELETERequest for the Server to delete the resource.
CONNECTReserved for use with a proxy that can switch to being a tunnel.

Difference between GET and POST request

GET Request
POST Request
Data is sent in header to the serverData is sent in request body
Get request can send only limited amount of dataLarge amount of data can be sent.
Get request is not secured because data is exposed in URLPost request is secured because data is not exposed in URL.
Get request can be bookmarked.Post request cannot be bookmarked.
Get request is more efficientPost request is less efficient.

Anatomy of an HTTP GET request

Get request contains path to server and any parameter added to it.

get request method


Anatomy of an HTTP POST request

Post request are used to make more complex request on the server. For instance, if a user has filled a long form and the application want to save all form's data to the database. Then the form data will be sent to the server in post request body also known as message body.

post request method



Introduction to Servlet

Servlet technology is used to create web application. Servlet technology uses Java language to create web application.

Web application are helper application that resides at web server and build dynamic web pages. A dynamic page could be anything like a page that randomly chooses picture to display or even a page that display current time.

web application example

As Servlet Technology uses Java, web application made using Servlet are secured, scalable and robust.


CGI

Before Servlet, CGI(Common Gateway Interface) programming was used to create web application. Here's how a CGI program works

  • User clicks a link that has URL to a dynamic page instead of static page.
  • The URL decide which CGI program to execute.
  • Web Server run the CGI program in seperate OS shell. The shell include OS enviroment and the process to execute code of the CGI program.
  • The CGI respond is sent back to the Web Server, which wraps the response in an HTTP response and sent it back to the web browser.

CGI example


Drawbacks of CGI program

  • High resposne time because CGI program execute in their own OS shell.
  • CGI is not scalable.
  • CGI are not always secure or object-oriented.
  • Platform-dependent.

Because of these disadvantage, developers need other CGI solutions. Sun Microsystems developed Servlet as a solution over traditional CGI technology.


Advantage with Servlet

  • Less response time because each request run in a seperate thread.
  • Servlet are scalable.
  • Servlet are robust and object oriented.
  • Servlet are platform independent.

Servlet example




Servlet API

Servlet API consist of two important packages that encapsulate all the important classes and interface.

  • javax.servlet
  • javax.servlet.http

Some Important Classes and Interface of javax.servlet

CLASSES and INTERFACES
ServletServletRequest
ServletResponseServletConfig
ServletContextRequestDispatcher
FilterChainFilter
ServletInputStreamGenericServlet
ServletOutputStreamServletException

Some Important Classes and Interface of javax.servlet.http

CLASSES and INTERFACES
HttpServletHttpServletRequest
HttpServletResponseHttpSessionAttributeListener
HttpSessionHttpSessionListener
CookieHttpSessionEvent

Servlet Interface

Servlet Interface provides five method. Out of this five method three method are servlet life cycle method and rest two are non life cycle method.

servlet interface example


GenericServlet Class

GenericServlet is an abstract class that provide implementation of most of the basic servlet method.

Methods of GenericServlet class

  • public void init(ServletConfig)
  • public abstract void service(ServletRequest request,ServletResposne response)
  • public void destroy()
  • public ServletConfig getServletConfig()
  • public String getServletInfo()
  • public ServletContext getServletContext()
  • public String getInitParameter(String name)
  • public Enumeration getInitParameterNames()
  • public String getServletName()
  • public void log(String msg)
  • public void log(String msg, Throwable t)

HttpServlet class

HttpServlet is also a abstract class. This class gives implementation of service() method of Servlet interface.

To create a servlet, we should create a class that extends HttpServlet abstract class. The servlet class that we will create should not override service() method. Our servlet class will override only doGet() and/or doPost() method.

The service() method of HttpServlet class look at the Http method(GET, POST etc) from request stream and invokes doGet() or doPost() method based on Http method.

Httpservlet Api



How a servlet application work

Web container is responsible for managing execution of servlet and Jsp pages for Java EE application.

When a request comes in for a servlet, the server hands the request to Web Container. Web Container is responsible for instantiate the servlet or make a new thread to handle the request. Its Web Container job to get the request and response to the servlet. The container creates multiple thread to process multiple requests to a single servlet.

Servlet don't have a main() method. Web Container manages the life cycle of a servlet instance.


Quick Review on how a servlet work

  1. User sends request for a servlet by clicking a link that has URL to a servlet.
  2. how a servlet application works


  3. The container finds the servlet using deployment descriptor and creates two objects
    1. HttpServletRequest
    2. HttpServletResponse

    how a servlet application works


  4. The container creates or allocates a thread for that request and calls the servlet's service() method and passes the request, response objects as argument
  5. how a servlet application works


  6. The service method decide which servlet method doGet() or doPost() to call based on HTTP Request Method(Get,Post) sent by the client. Suppose the client sent an HTTP GET request, so the service() calls servlet doGet() method
  7. how a servlet application works


  8. The servlet uses response object to write the response back to the client
  9. how a servlet application works


  10. After the service() method is completed the thread dies. The request and response object are ready for garbage collection
  11. how a servlet application works



Servlet life Cycle

servlet life cycle

  1. Loading Servlet Class: A Servlet class is loaded when first request for the servlet is recieved by the Web Container.
  2. Create Servlet instance:After the Servlet class is loaded, Web Container creates the instance of it. Servlet instance is created only once in the life cycle.
  3. Call the init() method: init() is called by the Web Container on servlet instance to initialize the servlet.
  4. Signature of init() method:

    public void init(ServletConfig config) throws ServletException
    
  5. Call the service() method: The containers call the service() method each time the request for servlet is received.
  6. Signature of service() method:

    public void service(ServletRequest request,ServletResponse response) throws ServletException, IOException
    
  7. Call destroy() method: The Web Container call the destroy() method before removing servlet instance giving a chance for cleanup activity.


Eclipse IDE

Eclipse is the most popular Java IDE used in the Industy. Eclipse is an open source community and can be downloaded for free from eclipse.org.


Steps to create servlet using Eclipse IDE

To create a servlet application in Eclipse IDE you will need to follow the following steps.

  1. Goto file -> New -> Dynamic Web Project
  2. steps to create servlet application in eclipse


  3. Give a name to your project and click next
  4. steps to create servlet application in eclipse



    steps to create servlet application in eclipse


  5. Check Generate web.xml Deployment Descriptor and click finish
  6. steps to create servlet application in eclipse


    steps to create servlet application in eclipse


  7. Click on First project, go to Java Resources -> src. Right click on src select -> New -> Servlet
  8. steps to create servlet application in eclipse


  9. Give servlet class name and click next
  10. steps to create servlet application in eclipse


    steps to create servlet application in eclipse


  11. Leave everything else to default and click finish
  12. steps to create servlet application in eclipse


  13. Now your servlet is created, write some code inside it.
  14. steps to create servlet application in eclipse


  15. Add servlet-api.jar file to your project. Click in Libraries, right click on Web App Libraries select Build Path -> Configure Build Path
  16. steps to create servlet application in eclipse


  17. Click on Add External JARs
  18. steps to create servlet application in eclipse


  19. Select servlet-api.jar from Apache Tomcat Directory
  20. steps to create servlet application in eclipse


    steps to create servlet application in eclipse


  21. Start the server and run the application
  22. steps to create servlet application in eclipse


Servlet Request

True job of a servlet is to handle client request. Servlet API provides two important interface javax.servlet.ServletRequest and javax.servlet.http.HttpServletRequest to encapsulate client request. Implementation of these interface provide important information about client request to a servlet.


Some important methods of ServletRequest

MethodsDescription
Object getAttribute(String name)return attribute set on request object by name
Enumeration getAttributeName() return an Enumeration containing the names of the attributes available inthis request
int getContentLength()return size of request body
int getContentType()return media type of request content
ServletInputStream getInputStream()returns a input stream for reading binary data
String getParameter(String name)returns value of parameter by name
String getLocalAddr()returns the Internet Protocol(IP) address of the interface on which the request was received
Enumeration getParameterNames()returns an enumeration of all parameter names
String[] getParameterValues(String name) returns an array of String objects containing all of the values the given request parameter has, or null if the parameter does not exist
ServletContext getServletContext()return the servlet context of current request.
String getServerName()returns the host name of the server to which the request was sent
int getServerPort()returns the port number to which the request was sent
boolean isSecure()returns a boolean indicating whether this request was made using a secure channel, such as HTTPS.
void removeAttribute(String name)removes an attribute from this request
void setAttribute(String name, Object o)stores an attribute in this request.


HttpServletRequest interface

HttpServletRequest interface adds the methods that relates to the HTTP protocol.

servlet request


Some important methods of HttpServletRequest

MethodsDescription
String getContextPath()returns the portion of the request URI that indicates the context of the request
Cookies getCookies()returns an array containing all of the Cookie objects the client sent with this request
String getQueryString()returns the query string that is contained in the request URL after the path
HttpSession getSession()returns the current HttpSession associated with this request or, if there is no current session and create is true, returns a new session
String getMethod()Returns the name of the HTTP method with which this request was made, for example, GET, POST, or PUT.
Part getPart(String name)gets the Part with the given name
String getPathInfo()returns any extra path information associated with the URL the client sent when it made this request.
String getServletPath()returns the part of this request's URL that calls the servlet


Example

In this example, we will show how a parameter is passed to a servlet in request object from html page.

index.html

<form method="post" action="check">
Name <input type="text" name="user" >

<input type="submit" value="submit">
</form>

web.xml

<servlet>
        <servlet-name>check</servlet-name>

        <servlet-class>MyServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>check</servlet-name>
        <url-pattern>/check</url-pattern>

    </servlet-mapping>

MyServlet.java


import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class MyServlet extends HttpServlet {

  protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
       response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
           
            String user=request.getParameter("user");
            out.println("<h2> Welcome "+user+"</h2>");
        } finally {            
            out.close();
        }
    }
}

Output

servlet request example output


servlet request example output


Servlet Response

Servlet API provides two important interface ServletResponse and HttpServletResponse to assist in sending response to client.


Some important methods of ServletResponse

MethodsDescription
PrintWriter getWriter()returns a PrintWriter object that can send character text to the client.
void setBufferSize(int size)Sets the preferred buffer size for the body of the response
void setContentLength(int len) Sets the length of the content body in the response In HTTP servlets, this method sets the HTTP Content-Length header
void setContentType(String type)sets the content type of the response being sent to the client before sending the respond.
void setBufferSize(int size)sets the preferred buffer size for the body of the response.
boolean isCommitted()returns a boolean indicating if the response has been committed
void setLocale(Locale loc) sets the locale of the response, if the response has not been committed yet.


HttpServletResponse interface

HttpServletResponse interface adds the methods that relates to the HTTP response.

servlet response


Some important methods of HttpServletResponse

MethodsDescription
void addCookie(Cookie cookie)adds the specified cookie to the response.
void sendRedirect(String location)Sends a temporary redirect response to the client using the specified redirect location URL and clears the buffer
int getStatus()gets the current status code of this response
String getHeader(String name)gets the value of the response header with the given name.
void setHeader(String name, String value)sets a response header with the given name and value
void setStatus(int sc)sets the status code for this response
void sendError(int sc, String msg)sends an error response to the client using the specified status and clears the buffer


Request Dispatcher

RequestDispatcher is an interface, implementation of which defines an object which can dispatch request to any resources(such as HTML, Image, Jsp, Servlet) on the server.


Method of RequestDispatcher

RequestDispatcher interface provides two important methods

MethodsDescription
void forward(ServletRequest request, ServletResponse response)forwards a request from a servlet to another resource (servlet, JSP file, or HTML file) on the server
void include(ServletRequest request, ServletResponse response) includes the content of a resource (servlet, JSP page, HTML file) in the response

How to get an object of RequestDispatcher

getRequestDispatcher() method of ServletRequest returns the object of RequestDispatcher.

RequestDispatcher rs = request.getRequestDispatcher("hello.html");
rs.forward(request,response);

RequestDispatcher detail

Or

RequestDispatcher rs = request.getRequestDispatcher("hello.html");
rs.include(request,response);
RequestDispatcher detail


Example

In this example, we will show how RequestDispatcher is used to forward or include response of a resource in a servlet. Here we are using index.html to get username and password from the user, Validate servlet will validate the password entered by the user, if the user has entered "studytonight" as password, then he will be forwarded to Welcome servlet else the index.html will be shown again to the user.

Files to be created

  • index.html will have form field to get user information
  • Validate.java will validate the data entered by the user
  • Welcome.java will be the welcome page
  • web.xml

index.html

<form method="post" action="Validate">
Name:<input type="text" name="user" /><br/>

Password:<input type="password" name="pass" ><br/>
<input type="submit" value="submit">
</form>

Validate.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class Validate extends HttpServlet {

   protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
      response.setContentType("text/html;charset=UTF-8");
     PrintWriter out = response.getWriter();
     try {
         String name = request.getParameter("user");
        String password = request.getParameter("pass");

        if(password.equals("studytonight"))
        {
            RequestDispatcher rd = request.getRequestDispatcher("Welcome");
           rd.forward(request, response);
        }
        else
         {
         out.println("<font color='red'><b>You have entered incorrect password</b></font>");
                RequestDispatcher rd = request.getRequestDispatcher("index.html");
                rd.include(request, response);

            }
        }finally {            
            out.close();
        }
        
    }
}

Welcome.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Welcome extends HttpServlet {

   protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            
            out.println("<h2>Welcome user</h2>");
        } finally {            
            out.close();
        }
    }
}

web.xml

<web-app>

    <servlet>
        <servlet-name>Validate</servlet-name>
        <servlet-class>Validate</servlet-class>
    </servlet>
    <servlet>

        <servlet-name>Welcome</servlet-name>
        <servlet-class>Welcome</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>Validate</servlet-name>

        <url-pattern>/Validate</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>Welcome</servlet-name>
        <url-pattern>/Welcome</url-pattern>

    </servlet-mapping>
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
        </welcome-file-list>
</web-app>

request dispatcher example


request dispatcher example


request dispatcher example


request dispatcher example


sendRedirect Method

sendRedirect() method redirect the response to another resource. sendRedirect() method actually makes the client(browser) to create a new request to get to the resource. The client can see the new url in the browser.

sendRedirect() accept relative URL, so it can go for resources inside or outside the server.


sendRedirect and request dispatcher

The main difference between a redirect and a request dispatch is that, redirect makes the client(browser) create a new request to get to the resource, the user can see the new URL while request dispatch get the resource in same request and URL does not changes.

sendRedirect works on response object while request dispatch work on request object.


Example

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class MyServlet extends HttpServlet {

   protected void doGet(HttpServletRequest request, HttpServletResponse response)
          throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            response.sendRedirect("http://www.studytonight.com");
        }finally {            
            out.close();
        }
        
    }
}


ServletConfig interface

When the Web Container initializes a servlet, it creates a ServletConfig object for the servlet. ServletConfig object is used to pass information to a servlet during initialization by getting configuration information from web.xml(Deployment Descriptor).


Method of ServletConfig

  • String getInitParameter(String name): returns a String value initialized parameter, or null if the parameter does not exist.
  • Enumeration getInitParameterNames(): returns the names of the servlet's initialization parameters as an Enumeration of String objects, or an empty Enumeration if the servlet has no initialization parameters.
  • ServletContext getServletContext(): returns a reference to the ServletContext
  • String getServletName(): returns the name of this servlet instance

How to initialize a servlet inside web.xml

In the Deployment Descriptor(web.xml) file

how to initialize a servlet using deployment descriptor

Inside Servlet class

ServletConfig sc=getServletConfig();
 out.println(sc.getInitParameter("email"));


Example

web.xml

<web-app...>
    
   <servlet>
      <servlet-name>check</servlet-name>

      <servlet-class>MyServlet</servlet-class>
      <init-param>
            <param-name>email</param-name>
            <param-value>we@studytonight.com</param-value>

      </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>check</servlet-name>
        <url-pattern>/check</url-pattern>

    </servlet-mapping>
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
     </welcome-file-list>   
</web-app>

MyServlet class

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class MyServlet extends HttpServlet {

  protected void doGet(HttpServletRequest request, HttpServletResponse response)
         throws ServletException, IOException {
       
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        ServletConfig sc=getServletConfig();
        out.println(sc.getInitParameter("email"));
        
    }
}


ServletContext interface

For every Web application a ServletContext object is created by the web container. ServletContext object is used to get configuration information from Deployment Descriptor(web.xml) which will be available to any servlet or JSPs that are part of the web app.


Some important method of ServletContext

MethodsDescription
Object getAttribute(String name)returns the container attribute with the given name, or null if there is no attribute by that name.
String getInitParameter(String name)returns parameter value for the specified parameter name, or null if the parameter does not exist
Enumeration getInitParameterNames() returns the names of the context's initialization parameters as an Enumeration of String objects
void setAttribute(String name,Object obj)set an object with the given attribute name in the application scope
void removeAttribute(String name)removes the attribute with the specified name from the application context

How Context parameter is initialized inside web.xml

how to initialize servlet context using deployment descriptor


How to get the object of ServletContext

ServletContext app = getServletContext();
or
ServletContext app = getServletConfig().getServletContext();

Advantage of ServletContext

  • Provides communication between servlets
  • Available to any servlets and JSPs that are part of web app
  • Used to get configuration information from web.xml

Difference between Context Init parameters and Servlet Init parameter

Context Init parametersServlet Init parameter
Available to any servlets and JSPs that are part of webAvailable to only servlet for which the was configured
Context Init parameters is initialized within the < web-app> not within a specific < servlet> elementInitialized within the < servlet> for each specific servlet
ServletContext object is used to get Context Init parametersServletConfig object is used to get Servlet Init parameters
Only one ServletContext object for entire web appEach servlet has its own ServletConfig object

Example

web.xml

<web-app ...>
   
   <context-param>

       <param-name>driverName</param-name>
       <param-value>sun.jdbc.JdbcOdbcDriver</param-value>
   </context-param>
   
   <servlet>
      <servlet-name>hello</servlet-name>

      <servlet-class>MyServlet</servlet-class>
   </servlet>
   <servlet-mapping>
        <servlet-name>hello</servlet-name>
        <url-pattern>/hello</url-pattern>

   </servlet-mapping>
       
</web-app>

MyServlet class


import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class MyServlet extends HttpServlet {

  protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
       response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        ServletContext sc=getServletContext();
        out.println(sc.getInitParameter("driverName"));
        
    }
}



Attribute

An attribute is an object that is used to share information in web app. Attribute allows servlets to share information among themselves. Attribute can be set and get from one of the following scope

  1. request
  2. session
  3. application

setting and getting an attribute


How to set an attribute

public void setAttribute(String name, Object obj) method is used to set an attribute.

Example

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class First extends HttpServlet {

  protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
       response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        ServletContext sc = getServletContext();
        sc.setAttribute("user","Abhijit");	//setting attribute on context scope
        
        
    }
}

How to get an attribute

Object getAttribute(String name) method is used to get an attribute.

Example

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class Second extends HttpServlet {

  protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
       response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        ServletContext sc = getServletContext();

       //getting attribute from context scope  
        String str = sc.getAttribute("user");
	
        out.println("Welcome"+str);
        
    }
}