Pages

Servlets

Web Application Development (WAD)

We have two kinds of applications in Java :
  1. Windows Based (or) Desktop Applications
  2. Web Applications

Any computer applications is said to be a web application if we can access it’s services from web (Internet Service). To offer online business services to customers, we go for web applications.


Web Application Architecture

Web Client : It is the browser software that requests the Web Server software for the sake of web resources. It is also known as a HTTP client most of the times web client requests for the web pages.
Web Server: It is a software/application that receives the web clients requests and fetches them requested resources. It is also known as HTTP Server.
Web Page : HTML documents once executed are known as web pages. We have two kinds of web pages.
  1. Static Pages
  2. Dynamic Pages
Static Page is a pre created html document. It is stored web server machine’s file system. Its contents remain unchanged from request to request. A page that is produced on the fly as and when the client request comes is known as dynamic page. Its contents change from request to request.

Q) What is the functionality of a web server and its limitations ?

Web Server is a networking + Input and Output Modules (Software)
  1. It provides connections to the web clients
  2. Fetching HTML documents, image files etc. to the web clients
Limitation : On its own it cannot handle the client request that involves end user input. It cannot process data, it cannot communicate with data base and it cannot produce dynamic page that is web server on its own cannot offer business services to the customers with web server alone we can have informative web site but not an interactive one.

Types of Web Programming : We have two kinds of Web Programming:
  1. Client Side Programming
  2. Server Side Programming
The piece of code executed by the browser that performs client side validations to ensure complete and proper input into the web forms is known as Client Side Programming.

Q) What is the purpose of Server Side Programming ?

To overcome, the limitation of the Web Server, Server Side Programming is required. Server Side Program performs the following duties in general.
1. Capturing web form data.
2. Building the dynamic data (or) processing the retrieved data.
3. Creating dynamic web content (dynamic web page) basing on the data produced in second step and giving the page to the Web Server.

Servlets

Servlets is a web technology from "Sun Micro Systems". Servlets is J2EE Technology. Servlets is a specification to web server (container) manufactures. Servlets API is used by the web application developers to make web sites inter active. A Servlet extends the funcationality of a web server. A servlet is a server side piece of code known as "Web Component". Web Component are JSP and Servlets. A Servlet produces dynamic web content. A Servlet is a dynamic web resource in a web application. A Servlet is a Java Class. A Servlet contains Java Code plus HTML Code. Java Code means dynamic Sake and HTML Code means Presentation Sake.

Servlet Development : A Servlet is a container (Server Software) managed public java class that implement directly or indirectly. javax.servlet is package. Servlet is an Interface.
Web Container Model : A web container is server software that comprises of three modules.
  1. HTTP Service / Default Handler / Web Server
  2. Servlet Engine / Container
  3. JSP Engine / Container

Skeleton Structure of a Servlet :
import javax.servlet.*;
public class MyServlet extends GenericServlet {
      public void init(ServletConfig ) {
            // Resources allocation to the Servlet is done here for example dbconnection creation.
      }
      public void service(ServletRequest, ServletResponse) {
            // Client request processing code
      }
      public void destroy() {
            // Resouce releasing code for example the data base connection.
      }
}
Servlet Life Cycle : Servlet Life Cycle is destroy or described by three life cycle methods and four phases. Servlet Engine controls the Servlet Life Cycle.
Life Cycle Methods :
  1. init();
  2. service();
  3. destroy();
Life Cycle Phases :
  1. Instantiation Phase
  2. Initialization Phase
  3. Servicing Phase
  4. Destruction Phase
Instantiation Phase : Servlet Engine loads our servlet class into memory and create its instance. In this phase, the servlet instance does not posses servletness. Posses servletness means ability attend the client request.

Initialization Phase : ServletConfig Engine creates ServletConfig object. In this object the missing information in the instantiation phase is encapsulated. Servlet Engine calls the init() method by supplying " Config " object (reference) as the arguments. Once the init() method in completely executed, the servlet gets Servletness and will be ready to serve the client request.

Servicing Phase : Servlet Engine create " Request " and " Response " object. It calls services method on the servlet instances by supplying the above two object (references) as arguments.

Note : Instantation and Initialization happens only once in the servlet life but for each client request, servlet should respond. Most of the servlets life is spent in serving the client requests.

Destruction Phase : When the servlet is taken out of service explicity, just before the servlet instance being garbage collected. Servlet Engine calls the destroy() method.

When the servlet is in instantiation phase two pieces of information is not available to it.
1. Initialization Information
2. Context Information

Q) Develop, Deploy and execute a servlet that sends "Welcome to our Web Site" message to the client ?

Web Application Development Steps :

Steps 1 : Create a structured hierarchy of directions root directory.
Root Directory
WEB-INF
Classes
lib

Steps 2 : Web resources development
In this step, we need to develop all the html documents image files, JSP, Servlets etc. of the web application. In the given application we have only servlet is the web resource.
import javax.servlet.*;
import java.io.*;
public class WelcomeServlet extends GenericServlet {
      public void service(ServletRequest request, ServletResponse response) throws IOException, ServletException {
            response.setContentType("text/html");
            PrintWriter pw = response.getWriter();
            String msg = "WELCOME TO OUR WEB SITE.";
            pw.println("<html>");
            pw.println("<body>");
            pw.println("<h1> " + msg + " </h1> ");
            pw.println("</body>");
            pw.println("</html>");
            pw.close();
      }
}

Steps 3 : Writing the development descriptor.
Development Descriptor is a text file whose name nust be "web.xml". In this file we do the servlet registration with the web application otherwise, the container can not recognize the servlet. xml tag is instruction to the container.

XML File Name : web.xml <web-app> <servlet> <servlet-name> one </servlet-name> <serlvet-class> WelcomeServlet </servlet-class> </servlet> <servlet-mapping> <servlet-name> one </servlet-name> <url-pattern>welcome</url-pattern> </servlet-mapping> </web-app> Steps 4 : Configuring the files (Resources files and helper files).
firstapp
WEB-INF
web.xml
classes
compile the program and copy it.

Exmple : Welcome Servlet Class
Deploying the Web Application : Installing the web application into the container and there by making it available to the container is known as Deployment.

Step 1 : Copy the root directory along with the resources into the following directory.
C:\Tomcat 5.0\webapps\

Step 2 : Start Tomcat Server
C:\Tomcat 5.0\startup
In order to get the service from the servlet open the browser and type the following "URL".

URL : http://localhost:8080/firstapp/welcome

Q) What are the System requirements to develop, deploy and execute web application ?

Install any web container software and set the classpath appropriately.
For Example : Tomcat from ASF.
To set the class path give the following command in the numbers prompt.
C:\ set classpath = C:\Tomcat 5.0\Common\lib\servlet-api.jar %classpath%

Q) What is the purpose of Servlet element in the web.xml ?

To register the servlet with the web application.

Q) What is the purpose of element ?

To give public name to the Servlet and Mapping the incoming client request to a particular Servlet.

Q) Explain response.setContentType("text/html") ?

The above method is used to set MIME Type that is image/gif,   application/ms-word,   text/html,   text/plain etc...

Q) Explain the following Statement ?

PrintWriter pw = response.getWrite();
"pw" is the character oriented stream object.
"pw" represents the browser stream.

Q) Explain the directory structure of a web application ?

The root directory name can be any thing. It is divided into two areas.
1. Public Area
2. Private Area
WEB-INF and its contents are private area. They are meant and not for the web client.
Examples :
1. Public Area :
myapp
*.html
*.jsp
All image files.
2. Private Area :
WEB-INF
web.xml
classes
*.class
lib
*.jar

Q) Develop, Deploy and execute a web application in which an end user should be able to enter his/her name into the web form. The end user should get the greeting message with name ?

Step 1 : Directory structure creation
Greeting App
  user.html
WEB-INF
  web.xml
classes
  GreetingServlet.class

Step 2 : Web Resources Development
In this example, we have one static resource (HTML) and one dynamic web resource (Servlet).

HTML File Name : user.html <html> <body bg-color = "Yellow"> <center> <h1> User Name Entry Screen </h1> <form action = "./great"> User Name : <input type = "text" name = "t1"/> <br/> <input type = "submit" value = "Click Here"/> </form> </center> </body> </html> Servlet Class Name : GreetingServlet.java

import javax.servlet.*;
import java.io.*;
public class GreetingServlet extends GenericServlet {
      public void service(ServletRequest request, ServletResponse respone) throws IOException, ServletExcption {
            String urs = request.getParameter("t1");
            // Capturing from data
            String msg = "Hello " + user + "Welcome to our Web Site";
            //Building dynamic data.
            response.setContentType("type/html");
            PrintWriter pw = response.getWriter();
            pw.println("<html>");
            pw.println("<body bg-color = "green">");
            pw.println("<h1>" + msg + "</h1>");
            pw.println("</body>");
            pw.println("</html>");
            pw.close();
      }
}

Step 3 : Writing Development Descriptor (web.xml) <web-app> <servlet> <servlet-name> two </servlet-name> <servlet-class> Greeting Servlet </serlvet-class> </servlet> <servlet-mapping> <servlet-name> two </servlet-name> <url-pattern> /greet </url-pattern> </servlet-mapping> </web-app> Step 4 : Configuring the Resource
greetingApp
  user.html
WEB-INF
  web.xml
classes
  GreetingServlet.class

Web URL : http://localhost.8080/greetingapp/user.html

Q) Web Application in which end user enters two numbers into the web form and get the sum as the result ?

Step 1 : Directory structure creation
Adding App
number.html
WEB-INF
web.xml
Classes
SumServlet.class

Step 2 : Web Form Source Code <html> <body bg-color = "Cyan"> <center> <h1> Addition Program </h1> <form action = "./add"> First Number : <input type = "text" name = "t1"/> <br/> Second Number : <input type = "text" name = "t2"/> <br/> <input type = "submit" value = "Addition"/> </form> </center> </body> </html> Servlet Class Name : SumServlet.java

import javax.servlet.*;
import java.io.*;
public class SumServlet extends GenericServlet {
      public void service(ServletRequest request, ServletResponse respone) throws IOException, ServletExcption {
            int n1 = Integer.parseInt(request.getParameter("t1"));
            int n2 = Integer.parseInt(request.getParameter("t2"));
            // Capturing from data
            int sum = n1 + n2;
            //Building dynamic data.
            response.setContentType("type/html");
            PrintWriter pw = response.getWriter();
            pw.println("<html>");
            pw.println("<body bg-color = "cyan">");
            pw.println("<h1>" + sum + "</h1>");
            pw.println("The Sum of Two Numbers is : " + sum);
            pw.println("</body>");
            pw.println("</html>");
            pw.close();
      }
}

Step 3 : Writing Development Descriptor (web.xml) <web-app> <servlet> <servlet-name> three </servlet-name> <servlet-class> SumServlet </serlvet-class> </servlet> <servlet-mapping> <servlet-name> three </servlet-name> <url-pattern> /add </url-pattern> </servlet-mapping> </web-app>

Q) Modify the above application in such a way that place two buttons on the web page (Add/Subtract) and give appropriate response ?

Note : In the web form. Create two submit buttons with different caption but with same name. <input type = "submit" name = "ss" value = "Sum"> In the Servlet service method find out the button on which end user clicked.
String caption = request.getParameter("ss");
if(caption.equals("add")) {
    addition();
} else {
    subtraction();
}
Performing data base operations in Servlets : We establish the connection in init() method close the connection in destroy() method. Creating the statement object, submitting the SQL statements and prcessing the results is done in the service method.

Note : ClassNotFoundException and SQLException. We can not pass on that is we cannot use the throws class for these Exceptions in Servlet programming. We need to handle them using try and catch.

Q) Develop Web Application in which, end user enters employee number into the web form and gets the employee details ?

employeeApp
  emp.html
WEB-INF
  web.xml
classes
  EmpServlet.class
lib
  classes12.jar

Web Url : http://localhost:8080/employeeapp/emp.html

HTML File Name : emp.html <html> <body bg color = "wheat"> <center> <h1> Employee Details Query Screen </h1> <form action = "./emp"> Emp No <input type = "text" Name = "t1"/> <br/> <br/> <input type = "submit" value = "Save" /> </form> </center> </body> </html> XML File Name : web.xml <web-app> <servlet> <servlet-name> four </servlet-name> <serlvet-class> EmployeeServlet </servlet-class> </servlet> <servlet-mapping> <servlet-name> four </servlet-name> <url-pattern>/emp </url-pattern> </servlet-mapping> </web-app> Servlet Class Name : EmployeeServlet

import javax.servlet.*;
import java.io.*;
import java.sql.*;
public class EmployeeServlet extends GenericServlet {
      Connection con;
      public void init(ServletConfig Config) throws ServletException {
            try {
                  class.forName("Oracle.jdbc.driver.oracleDriver");
                  con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:server","scott","tiger");
                  System.out.println("Connected");
            } catch(Exception exp) {
                  exp.printStackTrack();
            }
      }
      public void destroy () {
            try {
                  con.close();
            }
      }
      public void service (ServletRequest request, ServletResponse response) throws IOException, ServletException {
            response.setContentType("text/html");
            PrintWriter out = response.getWrite();
            int eno = Integer.parseInt(request.getParameter("t1"));
            try {
                  String sql = "SELECT * FROM EMPLOYEE WHERE ENO = " + eno ;
                  Statement st = con.createStatement();
                  ResultSet rs = st.executeQuery(sql);
                  if(rs.next()) {
                        out.println( "Employee ID : " + rs.getInt("id") );
                        out.println( "Employee Name : " + rs.getString("name") );
                        out.println( "Salary : " + rs.getString("salary") );
                        out.println( "City : " + rs.getString("city") );
                  }
            } catch(Exception exp) {
                  exp.printStackTrack();
            }
      }
}
Passing initialization parameters to Servlets : Initialization parameter are name value pair of strings supplied to the servlet during its initialization phase. We pass init parameter declaratively that is through web.xml. <init-param> <param-name> <param-value> </init-param>

Q) Write the web.xml in which Driver, Connection String, User Name and Password should be supplied as initialization parametes.

<web-app> <servlet> <servlet-name> five </servlet-name> <servlet-class> DataBaseServlet </servlet-class> <init-param> <param-name> P1 </param-name> <param-value> sun.jdbc.odbc.JdbcOdbcDriver </param-value> </init-param> <init-param> <param-name> P2 </param-name> <param-value> jdbc:odbc:ourdsn </param-value> </init-param> <init-param> <param-name> P3 </param-name> <param-value> scott </param-value> </init-param> <init-param> <param-name> P4 </param-name> <param-value> tiger </param-value> </init-param> </servlet> <servlet-mapping> <servlet-name> five </servlet-name> <url-pattern>/database </url-pattern> </servlet-mapping> </web-app> ServletConfig object holds init parameters. Servlet instances talks to Config object to retrieve init parameter values.
String d = config.getInitParameter("P2");

Q) Web Application in which end user should be able to enter application details repeatitively ?

databaseapp
  emp.html
WEB-INF
  web.xml
classes
  DataBaseServlet.class

HTML File Name : emp.html <html> <body bg color = "wheat"> <center> <h1> Employee Details </h1> <form action = "./database"> Emp No <input type = "text" name = "t1"/> <br/> <br/> Name <input type = "text" name = "t2" /> <br/> <br/> Salary <input type = "text" name = "t3" /> <br/> <br/> <input type="submit" value = "Insert"/> </form> </center> </body> </html> Servlet Class Name : DataBaseServlet.java

import javax.servlet.*;
import java.io.*;
import java.sql.*;
public class DataBaseServlet extends GenericServlet {
      Connection con;
      ParameterStatement ps;
      public void init(ServletConfig sc) {
            try {
                  String sql = "INSERT INTO EMPLOYEE VALUE S (?,?,?)";
                  class.forName(sc.getInitParameter("P1"));
                  con = DriverManager.getConnection(sc.getInitParameter("P2"), sc.getInitParameter("P4"));
                  ps = con.preparedStatement(sql);
                  System.out.println("Prepared Statement Created");
            } catch(Exception exp) {
                  exp.printStackTrace(exp);
            }
      }
      public void destroy() {
            try {
                  ps.close();
                  con.close();
            } catch(Exception exp) {
                  exp.printStackTrace(exp);
      }
      public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException {
            int no = Integer.parseInt(request.getParameter("t1"));
            String nm = request.getParameter("t2");
            float sal = Float.parseFloat(request.getParameter("t3"));
            try {
                  ps.setInt(1, no);
                  ps.setString(2,nm);
                  ps.setFloat(3,sal);
                  ps.executeUpdate();
                  response.setContentType("text/html");
                  PrintWriter out = response.getWriter();
                  out.println("<h1> One Employee Details Stored Succesfully </h1>");
                  out.close();
            } catch(Exception exp) {
                  exp.printStackTrace(exp);
            }
      }
}

Q) What are the methods of the Servlet Interfaces ?

1. Init(ServletConfig sc);
2. Service(ServletRequest, ServletResponse);
3. destroy();
4. String getServletConfig();
5. ServletConfig getServletConfig();
getServletConfig() method is implemented in our Servlet when ever we want to provides some information about the servlet that is author data of development team etc.

Q) What are the methods of the ServletConfig ?

It is interface. It is dot class file. It is belong to web.xml Servlet package.
1. String value = config.getIntParameter("name");
2. String regname = config.getServletName();
3. Enumeration getInitParameterNames();
4. ServletContext getServletcontext();

Servlet Collaboration

One Servlet assisting another servlet directory (or) in directory in passing the client request is known as Servlet Collaboration. Servlet Collaboration two types :
1. Sharing of Data
2. Sharing of Control

In sharing of data, inter servlet communication is not mandatory. In case of data sharing one servlet handles the client request mostly some times, client requests will be complex. A single servlet cannot handle on its own such requests. It perform its portion of processing and switches the control to another servlet. That servlet performs the remaining task performing duty. Here, inter servlet communication is mandatory.

Data Sharing among Servlet : In a web application, when ever servlets need to show data. Concept of attributes comes into picture. An attributes represents data is name value pair concept. To deal with attributes we have the following method in.
1. Servlet Request
2. Servlet Context
3. Http Session
Methods :
a. setAttribute("name", object value);
b. getAttribute("name");
c. removeAttribute("name");
d. enumeration getAttribute();

Q) Explain about scope of an attribute ?

According to Servlet Specification, Servlet Programming an attributes can have three scopes.
1. requestScope(req.***());
2. applicationScope(context.***());
3. Session session(session.***());

Data Sharing among Servlets in application Scope : As soon as a web application is deployed the web container create ServletContext object. Object oriented representation of the whole web application is nothing ServletContext Object. ServletContext object is only one per web application. ServletContext acts as the shared information repository. All the web components (Serlvet/JSPs) of that web applications, shares this objects.

Steps to implements data sharing in Application Scope :

Step 1 : One Servlet getting the reference of the SerlvetContext.
              ServletContext sc = getServletContext();
              sc means pointer reference to the ServletContext.
Step 2 : The first Servlet storing data items in the context object.
              sc.setAttribute("name", "value");
Step 3 : The other Servlet getting the reference of the ServletContext object.
              ServletContext sc420 = getServletContext();
Step 4 : The second Servlet retrieving the data item from the ServletContext object.
              sc420.getAttribute("name");

Q) Example web application in which two servlets sharing a data item in application scope ?

SharingApp
  share.html
WEB-INF
  web.xml
classes
  SharingServlet.class
  UsingServlet.class

Web URL : http://localhost:8080/SharingApp/share.html

XML File Name : web.xml <web-app> <servlet> <servlet-name> six </servlet-name> <servlet-class> SharingServlet </servlet-class> </servlet> <servlet> <servlet-name> seven </servlet-name> <servlet-class> UsingServlet </servlet-class> </servlet> <servlet-mapping> <servlet-name> six </servlet-name> <url-pattern> /source </url-patten> </servlet-mapping> <servlet-mapping> <servlet-name> seven </servlet-name> <url-pattern> /target </url-patten> </servlet-mapping> </web-app> HTML File Name : share.html <html> <body bg-color = "yellow"> <form action = "./souce"> Admin Mail <input type = "text" name = "t1"/> <br/> <input type = "submit"/> </form> </body> </html> Servlet Class Name : SharingServlet.java

import java.io.*;
import java.sql.*;
import java.servlet.*;
public class SharingServlet extends GenericServlet {
      public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException {
            String amail = request.getParameter("t1");
            ServletContext sc = getServletContext();
            sc = setAttribute("abc", amail);
            response.setContentType("text/html");
            PrintWriter out = response.getWriter();
            out.println("<a href = ./target> Get Info Here </a>");
            out.close();
      }
}

Servlet Class Name : UsingServlet.java

import java.io.*;
import java.sql.*;
import java.servlet.*;
public class UsingServlet extends GenericServlet {
      public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException {
            ServletContext sc420 = getServletContext();
            String am = (String) sc420.getAttribute("abc");
            response.setContentType("text/html");
            PrintWriter out = response.getWriter();
            out.println("<h1> Admin Mail is : " + am + "</h1>");
            out.close();
      }
}

Request Dispatching

One Servlet dispatching request processing duty to another servlet is known as Request Dispatching. Inter Servlet communication is implemented through request dispatching. When request dispatching is implemented, control is shared and if required, data is shared among servlet’s. In this case data sharing happens in request scope. While implementing request dispatching, all the servlets that share the control will share the ServletRequest object as well.

Request Dispatching is implemented in two ways :
1. Forward Machanism
2. Include Machanism

Steps to Implement Request Dispatching :

Step 1 : One Servlet getting the reference of the SerlvetContext.
              ServletContext sc = getServletContext();
Step 2 : Getting the reference of the Request Dispatching object.
              RequestDispatching rd = sc.getRequestDispatching(String target Servlet public name);
Step 3 : Perform the request dispatching.
              rd.forward(request, response);
              rd.include(request, response);

Q) Web Application to implement request dispatching using include and forward mechanism ?

DispatchApp
emp.html
caption.html
WEB-INF
web.xml
classes
GrossServlet.class
NetServlet.class
Web URL : http://localhost:8080/DispatchApp/emp.html

XML File Name : web.xml <web-app> <servlet> <servlet-name> source </servlet-name> <servlet-class> GrossServlet </servlet-class> </servlet> <servlet> <servlet-name> target </servlet-name> <servlet-class> NetServlet </servlet-class> </servlet> <servlet-mapping> <servlet-name> source </servlet-name> <url-pattern> /gross </url-patten> </servlet-mapping> <servlet-mapping> <servlet-name> target </servlet-name> <url-pattern> /net </url-patten> </servlet-mapping> </web-app> HTML File Name : emp.html <html> <body bg-color = "wheat"> <form action = "./gross"> Employee Basic <input type = "text" name = "basic"/> <br/> <input type = "submit"/> </form> </body> </html> Serlvet Class Name : GrossServlet.java

import java.io.*;
import java.servlet.*;
public class GrossServlet extends GenericServlet {
      public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException {
            float basic = Float.parseFloat(request.getParameter("basic"));
            float da = 0.5f * basic;
            float hra = 0.4f * basic;
            float gross = basic + da + hra;
            Float f = new Float(gross);
            request.setAttribute("gross", f);
            ServletContext sc = getServletContext();
            RequestDispatcher rd = sc.getRequestDispatcher("/net");
            rd.forward(request, response);
      }
}

Serlvet Class Name : NetServlet.java

import java.io.*;
import java.servlet.*;
public class NetServlet extends GenericServlet {
      public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException {
            response.setContentType("text/html");
            PrintWriter out = response.getWriter();
            Float gross = (Float) request.getAttribute("gross");
            float net = gross.floatValue() – 2000;
            ServletContext sc = getServletContext();
            RequestDispatcher rd = sc.getRequestDispatcher("/caption.html");
            rd.include(request, response);
            out.println("<html>");
            out.println("<body bg-color = "cyan">");
            out.println(" Your Net Salary is : " + net);
            out.println("</body> </html> ");
            out.close();
      }
}

HTMl File Name : caption.html <html> <body> <marquee> <font size ="6" color = "green"> No Substitute for Hard Word </font> </marquee> </body> </html> Include Machanism :
IncludeApp
  emp.html
WEB-INF
  web.xml
classes
  GrossServlet.class
  NetServlet.class

Web URL : http://localhost:8080/DispatchApp/emp.html

Serlvet Class Name : GrossServlet.java

import java.io.*;
import java.servlet.*;
public class GrossServlet extends GenericServlet {
      public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException {
            float basic = Float.parseFloat(request.getParameter("basic"));
            float da = 0.5f * basic;
            float hra = 0.4f * basic;
            float gross = basic + da + hra;
            Float f = new Float(gross);
            request.setAttribute("gross", f);
            ServletContext sc = getServletContext();
            RequestDispatcher rd = sc.getRequestDispatcher("/net");
            rd.include(request, response);
            Float n = (Float) request.getAttribute("net");
            float net = n.floatValue();
            response.setContentType("text/html");
            PrintWriter out = response.getWriter();
            out.println("<html>");
            out.println("<body bg-color = "cyan">");
            out.println(" <h1> Net Salary is Rs. : " + net + "</h1>");
            out.println("</body> </html> ");
            out.close();
      }
}

Servlet Class Name : NetServlet.java

import java.io.*;
import java.servlet.*;
public class NetServlet extends GenericServlet {
      public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException {
            Float gross = (Float) request.getAttribute("gross");
            float net = gross.floatValue() – 2000;
            request.setAttribute("net", new Float(net));
      }
}
Note : emp.html and web.xml from the previous applications.

HttpServlet Basics

Skeleton Structures of a HttpServlet :
import java.io.*;
import java.servlet.*;
import java.servlet.http.*;
public class MyServlet extends HttpServlet {
      public void init(ServletConfig config) throws ServletException {
            // Resource Allocation;
      }
      public void destroy() {
            // Resource Deallocation;
      }
      public void doGet/doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            // Client Request Process Code;
      }
}
Note : From the browser if the request is coming get format, we have to write doGet() method in our Servlet as the servicing method. If the browser request type is of Post type, we need to go for doPost() method.

Q) What are the different between GET and POST Methods ?

These are Http request method. Http client (Web Client/Browser) user any one of these two methods to send a request to Http Server (Web Server).

Http Life Cycle

HttpServlet Life Cycle is similar to that of GenericServlet in initialization and destruction. Servlet or Servicing phase has slight variance. Servlet engine creates ServletRequest and ServletResponse objects servlet engine calls service() method. This service() method is public method. The code of this method is implemented in HttpServlet class.

This method does two things :
1. Converting request and response object into Http specific object.
2. Calling protected (method) service method.

Protected Service method takes HttpServletRequest and HttpServletResponse as arguments.
This method is defined in the library class method javax.servlet.http.HttpServlet.

1. Evaluating the request object to find out the kind of request used by the web client.
    String m = request.getMethod();

2. if(m.equals("GET"));
        doGet(request, response);
    if(m.equals("POST"));
        doPost(request, response);

Q) Web Application to implement "GET" request processing ?

GetApp
  emp.html
WEB-INF
  web.xml
classes
  DataBaseServlet.class
lib
  classes12.jar

Web URL : http://localhost:8080/GetApp

HTML File Name : emp.html <html> <body bg-color = "wheat"> <center> <form action = "./emp" method = "get"> Employee No <input type = "text" name = "empno"/> <input type = "submit" value = "Send"/> </form> </center> </body> </html> XML File Name : web.xml : <web-app> <servlet> <servlet-name> jdbc </servlet-name> <servlet-class> DataBaseServlet </servlet-class> <init-param> <param-name> driver </param-name> <param-value> oracle.jdbc.driver.OracleDriver </param-value> </init-param> <init-param> <param-name> url </param-name> <param-value> jdbc:oracle:thin:@localhost:1521:orcl </param-value> </init-param> <init-param> <param-name> username </param-name> <param-value> scott </param-value> </init-param> <init-param> <param-name> pass </param-name> <param-value> tiger </param-value> </init-param> </servlet> <servlet-mapping> <servlet-name> jdbc </servlet-name> <url-pattern> /emp </url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file> emp.html </welcome-file> </welcome-file-list> </web-app> Serlvet Class Name : DataBaseServlet.java

import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class DataBaseServlet extends HttpServlet {
      Connection con;
      public void init() throws ServletException {
            String d = getInitParameter("driver");
            String u = getInitParameter("url");
            String us = getInitParameter("user");
            String pwd = getInitParameter("pass");
            try {
                  Class.forName(d);
                  con = DriverManager.getConnection(u, us, pwd);
                  System.out.println("Connection is established");
            } catch(ClassNotFoundException e) {
                  System.out.println(e);
            } catch(SQLException e) {
                  System.out.println("Unable to established the Connection");
            }
      }
      public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
            int empno = Integer.parseInt(request.getParameter("empno"));
            response.setContentType("text/html");
            PrintWriter pw = response.getWriter();
            try {
                  pw.println("<html>");
                  pw.println("<body bg-color = "wheat" >");
                  pw.println("<center>");
                  Statement st = con.createStatement();
                  String sql = "SELECT * FROM EMPLOYEE WHERE empno = " + empno;
                  ResultSet rs = st.executeQuery(sql);
                  if(rs.next()) {
                        pw.println("<h2> Employee Details </h2>");
                        pw.println("<table border = 1 cellpadding = 3 cellspacing = 0");
                        pw.println("<tr>");
                        pw.println("<td align = right width=100>" + Emp No + " </td>");
                        pw.println("<td align = right width=100>" + Name + " </td>");
                        pw.println("<td align = right width=100>" + Salary + " </td>");
                        pw.println("</tr>");
                        pw.println("<tr>");
                        pw.println("<td align = right width=100>" + empno + " </td>");
                        pw.println("<td align = right width=100>" + rs.getString(2) + " </td>");
                        pw.println("<td align = right width=100>" + rs.getFloat(3) + " </td>");
                        pw.println("</tr>");
                        pw.println("</table>");
                  } else {
                        pw.println("<h2> Employee Record not found </h2>");
                        pw.println("</center>");
                        pw.println("</body>");
                        pw.println("</html>");
                        pw.close();
                        rs.close();
                        st.close();
            } catch(SQLException e) {
                  System.out.println(e);
            }
      }
      public void destroy () {
            if(con != null) {
                  try { con.close() } catch(Exception e) { }
                  System.out.println("Connected Closed");
            }
      }
}

Q) How many init methods are given by the

1. init(ServletConfig );
2. init();

Servlet engine does not call zero arguments init () method. It always calls parameterized init() method. Parameterized init() method given by the GenericServlet calls zero argument init() method. Always it is advisable to override zero argument init() method in our own servlets. We get are flexibility, what ever the method of ServletConfig, directly we can call on the Servlet. These is no need of directly using "Config" object. This is possible because GenericServlet implements ServletConfig object. Originally init is holds the Servlet.


Q) Example web application to implemented POST request processing ?

PostApp
  emp.html
WEB-INF
  web.xml
classes
  PostServlet.class
lib
  classes12.jar

Web URL : http://localhost:8080/postapp/emp.html

HTML File Name : emp.html <html> <body bg-color = "wheat"> <center> <form action = "./pstmt" method = "post"> <h2> Employee Details </h2> Employee No <input type = "text" name = "empno"/> <br/> <br/> Name <input type = "text" name = "name"/> <br/> <br/> Salary <input type = "text" name = "salary"/> <br/> <br/> <input type = "submit" name = "click" value = "Insert"/> </form> </center> </body> </html> XML File Name : web.xml <web-app> <servlet> <servlet-name> insert </servlet-name> <servlet-class> PostServlet </servlet-class> </servlet> <servlet-mapping> <servlet-name> insert </servlet-name> <url-pattern> /pstmt </url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file> emp.html </welcome-file> </welcome-file-list> </web-app> Servlet File Name : PostServlet.java

import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.html.*;
public class PostServlet extends HttpServlet {
      Connection con;
      PreparedStatement ps;
      public void init() throws ServletException {
            try {
                  Class.forName("oracle.jdbc.driver.OracleDriver");
                  con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:ord", "scott", "tiger");
                  ps = con.preparedStatement("INSERT INTO EMPLOYEE VALUES (?,?,?)");
            } catch(ClassNotFoundException e) {
                  System.out.println(e);
            } catch(ClassNotFoundException e) {
                  System.out.println("Unable to establish the Connection");
            }
      }
      public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            int empno = Integer.parseint(request.getParameter("empno"));
            String name = request.getParameter("name");
            float salary = Float.parseint(request.getParameter("salary"));
            response.setContentType("text/html");
            PrintWriter out = response.getWriter();
            try {
                  ps.setInt(1, empno);
                  ps.setString(2, name);
                  ps.setFloat(3, salary);
                  ps.executeUpdate();
                  System.out.println("Record Inserted Successfully");
                  ServletContext sc = getServletContext();
                  RequestDispatcher rd = sc.getRequestDispatcher("/emp.html");
                  rd.include(request, response);
            } catch(SQLException e) {
                  System.out.println(e);
            }
      }
      public void destroy() {
            if(ps != null) {
                  try { ps.close() } catch(Exception e) { System.out.println("Prepared Statement Closed"); }
            }
            if(con != null) {
                  try { con.close() } catch(Exception e) { System.out.println("Connection Closed"); }
            }
      }
}

Session Tracking

We have two types of protocols.
1. Stateless (or) Connection Less : A protocol is said to be stateless, if the server has got no memory of prior connections and it can not distinguish one client request from that of the other.
Example : HTTP

2. Statefull (or) Connection Oriented : The protocol is said to be statefull, if the server has got the memory of prior connections and it can distinguish one client request from that of the server.
Example : FTP.

Session : The duration at time, the server is able to recognize the client in a series of client server inter-action is known as a Session.

Session Tracking : The ability of the server to recognize the client uniquely and associating each request with a particular client is known as Session Tracking.
A far as Servlet API support is concerned. We three machanisms to implements Session Tracking.
1. HttpSession Object Usage.
2. Cookies.
3. URL Rewriting.

Session Tracking using HttpSession :
Step 1 : Creating the session.
Step 2 : Dealing with Client State by using attribute() method.
Step 3 : Session time out or log out maintainces.

Q) Example Web Application in which two Servlets share data in Session Scope ?

SessionApplication
  data.html
WEB-INF
  web.xml
classes
  SourceServlet.class
  TargetServlet.class

HTML File Name : data.html

<html> <body bg-color = "green"> <center> <form action = "./source"> <h2> Book ISBN </h2> Employee No <input type = "text" name = "t1"/> <input type = "submit" value = "Submit"/> </form> </center> </body> </html> XML File Name : web.xml <web-app> <servlet> <servlet-name> source </servlet-name> <servlet-class> SourceServlet </servlet-class> </servlet> <servlet> <servlet-name> target </servlet-name> <servlet-class> TargetServlet </servlet-class> </servlet> <servlet-mapping> <servlet-name> source </servlet-name> <url-pattern> /source </url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name> target </servlet-name> <url-pattern> /target </url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file> data.html </welcome-file> </welcome-file-list> </web-app> Servlet Class Name : SourceServlet.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.html.*;
public class SourceServlet extends HttpServlet {
      public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            String isbn = request.getParameter("t1");
            HttpSession s = request.getSession();
            s.setAttribute("bno", isbn);
            System.out.println(s.getId());
            System.out.println(s.getMaxInactiveInterval());
            s.setMaxInactiveInterval(180);
            response.setContentType("text/html");
            PrintWriter out = response.getWriter();
            out.println("<a href=./target> Get Book Number Here </a> ");
            out.close();
      }
}

Serlvet Class Name : TargetServlet.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.html.*;
public class TargetServlet extends HttpServlet {
      public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            HttpSession s = request.getSession();
            System.out.println(s.getId());
            System.out.println(s.getNew());
            System.out.println(s.getMaxInactiveInterval());
            String bookno = (String) s.getAttribute("bno");
            response.setContentType("text/html");
            PrintWriter out = response.getWriter();
            out.println("<h1> Book Number is : " + bookno + "</h1>");
            out.close();
      }
}

Q) What happen in the background when request.getSession() method as called ?

Container does the following things :
1. If every evaluates the Http request headers to retrieved the Session id coming from the browser.
  Case 1 : If session id is not found, the container creates the new session object and associated session id.
  Case 2 : If session id comes from the browser, it looks for the match for the corresponding session object. In this case new session object is not created.
2. getSession() method return the reference of either new Session object or existing Session object.
3. Container writes the session id into the response object, when the servlet sends the response to the client along with the response headers, session id is sent to the browser.

Q) What do you know about Session Time Out ?

Between two client requests, if the (Inactive Period) time gap is beyond a configurable specified limit, the container forabily logs the client out such forcible implicit logging out is said to be "Session Time Out".
Note : When the end user options for the explicits logout still we need to destroy the session object, we do so by calling, s.invalidate();

Q) Example Web Application to implement Session Tracking using HttpSession Object ?

LoginApp
  login.html
WEB-INF
  web.xml
classes
  AuthenticationServlet.class
lib
  classes12.jar

Web URL : http://localhost:8080/loginapp/login.html

HTML File Name : login.html <html> <body bg-color = "cyan"> <center> <form action = "./authenticate" method = "post"> <h2> Login to Our Web Site </h2> User Name <input type = "text" name = "user"/> <br/> Password <input type = "text" name = "pass"/> <br/> <input type = "submit" value = "Click Here To Login"/> </form> </center> </body> </html> XML File Name : web.xml <web-app> <servlet> <servlet-name> login </servlet-name> <servlet-class> AuthenticationServlet </servlet-class> </servlet> <servlet-mapping> <servlet-name> login </servlet-name> <url-pattern> /authenticate </url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file> login.html </welcome-file> </welcome-file-list> </web-app> Servlet Class Name : AuthenticationServlet.java

import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.html.*;
public class AuthenticationServlet extends HttpServlet {
    Connection con;
    public void init(ServletConfig config) throws ServletException {
        try {
            Class.forName("oracle.jdbc.driver.OracleDriver");
            String url = "jdbc:oracle:thin:@localhost:1521:ord";
            con = DriverManager.getConnection(url, "scott", "tiger");
        } catch(ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Statement st = null;
        ResultSet rs = null;
        String user = request.getParameter("user");
        String pwd = request.getParameter("pass");
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<html>");
        out.println("<body bg-color = "wheat">");
        try {
                st = con.createStatement();
                String sql = "SELECT * FROM OUR_USERS USER = " + user + "AND PASSWORD = " + pwd + "";
                rs = st.executeQuery(sql);
                if(rs.next()) {
                        out.println("<h2> Welcome " + user + " To Our Web Site </h2>");
                } else {
                        out.println("<h2> Invalid User or Password </h2>");
                        out.println("<a href = "./login.html"> Login Again </a>");
                }
        } catch(Exception e) {
                e.printStackTrace()
        }
        finally {
                try {
                if(rs != null) { rs.close() }
                if(st != null) { st.close() }
        } catch(Exception e) { e.printStackTrace() }
        out.println("</body>");
        out.println("</html>");
        out.close();
        }
    }
    public void destroy() {
        try {
                if(con != null) {
        } catch(Exception e) { e.printStackTrace(); }
    }
}

Cookies

A Cookies is a name, value pair based textuial piece of information that is exchanged between server and client. Http concept any ASP are also cookies. Cookes is server side create.
We have two kinds of cookies.
1. Session Cookies (or) Tempary Storage
2. Persistent Cookies (or) Perment Storage

Session Cookies is that cookies which is available in the client side only for the duration of the browser session. Persistent Cookies are stored in the client machine’s file system.

Step to implement Persistent Cookies :

Step 1 : Create a Cookies by instantiating javax.servlet.http cookies class.
For Example : Cookie C1 = new Cookie("Sport","Foot Ball");
                          Cookie C2 = new Cookie("Stock Quote","IBM");
                          Cookie C3 = new Cookie("Usr","Devid");
                          Cookie C4 = new Cookie("Profession","Doctor");
Step 2 : Making the Cookie Persistent.
                          C1.setMaxAge(int Seconds);
For Example : C1.setMaxAge(180 * 24 * 3600);
Step 3 : Sending the Cookie to the client.
                          response.addCookie(C1);
                          response.addCookie(C2);
                          response.addCookie(C3);
Step 4 : Receiving the Cookies Cookies C [] = request.getCookies();

Step to implement Session Cookies :

Step 1 : Create a Cookies by instantiating javax.servlet.http cookies class.
For Example : Cookie C1 = new Cookie("Sport","Foot Ball");
                          Cookie C2 = new Cookie("Stock Quote","IBM");
                          Cookie C3 = new Cookie("Usr","Devid");
                          Cookie C4 = new Cookie("Profession","Doctor");
Step 3 : Sending the Cookie to the client.
                          response.addCookie(C1);
                          response.addCookie(C2);
                          response.addCookie(C3);
Step 4 : Receiving the Cookies Cookies C [] = request.getCookies();

Application of Cookies (or) Usage of Cookies :

Cookies are used in the following areas :
1. To recognize the client uniquely.
2. Identifying a particular user.
3. Keeping track of user preferences.
4. Targeted advertisement.

Q) Example Web Application to implement Persistent Cookie Concept ?

CookieApp
  cookieExample.html
  welcome.html
WEB-INF
  web.xml
classes
  CreateCookie.class
  CheckCookie.class

URL : http://localhost:8080/CookieApp/cookieExample.html

HTML File Name : cookieExample.html <html> <body bg-color = "cyan"> <center> <h2> Welcome To Shopping Mall </h2> <form action = "./create" method = "post"> User Name <input type = "text" name = "user"/> <br/> <br/> <input type = "submit" value = "Welcome"/> <br/> <br/> </form> </center> </body> </html> HTML File Name : welcome.html <html> <body> <marquee> <font color = "green" size = "6"> Welcome To Shopping Mall </font> </marquee> </body> </html> XML File Name : web.xml : <web-app> <servlet> <servlet-name> create </servlet-name> <servlet-class> CreateCookie </servlet-class> </servlet> <servlet> <servlet-name> check </servlet-name> <servlet-class> CheckCookie </servlet-class> </servlet> <servlet-mapping> <servlet-name> create </servlet-name> <url-pattern> /create </url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name> check </servlet-name> <url-pattern> /check </url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file> cookieExample.html </welcome-file> </welcome-file-list> </web-app> Servlet Class Name : CreateCookie.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.html.*;
public class CreateCookie extends HttpServlet {
      public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            String user = request.getParameter("user");
            response.setContentType("text/html");
            PrintWriter out = response.getWriter();
            Cookie c = new Cookie("user", user);
            c.setMaxAge(120);
            out.println("<html>");
            out.println("<body bg-color = "wheat"> <center>");
            request.getRequestDispatch("/welcome.html").include(request, response);
            out.println("<h2> <a href=./check> Shopping Goes Here </a> </h2>");
            out.println("</center> </body> </html>");
            out.close();
      }
}

Servlet Class Name : CheckCookie.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.html.*;
public class CheckCookie extends HttpServlet {
      public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            response.setContentType("text/html");
            PrintWriter out = response.getWriter();
            Cookie c [] = request.getCookies();
            String user = null;
            out.println("<html> <body bg-color = "wheat"> </h2>");
            if( c != null) {
                  for(int i = 0; i < c.length; i++) {
                        if(c[i].getName().equals("user")) {
                              user = c[i].getValue();
                              break;
                        }
                  }
            }
            out.println("<h1> Hai " + user + "I hope enjoy shopping here </h1>");
            out.close();
      }
}

URL Rewriting

Appending session id to the URL is known as URL Rewriting. When we are using HttpSession object to implement Session Tracking, the container uses implicit cookie mechanism to send the session id. If cookies are disabled in the browser, session id will not be sent back by the browser that is session tracking fails. URL Rewriting is an alternative to this problem.

How to implement URL Rewriting : To implement URL Rewriting the method is used response.encodeURL("url");

Example Program of URL Rewriting

UrlRewritingApp
  user.html
WEB-INF
  web.xml
classes
  SourceServlet.class
  TargetServlet.class

URL : http://localhost:8080/UrlRewritingApp/user.html

HTML File Name : user.html <html> <body bg-color = "green"> <center> <form action = "./source"> <h2> User </h2> Employee No <input type = "text" name = "t1"/> <input type = "submit" value = "Submit"/> </form> </center> </body> </html> XML File Name : web.xml :
<web-app> <servlet> <servlet-name> one </servlet-name> <servlet-class> SourceServlet </servlet-class> </servlet> <servlet> <servlet-name> two </servlet-name> <servlet-class> TargetServlet </servlet-class> </servlet> <servlet-mapping> <servlet-name> one </servlet-name> <url-pattern> /source </url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name> two </servlet-name> <url-pattern> /target </url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file> user.html </welcome-file> </welcome-file-list> </web-app> Servlet Class Name : SourceServlet.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.html.*;
public class SourceServlet extends HttpServlet {
            public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            String user = request.getParameter("t1");
            HttpSession s = request.getSession();
            s.setAttribute("rsu", user);
            response.setContentType("text/html");
            PrintWriter out = response.getWriter();
            out.println("<a href = " + response.encodeUrl("./target") + "> Get User Name Here </a> ");
            out.close();
      }
}

Servlet Class Name : TargetServlet.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.html.*;
public class TargetServlet extends HttpServlet {
      public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            HttpSession s = request.getSession();
            System.out.println(s.getNew());
            String user = (String) s.getAttribute("rsu");
            response.setContentType("text/html");
            PrintWriter out = response.getWriter();
            out.println("<h1> User is : " + user + "</h1>");
            out.close();
      }
}

HTTP Status Code

Status Code Status Description
200 OK Success
400 Bad Request Error with the input Parameters
404 Not Found Requested Entity Not Found
403 Not Authorized When We Pass Wrong API Key
500 Interner Server Error Error due to Wrong Data, Data Base, SMTP or Other External Dependencies