Professional Documents
Culture Documents
Author(s)
Yuvarani Meiyappan
Authorized by
Creation/Revision Date
Version
Srikantan Moorthy
Jun-2010
1.1
INTERNAL
COPYRIGHT NOTICE
All ideas and information contained in this document are the intellectual property of
Education and Research Department, Infosys Technologies Limited. This document is not for
general distribution and is meant for use only for the person they are specifically issued to.
This document shall not be loaned to anyone, within or outside Infosys, including its
customers. Copying or unauthorized distribution of this document, in any form or means
including electronic, mechanical, photocopying or otherwise is illegal.
Jun 2010
Author(s)
Vaishali S Mudkhedkar
Raoke
Shashidhar H Basavaraju
ER/CORP/CRS/ED113A/007
Reviewer(s)
Comments
Initial Draft
Yuvarani
Meiyappan
Table of Contents
Contents
COPYRIGHT NOTICE ...................................................................................................... II
DOCUMENT REVISION HISTORY ......................................................................................... I
CONTENTS .................................................................................................................. II
CONTEXT ................................................................................................................... 1
DAY 1 ASSIGNMENTS ..................................................................................................... 1
ASSIGNMENT 1: DEVELOPING WEB APPLICATION WITH ECLIPSE ............................................................. 1
ASSIGNMENT 2: DEVELOP GENERIC AND HTTP SERVLETS AND LEARN THE SERVLET LIFECYCLE ............................ 13
ASSIGNMENT 3: DEVELOP A SERVLET, DEPLOY IT ON TOMCAT WEB CONTAINER, AND ACCESS IT THROUGH HTML ......... 24
ASSIGNMENT 4: EXPORTING THE PROJECT INTO A WAR AND CREATING THE MANUAL DEPLOYMENT FOR TOMCAT WEB
CONTAINER ............................................................................................................... 26
ASSIGNMENT 5: DEVELOPING WEB APPLICATION USING SERVLETS AND DEPLOYING IT ON TOMCAT WEB CONTAINER, IN
ABSENCE OF IDE .......................................................................................................... 30
SELF REVIEW QUESTIONS ................................................................................................. 39
ER/CORP/CRS/ED113A/007
ii
Context
This document contains assignments to be completed as part of the hands on for the subject
Presentation tier using JSP and JSF (Course code: ED113A).
Note: In order to complete the course, assignments in this document must be completed in the
sequence mentioned.
Day 1 Assignments
Assignment 1: Developing Web Application with Eclipse
Objective: To understand how to develop and deploy a simple web application using Eclipse.
Problem Description: Develop a simple web application using Eclipse.
Estimated time: 30 Min
Theory: IDEs (Integrated Development Environment) help us in developing and deploying web
applications easily.
IDE provides environment, which facilitates creation, compilation/building (compiling) and
deploying of the web application on click of a button.
Eclipse is one such IDE, which is open source and most popularly used in Java web application
development. We will use Eclipse Ganymede V3.4.2 in our hands on.It has built-in editor,
debugger, compiler and Auto deployment capability (Run on Server) under one umbrella.
Other popular IDEs are NetBeans, JDeveloper, etc
Step 1: Let us build our first web application using eclipse. Create a new workspace, say
PresentationTier.
ER/CORP/CRS/ED113A/007
Step 2: Now Eclipse is opened up with the below welcome screen. It provides you with many icons
to use how to help facility. Close this window. You will see the Eclipse opened in Java
perspective; change it to Java EE perspective. Till now, you were working in Java perspective,
from this course, you will be using Java EE perspective, as in this perspective, you will find all the
required tools required to develop and deploy web applications/enterprise application.
ER/CORP/CRS/ED113A/007
Step 3: Let us add server to the perspective. We can do that many ways. Let us do it in the easiest
way. Right click on the server tab, as shown in the screen shot. It will open up a dialog box, which
is a wizard to add a new server. Many servers are listed, locate Apache - > Tomcat v6.0 server
Note: We are going to add Tomcat 6.0 server, but the same steps could be
used to add JBoss Application Server. It is under JBoss -> JBoss v5.0
On your systems, Tomcat would be located through softgrid. So to select the
installation directory, browse through Computer -> SoftGrid (Q:) ->
JBOSS.002 -> Soft ->tomcat 6
ER/CORP/CRS/ED113A/007
So, after selecting Tomcat v6.0 server, click on Next button. You get the below screen shot, as you
are performing this activity for the first time.
ER/CORP/CRS/ED113A/007
Now we will select the Application Server Directory, by clicking Browse button. Locate your
servers installation directory, as already mentioned in first assignment, our Tomcat 6.0
installation directory is D:\Program Files\Apache Software Foundation\Tomcat 6.0
On your systems, Tomcat would be located through softgrid. So to select the installation directory,
browse through Computer -> SoftGrid (Q:) -> JBOSS.002 -> Soft ->tomcat 6
ER/CORP/CRS/ED113A/007
Click on OK, and then Finish. Now you see a server is added to the Server tab. There on the same
tab you see a small green arrow button, this is to start the server. A small rectangle red button is
to stop the server.
ER/CORP/CRS/ED113A/007
ER/CORP/CRS/ED113A/007
Step 5: Let us create a Servlet named, ClientBrowserInfoServlet. Right Click on the Application
Folder name. Select New->Servlet, a wizard will open up, wherein you need to give name of the
class (ClientBrowserInfoServlet), and the package in which you need to create it.
ER/CORP/CRS/ED113A/007
Click on Next, and you will be prompted with next dialog box as below:
Here you can enter servlet deployment descriptor specific information. We can provide description
for our servlet, initialization parameters, if any. We are going to change the URL Mappings, we
want
user
to
access
this
servlet
using
/info
url
appended
to
http://localhost:8080/ServletDemoOne
i.e. in order to access our servlet, the URL would be
http://localhost:8080/ServletDemoOne/info
Click on Finish, and then add the business logic, to create the dynamic content in the servlet class.
Business Logic: We are going to display the browser specific details, received by the server
through HttpServletRequest object.
ER/CORP/CRS/ED113A/007
ClientBrowserInfoServlet.java
package com.infy.enr.servlets;
import java.io.IOException;
import java.io.PrintWriter;
import
import
import
import
javax.servlet.ServletException;
javax.servlet.http.HttpServlet;
javax.servlet.http.HttpServletRequest;
javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class ClientBrowserInfoServlet
*/
public class ClientBrowserInfoServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
response.setContentType("text/html");
out.print("<html><head><title>Servlet gives Browser Information </title>
</head> <body>");
out.print("<h1>User-Agent:"+request.getHeader("User-Agent")+"<br><br>");
out.print("Accept-Language:"+request.getHeader("Accept-Language") +"<br>
<br><br>");
out.print("Can accept data of mime type:" +request.getHeader("Accept")
+"<br> </h1>");
out.print("</body></html>");
}
}
Open web.xml, observe the <servlet> and <servlet-mapping> tags added. In <welcome-file-list>
tag, make change as per below:
<welcome-file-list>
<welcome-file>home.html</welcome-file>
</welcome-file-list>
This tag specifies the default page to be displayed when this web application is accessed.
Step 6: Create a Home.html page which has been configured to run on start of this web application
in the previous step.
ER/CORP/CRS/ED113A/007
10
Home.html is a simple page with a hyper link with the url pattern info in the href (as
shown in the screenshot).
Step 7: To deploy/publish this web application, right click on the project and select Run As Run
on Server.
Complete the wizard and click on Finish. You can see the following output.
ER/CORP/CRS/ED113A/007
11
Observe the url in the browser address bar and the contents of the response page.
Summary of this assignment:
You have just learnt:
To create, and deploy a simple dynamic web project having html and servlet in Eclipse IDE.
ER/CORP/CRS/ED113A/007
12
Assignment 2: Develop Generic and HTTP servlets and learn the Servlet
Lifecycle
Objective: To understand the Generic and HTTP servlet lifecycle.
Problem Description: Develop Generic and HTTP servlets and understand the lifecycle of the
servlets.
Estimated time: 20 Min.
Artifacts to be developed:
1. ServletHome.html
2. GenServletDemo.html
3. HttpServletDemo.html
4. GenServletDemo.java GenericServlet (javax.servlet.GenericServlet)
5. HttpServletDemo.java HTTPServlet (javax.servlet.http.HttpServlet)
6. web.xml the deployment descriptor
ER/CORP/CRS/ED113A/007
13
ER/CORP/CRS/ED113A/007
14
1. ServletHome.html
ServletHome.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Servlet Home</title>
</head>
<body>
<center>
<a href='GenServletDemo.html'> Generic Servlet Demo</a><br>
<a href='HttpServletDemo.html'> HTTP Servlet Demo</a>
</center>
</body>
</html>
ER/CORP/CRS/ED113A/007
15
2. GenServletDemo.html
GenServletDemo.html
ER/CORP/CRS/ED113A/007
16
3. HttpServletDemo.html
HttpServletDemo.html
<!DOCTYPE
html
PUBLIC
"-//W3C//DTD
HTML
4.01
Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>HTTP Servlet Demo</title>
</head>
<body>
<h1 align="center" style="color: gray;"> HTTP Servlet Demo</h1>
<center>
<form action="HttpServletDemo" method="get" >
<h1>GET method form</h1>
Name: <input type="text" name="name"> <br>
<input type="submit" value="GET Request">
<div style="color: red; font-size: 12px;">
Take a look @ the url after submit
</div>
</form>
<hr>
<form action="HttpServletDemo" method="post">
<h1>POST method form</h1>
Name: <input type="text" name="name"> <br>
<input type="submit" value="POST Request">
</form>
</center>
</body>
</html>
ER/CORP/CRS/ED113A/007
17
Step
3:
Create
GenericServlet:
javax.servlet.GenericServlet
ER/CORP/CRS/ED113A/007
GenServletDemo.java
that
implements
18
java.io.IOException;
java.io.PrintWriter;
javax.servlet.GenericServlet;
javax.servlet.Servlet;
javax.servlet.ServletConfig;
javax.servlet.ServletException;
javax.servlet.ServletRequest;
javax.servlet.ServletResponse;
// continued
ER/CORP/CRS/ED113A/007
19
// continued
public class GenServletDemo extends GenericServlet implements Servlet {
private static final long serialVersionUID = 1L;
public GenServletDemo() {
super();
System.out.println("-----------------------------------------------");
System.out.println("GenServletDemo:Constructor, Object created");
System.out.println("Memory is allocated to the GenServlet in the
heap");
System.out.println("-----------------------------------------------");
}
public void init(ServletConfig config) throws ServletException {
System.out.println("-----------------------------------------------");
System.out.println("GenServletDemo: init");
System.out.println("-----------------------------------------------");
}
public void destroy() {
System.out.println("-----------------------------------------------");
System.out.println("GenServletDemo: destroy");
System.out.println("GenServlet has no more presence in the heap");
System.out.println("-----------------------------------------------");
}
public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException {
//HTTP request will run this method irrespective of the POST or
GET method
System.out.println("-----------------------------------------------");
System.out.println("GenServletDemo: service");
System.out.println("Servicing the request");
System.out.println("-----------------------------------------------");
PrintWriter out = response.getWriter();
out.println("<center>");
out.println("Hello, "+ request.getParameter("name")+" welcome to
GenServletDemo, service!!");
out.println("<br><a href='GenServletDemo.html'>Go back!!</a>");
out.println("</center>");
}
}
ER/CORP/CRS/ED113A/007
20
Step
4:
Create
HTTPServlet:
javax.servlet.GenericServlet
HttpServletDemo.java
that
implements
ER/CORP/CRS/ED113A/007
21
HttpServletDemo.java
package com.infy.enr.servlets;
import java.io.IOException;
import java.io.PrintWriter;
import
import
import
import
import
javax.servlet.ServletConfig;
javax.servlet.ServletException;
javax.servlet.http.HttpServlet;
javax.servlet.http.HttpServletRequest;
javax.servlet.http.HttpServletResponse;
// continued
ER/CORP/CRS/ED113A/007
22
// continued
protected void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
System.out.println("-----------------------------------------------");
System.out.println("HTTP request type: GET");
System.out.println("-----------------------------------------------");
PrintWriter out = response.getWriter();
out.println("<center>");
out.println("<h1>HttpServlet: GET service method</h1>");
out.println("Take a look into the server console to user stand the
servlet life cycle");
out.println("<br><a href='HttpServletDemo.html'>Go back!!</a>");
out.println("</center>");
}
protected void doPost(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
System.out.println("-----------------------------------------------");
System.out.println("HTTP request type: POST");
System.out.println("-----------------------------------------------");
PrintWriter out = response.getWriter();
out.println("<center>");
out.println("<h1>HttpServlet: POST service method</h1>");
out.println("Take a look into the server console to user stand the
servlet life cycle");
out.println("<br><a href='HttpServletDemo.html'>Go back!!</a>");
out.println("</center>");
}
ER/CORP/CRS/ED113A/007
23
Step 4: web.xml should have the following servlet description as shown in the picture below
ER/CORP/CRS/ED113A/007
24
ER/CORP/CRS/ED113A/007
25
Assignment 4: Exporting the project into a WAR and creating the manual
deployment for Tomcat web container
Objective:
To have a visual understanding of the deployment folder structure
Theory:
Deployment is process of installing a web application on to web container / application server.
Here we are going to use a web container; Tomcat 6.0 for first two assignments.
Web application could be deployed in various ways:
1. Statically, web application is deployed before server startup
2. Dynamically, web application is deployed after server startup
In this assignment, we are going to perform it statically.
Web application could be deployed in the Web ARchive (WAR) format or in exploded format.
Procedure: Consider the web project done in Assignment 1
Step 1: Export the project as WAR. Right-click on the project ServletDemoOne and select Export ->
WAR file.
On selecting Export -> WAR file you will get the following screen
ER/CORP/CRS/ED113A/007
26
Step 2: Choose the destination to place the created .war file by clicking on Browse and choosing
the desired path on your hard drive.
ER/CORP/CRS/ED113A/007
27
Note: Make sure you check the Export source files, if you want the all the
.java source files to be added to the archive which comes under
folder in eclipse.
Step 3: Once done open the command prompt, go to the destination folder where the .war file is
created and type the command jar xvf ServletDemoOne.war
Step 4: Now navigate to the folder where you have created the deployment on the drive you will
see the files created in the following folder structure.
ER/CORP/CRS/ED113A/007
28
We can deploy the application by copying the files into the root folder of the application
server (tomcat 6.0) as shown below
ER/CORP/CRS/ED113A/007
29
ER/CORP/CRS/ED113A/007
30
<html><head><title>Login Page</title></head>
<body bgcolor="#CCFFCC" >
<h2 align="center">Enter Login Details<br></h2>
<form action="Login" method="post">
<table border="4" align="center" bordercolor="brown"
bgcolor="pink">
<tr><td>UserName</td>
<td><input type="text" name="username"></td></tr>
<tr><td>Password</td>
<td><input type="password" name="pwd"></td></tr>
<tr><td><input type="submit" value="Login"/></td>
<td><input type="reset" value="Reset"/></td>
</tr>
</table>
</form>
</body></html>
ER/CORP/CRS/ED113A/007
31
LoginServlet.java
package edu.infy.servlets;
import
import
import
import
import
import
import
java.io.IOException;
java.io.PrintWriter;
java.util.ArrayList;
javax.servlet.ServletException;
javax.servlet.http.HttpServlet;
javax.servlet.http.HttpServletRequest;
javax.servlet.http.HttpServletResponse;
32
LoginServlet continued
private void validate(String name)
{
if(message.length()!=0)
{
message.delete(0, message.length());
}
if(names.contains(name))
{
String msg = "Hello "+name+" !!!. Login successful<br>";
if(name.equalsIgnoreCase("admin"))
{
message.append(msg + "<br> ");
message.append("<a href=\"addAccount.html\">Add
Account</a><br>");
message.append("<a href=\"displayAccount.html\">
Display Account</a><br>");
}
else if (name.equalsIgnoreCase("staff"))
{
message.append("<a href=\"displayAccount.html\">
Display Account</a><br>");
}
else if (name.equalsIgnoreCase("customer"))
{
message.append("<a href=\"displayAccount.html\">
Display Account</a><br>");
message.append("<a href=\"modifyAccount.html\">
Modify Account</a> <br>");
}
}
else {
message.append("Hello guest! Login is invalid...");
}
}
}
Step 3: Create web.xml as shown
33
web.xml continued
<servlet>
<description>Simple Login</description>
<display-name>Login</display-name>
<servlet-name>Login</servlet-name>
<servlet-class>edu.infy.servlets.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Login</servlet-name>
<url-pattern>/Login</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>loginForm.html</welcome-file>
</welcome-file-list>
</web-app>
Step 4: Create the folder structure as shown below
ER/CORP/CRS/ED113A/007
34
You need to create it in your local machine, where you are able to create folders.
Consider the Tomcat installation directory is in
D:\Program Files\Apache Software Foundation\Tomcat 6.0
It has a servlet-api.jar file in its lib folder, which needs to be in classpath, as it contains all
the classes and interfaces required for servlet development.
Compile the packaged servlet, as below:
On below command prompt execute the command:
D:\ServletDemoManual\WEB-INF\src\edu\infy\servlets>
javac classpath .;D:\Program Files\Apache Software Foundation\Tomcat
6.0\lib\servlet-api.jar d D:\ServletDemoManual\WEB-INF\classes LoginServlet.java
Considering you already know, how to compile .java files into .class file, we are just reiterating the above command components.
javac : java compiler command
-classpath classpath: option to specify the classpath to use when you run javac command,
it overrides CLASSPATH environment variable
-d directory: option to set the destination directory for class files
So after this command, see your folder structure again. In the classes folder,
LoginServlet.class file would be created in the proper directory structure.
Step 6: Our web application is ready to deploy. We are going to deploy this web application in the
exploded format.
Locate webapps folder in the tomcat installation directory.
In our machine, it is D:\Program Files\Apache Software Foundation\Tomcat
6.0\webapps
Step 7: Copy the ServletDemoManual folder into webapps folder
Thats it!!! copying is done, now the application is ready for deployment
ER/CORP/CRS/ED113A/007
35
ER/CORP/CRS/ED113A/007
36
If you are getting any of the above screens, which means tomcat server is running in your
system.
Step 9: Let us execute our web application.
Web applications are accessed using web browsers. So, open browser and type below link:
http://localhost:8080/ServletDemoManual
ER/CORP/CRS/ED113A/007
37
Step 7: Test the application for all testcases, such as: username as Staff, Customer and other
than, the given 3. And see the result. We have not added more functionality to our web
application, hence if you try to click on any of the Add Account, Display Account or Modify
Account link, it will result in the Page Not Found error (Status code 404).
Why this error?
This is because all these resources are not present in our web application folder which is
deployed on to the server.
Observation: Once you deploy your application on Tomcat (i.e. copying of the web
application folder in webapps folder in tomcat installation directory), and you start the
server, open the tomcat installation directory and locate the below folder in it:
work\Catalina\localhost
What did you find there?
It has the copy of your web application folder, which is accessed / executed, when you
request for the web application using web browser.
Summary of this assignment:
You have just learnt:
To develop a simple web application using servlet and deploy it on the web container,
Tomcat 6; in the absence of sophisticated IDE.
The web application folder structure
ER/CORP/CRS/ED113A/007
38
<servlet>
<display-name>buy</display-name>
<servlet-name>bp</servlet-name>
<servlet-class>servlets.BuyProduct</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>bp</servlet-name>
<url-pattern>/buyonline</url-pattern>
</servlet-mapping>
How will we write a URL to access it?
Consider, the Application name is OnlineStore, and deployed on http://localhost:8080
If in the form, if we want to post the data in the body of the Http Request, how will
we ensure this functionality?
If we are posting the data through POST method, and if we do not implement
doPost() method in the HttpServlet, what will happen?
ER/CORP/CRS/ED113A/007
39