Advanced Java Module-4 Notes
Advanced Java Module-4 Notes
Introduction
• Servlets are the Java programs that run on the Java-enabled web server or application server.
They are used to handle the request obtained from the webserver, process the request,
produce the response, then send a response back to the webserver.
• Properties of Servlets are as follows:
1.Servlets work on the server-side.
2.Servlets are capable of handling complex requests obtained from the webserver.
• Servlet Architecture is can be depicted as follows:
What is CGI?
• CGI is actually an external application that is written by using any of the programming languages
like C or C++ and this is responsible for processing client requests and generating dynamic content.
• In CGI application, when a client makes a request to access dynamic Web pages, the Web server
performs the following operations :
1. It first locates the requested web page i.e the required CGI application using URL.
2. It then creates a new process to service the client’s request.
3. Invokes the CGI application within the process and passes the request information to the
application.
4. Collects the response from the CGI application.
5.Destroys the process, prepares the HTTP response, and sends it to the client.
Advanced Java (BIS402) Dr. Vani V 3
So, in CGI server has to create and destroy the process for every request. It’s easy to
understand that this approach is applicable for handling few clients but as the number of clients
increases, the workload on the server increases and so the time is taken to process requests
increases.
Swing Is Built
The Life Cycleon
ofthe AWT
a Servlet
`As displayed in the diagram, there are three states of a servlet: new, ready and end. The
servlet is in new state if servlet instance is created. After invoking the init() method,
Servlet comes in the ready state. In the ready state, servlet performs all the tasks. When
the web container invokes the destroy() method, it shifts to the end state.
1. Servlet class is loaded : The classloader is responsible to load the servlet class. The
servlet class is loaded when the first request for the servlet is received by the web
container.
2. Servlet instance is created : The web container creates the instance of a servlet
after loading the servlet class. The servlet instance is created only once in the servlet
life cycle.
3. init method is invoked : The web container calls the init method only once after
creating the servlet instance. The init method is used to initialize the servlet. It is the
life cycle method of the javax.servlet.Servlet interface. Syntax of the init method
given below:
public void init(ServletConfig config) throws ServletException
4. service method is invoked: The web container calls the service method each time
when request for the servlet is received. If servlet is not initialized, it follows the first
three steps as described above then calls the service method. If servlet is initialized, it
calls the service method. Notice that servlet is initialized only once. The syntax of the
service method of the Servlet interface is given below:
public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException
5. destroy method is invoke : The web container calls the destroy method before
removing the servlet instance from the service. It gives the servlet an opportunity to
clean up any resource for example memory, thread etc. The syntax of the destroy
method of the Servlet interface is given below:
public void destroy() Dr. Vani V 6
The Life Cycle of a Servlet
• Three methods are central to the life cycle of a servlet. These are init( ), service( ), and destroy( ). They are
implemented by every servlet and are invoked at specific times by the server. Let us consider a typical user
scenario to understand when these methods are called.
1. First, a user enters a Uniform Resource Locator (URL) to a web browser. The browser then generates an
HTTP request for this URL. This request is then sent to the appropriate server.
2. Second, this HTTP request is received by the web server. The server maps this request to a particular
servlet. The servlet is dynamically retrieved and loaded into the address space of the server.
3. Third, the server invokes the init( ) method of the servlet. This method is invoked only when the servlet is
first loaded into memory. It is possible to pass initialization parameters to the servlet so it may configure
itself.
4. Fourth, the server invokes the service( ) method of the servlet. This method is called to process the HTTP
request. You will see that it is possible for the servlet to read data that has been provided in the HTTP
request. It may also formulate an HTTP response for the client. The servlet remains in the server’s address
space and is available to process any other HTTP requests received from clients. The service( ) method is
called for each HTTP request.
5. Finally, the server may decide to unload the servlet from its memory. The server calls the destroy( )
method to relinquish any resources such as file handles that are allocated for the servlet. The memory
allocated for the servlet and its objects can then be garbage collected.
Dr. Vani V 7
Dr. Vani V 8
Using Tomcat
• Tomcat contains the class libraries, documentation, and run-time support that we will need to create
and test servlets. Several versions of Tomcat are available.
• The instructions that follow use 7.0.47.
• You can download Tomcat from tomcat.apache.org. You should choose a version appropriate to
your environment. Assuming that a 64-bit version of Tomcat 7.0.47 was unpacked from the root
directly, the default location is
C:\apache-tomcat-7.0.47-windows-x64\apache-tomcat-7.0.47\
• If you load Tomcat in a different location (or use a different version of Tomcat), you will need to make
appropriate changes to the examples. You may need to set the environmental variable JAVA_HOME
to the top- level directory in which the Java Development Kit is installed.
• Once installed, you start Tomcat by selecting startup.bat from the bin directly under the apache-
tomcat-7.0.47 directory. To stop Tomcat, execute shutdown.bat, also in the bin directory.
• The classes and interfaces needed to build servlets are contained in servlet-api.jar, which is in the
following directory:
C:\apache-tomcat-7.0.47-windows-x64\apache-tomcat-7.0.47\lib
• To make servlet-api.jar accessible, update your CLASSPATH environment variable so that it includes
C:\apache-tomcat-7.0.47-windows-x64\apache-tomcat-7.0.47\lib\servlet-api.jar
• Alternatively, you can specify this file when you compile the servlets. For example, the following
command compiles the first servlet example:
javac HelloServlet.java -classpath "C:\apache-tomcat-7.0.47-windows- x64\apache-tomcat-
7.0.47\lib\servlet-api.jar"
Dr. Vani V 9
• Once you have compiled a servlet, you must enable Tomcat to find it. For our purposes, this means
putting it into a directory under Tomcat’s webapps directory and entering its name into a web.xml
file. Here is the procedure that you will follow.
• First, copy the servlet’s class file into the following directory:
C:\apache-tomcat-7.0.47-windows-x64\apache-tomcat-7.0.47\webapps\examples\WEB-
INF\classes
• Next, add the servlet’s name and mapping to the web.xml file in the following directory:
C:\apache-tomcat-7.0.47-windows-x64\apache-tomcat-7.0.47\webapps\examples\WEB-INF
For instance, assuming the first example, called HelloServlet, you will add the following lines in the
section that defines the servlets:
1. To begin, create a file named HelloServlet.java that contains the following program:
import java.io.*;
import javax.servlet.*;
public class HelloServlet extends GenericServlet {
public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>Hello!");
pw.close();
}
}
2. Start Tomcat : Tomcat must be running before you try to execute a servlet.
3. Start a Web Browser and Request the Servlet: Start a web browser and enter the URL shown here:
http://localhost:8080/examples/servlets/servlet/HelloServlet
Alternatively, you may enter the URL shown here:
http://127.0.0.1:8080/examples/servlets/servlet/HelloServlet
Dr. Vani V 14
The ServletContext Interface
• The ServletContext interface enables
servlets to obtain information about
their environment.
Compile the servlet. Next, copy it to the appropriate directory, and update the web.xml
File. Then, perform these steps to test this example:
1. Start Tomcat (if it is not already running).
2. Display the web page in a browser.
3. Enter an employee name and phone number in the text fields.
4. Submit the web page.
After following these steps, the browser will display a response that is dynamically
generated by the servlet.
The HttpServletResponse
Interface
Dr. Vani V
Session Tracking
• HTTP is a stateless protocol. Each request is
independent of the previous one. However, in some
applications, it is necessary to save state information
so that information can be collected from several
interactions between a browser and a server. Sessions
provide such a mechanism.
• A session can be created via the getSession( ) method
of HttpServletRequest. An HttpSession object is
returned. This object can store a set of bindings that
associate names with objects.
• The setAttribute( ), getAttribute( ), getAttributeNames(
), and removeAttribute( ) methods of HttpSession
manage these bindings. Session state is shared by all
servlets that are associated with a client.
• The following servlet illustrates how to use session
state. The getSession( ) method gets the current
session. A new session is created if one does not
already exist. The getAttribute( ) method is called to
obtain the object that is bound to the name "date".
That object is a Date object that encapsulates the date
and time when this page was last accessed. A Date
object encapsulating the current date and time is then
created.
• The setAttribute( ) method is called to bind the name
"date" to this object
Advanced Java (BIS402) Dr. Vani V 26
26
Java Server Pages (JSP)
• A JSP (Java Server Page) is a server-side technology which is used for creating web
applications. It is used to create dynamic web content. JSP consists of both HTML tags
and JSP tags. In this, JSP tags are used to insert JAVA code into HTML pages. It is an
advanced version of Servlet Technology i.e. a web-based technology that helps us to
create dynamic and platform-independent web pages.
• Java code can be inserted in HTML/ XML pages or both. JSP is first converted into a
servlet by the JSP container before processing the client’s request.
• A JSP is called by a client to provide web services, the nature of which depends on client
• application.
• There are three methods that are automatically called when JSP is requested and when
JSP terminates normally. These are the JSPInit() method , the JSPDestroy() method
and service() method.
• A JSPInit() is identical to init() method of java servlet. It is called when first time JSP is
called.
• A JSPDestroy() is identical to destroy() method of servlet. The destroy() method is
automatically called when JSP terminates normally. It is not called when JSP terminates
abruptly. It is used for placing clean up codes.
• The sevice() method is automatically called and retrieves a connection to HTTP.
JSP Tags
• A JSP tag consists of a combination of HTML tags and JSP tags. JSP tags define java code that is to be
executed before the output of JSP program is sent to the browser.
• A JSP tag begin with a <%, which is followed by java code , and ends with %>,
• There is an XML version of JSP tag <jsp:TagID> </jsp:TagID>
• A JSP tags are embedded into the HTML component of a JSP program and are processed by JSP virtual
engine such as Tomcat.
• Java code associated with JSP tag are executed and sent to browser by tomcat.
Methods
Methods are defined same way as it is defined in java program, except these are placed in JSP
tag. Methods are declared in JSP declaration tag. The JSP calls method inside the expression
tag.
Example:
<html> <html>
<head> <head>
<title> JSP Programming </title> <title> JSP Programming </title>
<\head> <\head>
<body> <body>
<%! int add(int n1, int n2) <%! boolean curve(int grade)
{ {
int c; return 10+grade;
c=a+b; }
return c; boolean curve(int grade, int curveValue)
} {
%> return curveValue+grade;
<p> Addition of two numbers : <%= add(45,46)%> </p> }
</body>
</html> %>
</body>
</html>
Loops
• JSP loops are nearly identical to loops that we use in our java program except that we can
repeat the html tags and related information multiple times within the JSP program.
• There are three kind of JSP loop that are commonly used in JSP program. Ex: for loop ,
while loop , do while .
• Loop plays an important role in JSP database program because loops are used to populate
HTML tables with data in the result set.
Example:
<%! int[] grade = {100, 82, 93}; <%! int[] grade = {100, 82, 93};
<html> <%! int[] grade = {100, 82, 93};
int x=0;%> int x=0;%>
<head> int x=0;%>
<table> <table>
<title> For Loop Example</title> <table>
<tr> <tr>
<tr>
<\head> <td> First </td> <td> First </td>
<td> First </td>
<body> <td> Second </td> <td> Second </td>
<td> Second </td>
<td> Third </td> <td> Third </td>
<% <td> Third </td>
</tr> </tr>
for (int i = 0; i < 10;i++) { </tr>
<tr> <tr>
%> <tr>
<% while(x<3 { %> <% x=0;
<% for(int I;i<3;i++) { %>
<p> Hello World</p> <td> <%= grade[x] %> </td> do { %>
<td> <%= grade[i] %> </td>
<% } %> <% x++; <td> <%= grade[x] %> </td>
<% } %
</body> }% <% x++;
</tr>
</tr> } while(x<3) %
</html> </table>
</table> </tr>
</table>
Request String
• A browser generate requst string whenever the submit button is selected. The user requests
the string consists of URL and the query the string.
• Example of request string:
http://www.jimkeogh.com/jsp/myprogram.jsp?fname=“Bob”&lname=“Smith”
• Your jsp program needs to parse the query string to extract the values of fields that are to be
processed by your program. You can parse the query string by using the methods of the
request object.
• getParameter(Name) method is used to parse a value of a specific field and it requires an
argument which is the name of the field whose value we want to retrieve.
<%! String FirstName =requst.getParameter(fname);
String LastName =requst.getParameter(lname); %>
• Copying from multivalued field such as selection list field can be tricky. The multivalued
fields are handled by using getParameterValues()
• Other than request string URL has protocols, port no, the host name etc.
• The request string sent to the JSP by the browser is divided into two general
components that are separated by question mark. The URL component appears to the
left of the question mark and the query string is to the right of the question mark.
The URL is divided into four parts: protocol, host, port and virtual path.
• The protocol defines the rules that are used to transfer the request string from the
browser to the JSP program. Three commonly used protocols are HTTP, HTTPS and
FTP.
• Next is the host and port combination. The host is Internet Protocol (IP) address or the
name of the server that contains JSP program. Port number is the port that the host
monitors. Usually port is excluded form request string whenever HTTP is used because
the assumption is the host is monitoring port 80.
• Following the host and port is the virtual path of the JSP program. The server maps the
virtual path to the physical path.
• In the above request string, the protocol is HTTP, the host is www.jimkeogh.com. There
is no port number and the virtual path is /jsp/myprogram.jsp
Dr. Vani V 39
Dr. Vani V 41