You are on page 1of 43

Lab Guide for Presentation tier using JSP and JSF

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.

Education and Research Department


Infosys Technologies Limited
Electronic City
Hosur Road
Bangalore - 561 229, India.
Tel: 91 80 852 0261-270
Fax: 91 80 852 0362
www.infy.com
mailto:E&R@infy.com

Infosys Technologies Limited

Document Revision History

Document Revision History


Version Date
1.0
Jun-2009
1.1

Jun 2010

Author(s)
Vaishali S Mudkhedkar
Raoke
Shashidhar H Basavaraju

ER/CORP/CRS/ED113A/007

Version No: 1.1

Reviewer(s)

Comments
Initial Draft

Yuvarani
Meiyappan

Infosys Technologies Limited

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

Version No. 1.1

ii

Infosys Technologies Limited

Lab Guide for Presentation tier using JSP and JSF

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

Version No. 1.1

Infosys Technologies Limited

Lab Guide for Presentation tier using JSP and JSF

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

Version No. 1.1

Infosys Technologies Limited

Lab Guide for Presentation tier using JSP and JSF

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

Version No. 1.1

Infosys Technologies Limited

Lab Guide for Presentation tier using JSP and JSF

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

Version No. 1.1

Infosys Technologies Limited

Lab Guide for Presentation tier using JSP and JSF

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

Version No. 1.1

Infosys Technologies Limited

Lab Guide for Presentation tier using JSP and JSF

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.

Now let us create a web application.


Step 4: In order to create web application, choose Dynamic Web Project as shown below:
File -> New -> Dynamic Web Project
It opens up a wizard, which helps to create a new dynamic web project. Provide a name to your
project. Screen shots are given on next page
Note: Project Name should not have spaces in it. It should not start with
digits. Here, we have given, ServletDemoOne, as project name

ER/CORP/CRS/ED113A/007

Version No. 1.1

Infosys Technologies Limited

Lab Guide for Presentation tier using JSP and JSF

Note: Observe the web application folder structure created.


Root folder is Application folder (ServletDemoOne), which has src,
WebContent sub-folders. All the packaged classes, having business logic need
to be under src folder. Resources which you want to publish - like html
pages, JSP pages, need to be stored under WebContent folder. Apart from
these, this folder contains WEB-INF sub-folder. Contents of WEB-INF are not
visible to user. It contains web.xml, the deployment descriptor and lib subfolder. All the library files required for your web application like,
classes12.jar, servlet-api.jar should be kept under the lib folder.

ER/CORP/CRS/ED113A/007

Version No. 1.1

Infosys Technologies Limited

Lab Guide for Presentation tier using JSP and JSF

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

Version No. 1.1

Infosys Technologies Limited

Lab Guide for Presentation tier using JSP and JSF

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

Version No. 1.1

Infosys Technologies Limited

Lab Guide for Presentation tier using JSP and JSF

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

Version No. 1.1

10

Infosys Technologies Limited

Lab Guide for Presentation tier using JSP and JSF

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

Version No. 1.1

11

Infosys Technologies Limited

Lab Guide for Presentation tier using JSP and JSF

Clicking on the link, you are trying to access the servlet

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

Version No. 1.1

12

Infosys Technologies Limited

Lab Guide for Presentation tier using JSP and JSF

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

Step 1: Create a new dynamic web project ServletDemo as in Assignment 1

ER/CORP/CRS/ED113A/007

Version No. 1.1

13

Infosys Technologies Limited

Lab Guide for Presentation tier using JSP and JSF

Do remember to include servlet-api.jar in the lib folder

Step 2: Create the html pages listed below

ER/CORP/CRS/ED113A/007

Version No. 1.1

14

Infosys Technologies Limited

Lab Guide for Presentation tier using JSP and JSF

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

Version No. 1.1

15

Infosys Technologies Limited

Lab Guide for Presentation tier using JSP and JSF

2. GenServletDemo.html
GenServletDemo.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>Generic Servlet Demo</title>
</head>
<body>
<h1 align="center" style="color: gray;"> Generic Servlet Demo</h1>
<center>
<form action="GenServlet" 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="GenServlet" 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

Version No. 1.1

16

Infosys Technologies Limited

Lab Guide for Presentation tier using JSP and JSF

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

Version No. 1.1

17

Infosys Technologies Limited

Lab Guide for Presentation tier using JSP and JSF

Step
3:
Create
GenericServlet:
javax.servlet.GenericServlet

ER/CORP/CRS/ED113A/007

GenServletDemo.java

Version No. 1.1

that

implements

18

Infosys Technologies Limited

Lab Guide for Presentation tier using JSP and JSF

Once the servlet is created, type in the code as below


GenServlet.java
package com.infy.enr.servlets;
import
import
import
import
import
import
import
import

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

Version No. 1.1

19

Infosys Technologies Limited

Lab Guide for Presentation tier using JSP and JSF

// 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

Version No. 1.1

20

Infosys Technologies Limited

Lab Guide for Presentation tier using JSP and JSF

Step
4:
Create
HTTPServlet:
javax.servlet.GenericServlet

HttpServletDemo.java

that

implements

Once the servlet is created, type in the code as below

ER/CORP/CRS/ED113A/007

Version No. 1.1

21

Infosys Technologies Limited

Lab Guide for Presentation tier using JSP and JSF

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;

public class HttpServletDemo extends HttpServlet {


private static final long serialVersionUID = 1L;
public HttpServletDemo() {
super();
System.out.println("-----------------------------------------------");
System.out.println("HttpServletDemo: Constructor");
System.out.println("Servlet created");
System.out.println("-----------------------------------------------");
}

public void init(ServletConfig config) throws ServletException {


System.out.println("-----------------------------------------------");
System.out.println("HttpServletDemo: init");
System.out.println("-----------------------------------------------");
}

public void destroy() {


System.out.println("-----------------------------------------------");
System.out.println("HttpServletDemo: destroy");
System.out.println("-----------------------------------------------");
}

// continued

ER/CORP/CRS/ED113A/007

Version No. 1.1

22

Infosys Technologies Limited

Lab Guide for Presentation tier using JSP and JSF

// 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

Version No. 1.1

23

Infosys Technologies Limited

Lab Guide for Presentation tier using JSP and JSF

Step 4: web.xml should have the following servlet description as shown in the picture below

Step 5: Run the project and analyze the output.

Assignment 3: Develop a servlet, deploy it on Tomcat web container, and


access it through HTML
Objective:
To develop, deploy and access a servlet in a web application
Problem Description: Infy Bank needs to authenticate the users based on their roles. The Infy Bank
login page should accept the details (username and password) from the user. The details should be
accepted in a HTML form and submitted to Login Servlet. The Login Servlet should validate the role
of the user and display the homepage links as per the role of the user given below:
o If username is admin, links are: Add Account, Display Account Details.
o If username is staff, links are: Display Account Details
o If username is customer, links are: Display Account Details, Modify account
o If any other value is sent for username than above usernames, display error message
Invalid username! Login failed
Note: The username and password could be hardcoded in a collection object
(in Login Servlet) for simplicity which will be usually checked against the
database records for Login credentials

ER/CORP/CRS/ED113A/007

Version No. 1.1

24

Infosys Technologies Limited

Lab Guide for Presentation tier using JSP and JSF

Estimated time: 20 Min.


Artifacts to be developed:
7. loginForm.html
8. LoginServlet.java
9. web.xml the deployment descriptor
Expected output:

On click of Login Button, LoginServlet will be invoked.

ER/CORP/CRS/ED113A/007

Version No. 1.1

25

Infosys Technologies Limited

Lab Guide for Presentation tier using JSP and JSF

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

Version No. 1.1

26

Infosys Technologies Limited

Lab Guide for Presentation tier using JSP and JSF

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

Version No. 1.1

27

Infosys Technologies Limited

Lab Guide for Presentation tier using JSP and JSF

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

Version No. 1.1

28

Infosys Technologies Limited

Lab Guide for Presentation tier using JSP and JSF

We can deploy the application by copying the files into the root folder of the application
server (tomcat 6.0) as shown below

Step 5: Start the server and access the corresponding URL.

ER/CORP/CRS/ED113A/007

Version No. 1.1

29

Infosys Technologies Limited

Lab Guide for Presentation tier using JSP and JSF

Assignment 5: Developing web application using servlets and deploying it


on Tomcat web container, in absence of IDE
Objective:
To develop a web application using servlets
To understand the folder structure of a Java EE web application and deploy it on a web
container (such as Tomcat 6 or 5.5)
Note : This assignment is for your study reference only. You may not be able to implement it as
access to web containers (Tomcat) folder hierarchy is not given to you directly.
Problem Description: Infy Bank needs to authenticate the users based on their roles. The Infy Bank
login page should accept the details (username and password) from the user. The details should be
accepted in a HTML form and submitted to Login Servlet. The Login Servlet should validate the role
of the user and display the homepage links as per the role of the user given below:
o If username is admin, links are: Add Account, Display Account Details.
o If username is staff, links are: Display Account Details
o If username is customer, links are: Display Account Details, Modify account
o If any other value is sent for username than above usernames, display error message
Invalid username! Login failed
Note: The username and password are hardcoded (in Login Servlet) for
simplicity which will be usually checked against the database records for
Login credentials

Estimated time: 40 Min.


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:
3. Statically, web application is deployed before server startup
4. 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.
Artifacts to be developed (Use Textpad/Notepad editor to develop the artifacts)
10. loginForm.html
11. LoginServlet.java
12. web.xml the deployment descriptor

ER/CORP/CRS/ED113A/007

Version No. 1.1

30

Infosys Technologies Limited

Lab Guide for Presentation tier using JSP and JSF

The typical web application folder structure is as shown below:

Step 1: Create loginForm.html as shown


loginForm.html

<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

Version No. 1.1

31

Infosys Technologies Limited

Lab Guide for Presentation tier using JSP and JSF

Step 2: Create LoginServlet.java as shown

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;

public class LoginServlet extends HttpServlet


{
StringBuffer message = new StringBuffer();
ArrayList<String> names;
public LoginServlet()
{
super();
names = new ArrayList<String>();
names.add("Admin");
names.add("Staff");
names.add("Customer");
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response)throws ServletException, IOException
{
String username = request.getParameter("username");
if((username == null) || (username.length()==0))
{
message.append("Username required field");
}
else
{
validate(username);
}
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<HTML><HEAD><TITLE>Login Page</TITLE></HEAD>"+
"<BODY BGCOLOR=\"#99CCFF\">"<H1> "+ message+" </H1>" +
"</BODY></HTML>");
}
ER/CORP/CRS/ED113A/007
Continued
on next page

Version No. 1.1

32

Infosys Technologies Limited

Lab Guide for Presentation tier using JSP and JSF

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

web.xml (elements of web.xml are discussed in Day 1 slides)


<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
ER/CORP/CRS/ED113A/007
Version No. 1.1
<display-name>ServletDemoManual</display-name>

33

Infosys Technologies Limited

Lab Guide for Presentation tier using JSP and JSF

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

Step 5: Compiling Servlet


We have created ServletDemoManual folder in D:\

ER/CORP/CRS/ED113A/007

Version No. 1.1

34

Infosys Technologies Limited

Lab Guide for Presentation tier using JSP and JSF

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

Version No. 1.1

35

Infosys Technologies Limited

Lab Guide for Presentation tier using JSP and JSF

Step 8: Now start the server.


Locate the bin folder in tomcat installation directory, and double click on tomcat6 icon
(Service Runner). One command prompt window will open up, and you can see, tomcat
server running. DO NOT CLOSE THIS WINDOW. [If you close this window, Server will stop
working.]

Let us test, whether Server is running or not!!!


Running Server
1) Hope same window is displayed on your machines screen.

2) Open Internet Explorer / Mozilla browser, and type:


http://localhost:8080
Our tomcat server is configured on 8090 port.
So we will type: http://localhost:8090

ER/CORP/CRS/ED113A/007

Version No. 1.1

36

Infosys Technologies Limited

Lab Guide for Presentation tier using JSP and JSF

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

On click of Login Button, LoginServlet will be invoked.

ER/CORP/CRS/ED113A/007

Version No. 1.1

37

Infosys Technologies Limited

Lab Guide for Presentation tier using JSP and JSF

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

Version No. 1.1

38

Infosys Technologies Limited

Lab Guide for Presentation tier using JSP and JSF

Self Review Questions


1. Consider we have created a Servlet named BuyProduct.java in servlets package of web
application folder, which performs online transaction when user wants to buy a product
through your web application. In which file of web application folder, will you describe
about your Servlet?
2. In order to describe the servlet, which tags need to be used in deployment descriptor file?
What is the name of deployment descriptor of web application? Can you give any other
name to the deployment descriptor? Or is web.xml a mandatory name?
3. If my servlet is described in web.xml with following tags:

<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

Consider, we have a html page buyProductForm.html, which displays all required


field details to be accepted from user for this transaction, on click of a button this
servlet needs to be invoked. How will we perform this functionality?

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

Version No. 1.1

39

You might also like