WT-Program Manual

Download as pdf or txt
Download as pdf or txt
You are on page 1of 61

Program Index

Sr. No. Experiment Sign

1 Write HTML/Java scripts to display your CV in navigator,


your Institute website, Department Website and Tutorial
website for specific subject
2 Write an HTML program to design an entry form of student
details and send it to store at database server like SQL,
Oracle or MS Access.
3 Write programs using Java script for Web Page to display
browsers information.
4 Write a Java applet to display the Application Program
screen i.e. calculator and other.
5 Writing program in XML for creation of DTD, which
specifies set of rules. Create a style sheet in CSS/ XSL &
display the document in internet explorer.
6 Program to illustrate JDBC connectivity. Program for
maintaining database by sending queries. Design and
implement a simple servlet book query with the help of
JDBC & SQL. Create MS Access Database, Create on
ODBC link, Compile & execute JAVA JDVC Socket.
7 Install TOMCAT web server and APACHE. Access the
above developed static web pages for books web site, using
these servers by putting the web pages developed.
8 Assume four users user1, user2, user3 and user4 having the
passwords pwd1, pwd2, pwd3 and pwd4 respectively. Write
a servlet for doing the following. Create a Cookie and add
these four user id’s and passwords to this Cookie. 2. Read the
user id and passwords entered in the Login form and
authenticate with the values available in the cookies.
9 Install a database (Mysql or Oracle). Create a table which
should contain at least the following fields: name, password,
email-id, phone number Write a java program/servlet/JSP to
connect to that database and extract data from the tables and
display them. Insert the details of the users who register with
the web site, whenever a new user clicks the submit button in
the registration page.
10 Write a JSP which insert the details of the 3 or 4 users who
register with the web site by using registration form.
Authenticate the user when he submits the login form using
the user name and password from the database
11 Design and implement a simple shopping cart example with
session tracking API.

1
Experiment No. 1 Write HTML/Java scripts to display your CV in
navigator, your Institute website, Department Website and Tutorial
website for specific subject.

Code:

<html>
<head>
<title>RESUME | NAME</title>
<style>
h2{
background-color: aquamarine;
}
</style>
</head>
<body>
<!-- BEGIN DIV FOR OVERALL BOX -->
<div id="resume">
<!-- THIS DIV CENTERS OUR HEADING -->
<h1 onmouseover="func1(this)" onmouseout="func2(this)">Rohan Khanna</h1>
<h3 onmouseover="func1(this)" onmouseout="func2(this)">Email :
[email protected]<br> Contact : +91-9876543210 </h3>
<!-- END CENTERING DIV -->
</div>
<h2 onmouseover="heading1(this)" onmouseout="heading2(this)">Career
Objective</h2>
<p onmouseover="func1(this)" onmouseout="func2(this)">To achieve a
responsible in an organization with my best abilities of hard dedication and
knowledge</p> </p>
<h2 onmouseover="heading1(this)" onmouseout="heading2(this)">Education
Details</h2>
<table border="2" onmouseover="func1(this)" onmouseout="func2(this)">
<tr>
<th>Course</th>
<th>School/University</th>
<th>year</th>
<th>Percentage</th>
</tr>
<tr>
<td>10th</td>
<td>CBSE</td>
<td>2015</td>
<td>75%</td>
</tr>
<tr>
<td>12th</td>
<td>CBSE</td>
<td>2017</td>
<td>80%</td>

2
</tr>
<tr>
<td>B.tech</td>
<td>AKTU</td>
<td>2021</td>
<td>80%</td>
</tr>
</table>
<h2 onmouseover="heading1(this)" onmouseout="heading2(this)">Skills</h2>
<ul onmouseover="func1(this)" onmouseout="func2(this)">
<li><b>Languges : </b> HTML,CSS,JavaScript,Java,Python</li>
<li><b>Plateforms : </b> Android Studios , Visual Studios</li>
</ul>
<h2 onmouseover="heading1(this)" onmouseout="heading2(this)">Personal
Details</h2>
<ul onmouseover="func1(this)" onmouseout="func2(this)">
<li>Name : Rohan Khanna</li>
<li>Father : Ritik Khanna</li>
<li>Mother : Riya Khanna</li>
<li>Adsress : NH-24 Sitapur Road BKT Lucknow</li>
</ul>
<!-- THIS DIV CENTERS OUR LINKS -->
<div id="bottom">
<p> <a href="https://AKTU.ac.in">AKTU</a> |
<a href="http://www.srgilucknow.in">SRGI</a> |
<a href="https://www.srimt.in" target="_blank">SRIMT</a> |
<a href="https:www.srglobalschool.org.in" target="_blank">SRGS</a>
</p> </div>
<!-- END CENTERING LINKS -->
</div>
<!-- END DIV FOR OVERALL BOX -->
</body>
<script type="text/javascript">
function func1(sty) {
sty.style.color="red"
}
function func2(nor) {
nor.style.color="black";
}
function heading1(head){
head.style.fontSize="3em"
}
function heading2(head){
head.style.fontSize=""
}
</script>
</html>

3
Output :-

4
Experiment No. 2 Write an HTML program to design an entry form
of student details and send it to store at database server like SQL,
Oracle or MS Access.

Theory: HTML Forms HTML Forms are required to collect different kinds of user
inputs, such as contact details like name, email address, phone numbers, or details like
credit card information, etc. Forms contain special elements called controls like
inputbox, checkboxes, radio-buttons, submit buttons, etc.

Users generally complete a form by modifying its controls e.g. entering text, selecting
items, etc. and submitting this form to a web server for processing.

The <form> tag is used to create an HTML form. Here's a simple example of a login
form: Input Element This is the most commonly used element within HTML forms. It
allows you to specify various types of user input fields, depending on the type
attribute and several new input types introduced in HTML5. The most used input
types are described below.

Text Fields: - Text fields are one line areas that allow the user to input text. Single-
line text input controls are created using an <input> element, whose type attribute has
a value of text.

Password Field: - Password fields are similar to text fields. The only difference is;
characters in a password field are masked i.e. shown as asterisks or dots. This is to
prevent others from reading the password on the screen. This is also a single-line text
input controls created using an <input> element whose type attribute has a value of
password.

Radio Buttons: - Radio buttons are used to let the user select exactly one option from
a pre-defined set of options. It is created using an <input> element whose type
attribute has a value of radio.

Checkboxes: - Checkboxes allows the user to select one or more option from a pre-
defined set of options. It is created using an <input> element whose type attribute has
a value of checkbox.
File Select box: - The file fields allow a user to browse for a local file and send it as
an attachment to the form data. It normally rendered as a text box with a button that
enables the user to browse for a file. However, the user can also type the path and
name of the file in the text box. This is also created using an <input> element, whose
type attributes value is set to file.

Textarea: - Textarea is a multiple-line text input control that allows a user to enter
more than one line of text. Multi-line text input controls are created using an <
Textarea > element. Select Boxes A select box is a drop down list of options that
allows user to select one or more option from a pull-down list of options. Select box is
created using the <select> element and <option> element. The option elements within
the <select> element define each list item.

5
Submit and Reset Buttons: - A submit button is used to send the form data to a web
server. When submit button is clicked the form data is sent to the file specified in the
form's action attribute to process the submitted data. A reset button resets all the
forms control to default values.

Code:-
<html>
<head>
<script type="text/javascript" src="validate.js" ></script>
<style type="text/css" >
.div1{
border:5px solid black;
}

</style>
</head>
<body>
<div class="div1">
<form action="register.jsp" name="StudentRegistration" method=”post”>
<center> <font size="6"><b> Student Registration Form </b> </font> </center>

<lable for="textnames">Name : </label> <input type="text" name="textnames"


id="textname" size="30"><br><br>

<lable for="fathername">Father Name :</label><input type="text"


name="fathername" id="fathername" size="30"><br><br>

<lable for="paddress">Postal Address :</label> <input type="text" name="paddress"


id="paddress" size="30"><br><br>

<lable for="personaladdress">Personal Address : </label> <input type="text"


name="personaladdress" id="personaladdress" size="30"> <br><br>

<lable for="sex">Sex :</label> <input type="radio" name="sex" value="male"


size="10">Male <input type="radio" name="sex" value="Female"
size="10">Female<br><br>

<lable for="">City : <select name="City">


<option value="-1" selected>--select--</option>
<option value="New Delhi">NEW DELHI</option>
<option value="Mumbai">MUMBAI</option>
<option value="Goa">GOA</option>
<option value="Patna">PATNA</option> </select> <br><br>

<lable for="">Course :</label> <select name="Course">


<option value="-1" selected>--select--</option>
<option value="B.Tech">B.TECH</option>
<option value="MCA">MCA</option>
<option value="MBA">MBA</option>
<option value="BCA">BCA</option> </select><br><br>

6
<lable for="">District :</label><select name="District">
<option value="-1" selected>--select--</option>
<option value="Nalanda">NALANDA</option>
<option value="UP">UP</option>
<option value="Goa">GOA</option><br><br>

<option value="Patna">PATNA</option> </select>


<lable for="">State :</label> <select Name="State">
<option value="-1" selected>select..</option>
<option value="New Delhi">NEW DELHI</option>
<option value="Mumbai">MUMBAI</option>
<option value="Goa">GOA</option>
<option value="Bihar">BIHAR</option> </select><br><br>

<lable for="">Pin Code :</label> <input type="text" name="pincode" id="pincode"


size="30"><br><br>

<lable for="">EmailId :</label> <input type="email" name="emailid" id="emailid"


size="30"><br><br>

<lable for="">DOB :</label> <input type="datetime-local" name="dob" id="dob"


size="30"> <br><br>

<lable for="">MobileNo :</label> <input type="text" name="mobileno"


id="mobileno" size="30"><br><br>

<input type="reset">

<input type="submit" value="Submit Form" />


</table>
</form><br><br>

<h1><a href="MainPage.html">Back</a></h1>
</div>
</body>
</html>

7
Output :-

8
Experiment No. 3 Write programs using Java script for Web Page to
display browsers information.

Navigator : The window.navigator object contains information about the visitor's


browser.The window.navigator object can be written without the window prefix.

Property Description
appCodeName Returns the code name of the browser
appName Returns the name of the browser
appVersion Returns the version information of the browser
cookieEnabled Determines whether cookies are enabled in the
browser
geolocation Returns a Geolocation object that can be used to
locate the user's
positionlanguage Returns the language of the browser
onLine Determines whether the browser is online

platform Returns for which platform the browser is compiled

product Returns the engine name of the browser

userAgent Returns the user-agent header sent by the browser to


the server

Code:
<!DOCTYPE html>
<html>
<head runat="server">
<title>Progam 3</title>
<style>
#AppName{background-color: aquamarine;}
#Version{background-color: lightgreen;}
#Codename{background-color: lightgray;}
#Cookie{background-color: lightpink;}
#Java{background-color: lightskyblue;}
#Mime{background-color: lightsalmon;}
#Platform{background-color: lightgoldenrodyellow;}
#Plugins{background-color: lightblue;}
#SystemLang{background-color: lightcoral;}
#UserLang{background-color: lightcyan;}
#UserAgent{background-color: lightslategray;}
</style>
</head>
<body>
<button type="button" onclick="Click()">Click Here</button>
<div id="AppName"></div>
<div id="Version"></div>

9
<div id="Codename"></div>
<div id="Cookie"></div>
<div id="Java"></div>
<div id="Mime"></div>
<div id="Platform"></div>
<div id="Plugins"></div>
<div id="SystemLang"></div>
<div id="UserLang"></div>
<div id="UserAgent"></div>

<script>
function Click(){
document.getElementById("AppName").innerHTML="App Name is :
<b>"+navigator.appName+"</b>";
document.getElementById("Version").innerHTML="Version :
<b>"+navigator.appVersion +"</b>";
document.getElementById("Codename").innerHTML="Codename : <b>"
+navigator.appCodeName +"</b>";
document.getElementById("Cookie").innerHTML="Cookie enable :
<b>"+navigator.cookieEnabled +"</b>";
document.getElementById("Java").innerHTML="Java Enable :
<b>"+navigator.javaEnabled +"</b>";
document.getElementById("Mime").innerHTML="Mime type :
<b>"+navigator.mimeTypes +"</b>";
document.getElementById("Platform").innerHTML="Platform :
<b>"+navigator.platform +"</b>";
document.getElementById("Plugins").innerHTML="Plugins :
<b>"+navigator.plugins +"</b>";
document.getElementById("SystemLang").innerHTML="System Language :
<b>"+navigator.systemLanguage +"</b>";
document.getElementById("UserLang").innerHTML="User language :
<b>"+navigator.userAgent +"</b>";
document.getElementById("UserAgent").innerHTML="User Agent :
<b>"+navigator.userAgent +"</b>";
}
</script>
</body>
</html>

10
Output :-

11
Experiment No. 4 Write a Java applet to display the Application
Program screen i.e. calculator and other.

Theory : Applet is a special type of program that is embedded in the web page to
generate the dynamic content. It runs inside the browser and works at client side.
There are many advantages of applet. They are as follows
a) It works at client side so less response time
b) Secured
c) It can be executed by browsers running under many platforms, including Linux,
Windows, Mac Os etc.

Code for Calculator:


import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/* <applet code="Calculator" width=500 height=500> </applet> */
public class Calculator extends Applet implements ActionListener {
TextField t1;
Button b1, b2, b3, b4, b5, b6, b7, b8, b9, b0;
Button add, sub, mul, div, eql, dot;
String msg = "", tmp;
int a, b;

public void init() {


setLayout(null);
t1 = new TextField(20);
b1 = new Button("1");
b2 = new Button("2");
b3 = new Button("3");
b4 = new Button("4");
b5 = new Button("5");
b6 = new Button("6");
b7 = new Button("7");
b8 = new Button("8");
b9 = new Button("9");
b0 = new Button("0");
add = new Button("+");
sub = new Button("-");
div = new Button("/");
mul = new Button("*");
dot = new Button(".");
eql = new Button("=");

add(t1);
add(b7);
add(b8);
add(b9);
add(div);

add(b4);

12
add(b5);
add(b6);
add(mul);

add(b1);
add(b2);
add(b3);
add(sub);

add(dot);
add(b0);
add(eql);
add(add);

t1.setBounds(30, 30, 200, 40);


b7.setBounds(30, 80, 44, 44);
b8.setBounds(82, 80, 44, 44);
b9.setBounds(134, 80, 44, 44);
b4.setBounds(30, 132, 44, 44);
b5.setBounds(82, 132, 44, 44);
b6.setBounds(134, 132, 44, 44);
b1.setBounds(30, 184, 44, 44);
b2.setBounds(82, 184, 44, 44);
b3.setBounds(134, 184, 44, 44);
dot.setBounds(30, 236, 44, 44);
b0.setBounds(82, 236, 44, 44);
eql.setBounds(134, 236, 44, 44);
add.setBounds(186, 236, 44, 44);
sub.setBounds(186, 184, 44, 44);
mul.setBounds(186, 132, 44, 44);
div.setBounds(186, 80, 44, 44);

b0.addActionListener(this);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
b5.addActionListener(this);
b6.addActionListener(this);
b7.addActionListener(this);
b8.addActionListener(this);
b9.addActionListener(this);
div.addActionListener(this);
mul.addActionListener(this);
add.addActionListener(this);
sub.addActionListener(this);
eql.addActionListener(this);
}
public void actionPerformed(ActionEvent ae) {
String str = ae.getActionCommand();

13
if (str.equals("+") || str.equals("-") || str.equals("*") || str.equals("/")) {
String str1 = t1.getText();
tmp = str;
a = Integer.parseInt(str1);
msg = "";
} else if (str.equals("=")) {
String str2 = t1.getText();
b = Integer.parseInt(str2);
int sum = 0;
if (tmp == "+")
sum = a + b;
else if (tmp == "-")
sum = a - b;
else if (tmp == "*")
sum = a * b;
else if (tmp == "/")
sum = a / b;
String str1 = String.valueOf(sum);
t1.setText("" + str1);
msg = "";
} else {
msg += str;
t1.setText("" + msg);
}
}

public void paint(Graphics g)


{
}
}

14
Output :-

15
Experiment No. 5 : Writing program in XML for creation of DTD,
which specifies set of rules. Create a style sheet in CSS/ XSL &
display the document in internet explorer.

Code:

1.XML
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE note SYSTEM "Note.dtd">
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
DTD: <!DOCTYPE note [ <!ELEMENT note (to,from,heading,body)>
<!ELEMENT to (#PCDATA)>
<!ELEMENT from (#PCDATA)>
<!ELEMENT heading (#PCDATA)>
<!ELEMENT body (#PCDATA)> ]>

Output:-

2.XML

<?xml version="1.0"?>
<?xml-stylesheet type="text/css" href="Program6.css"?>
<!DOCTYPE globe>
<globe>
<Country>
<name>United States of America</name>
<areawidth>50,000</areawidth>
<capital>Washington,D.C</capital>

16
</Country>
<Country>
<name>Canada</name>
<areawidth>1,00000</areawidth>
<capital>Ottawa</capital>
</Country>
<Country>
<name>Norway</name>
<areawidth>60,000</areawidth>
<capital>Oslo</capital>
</Country>
<Country>
<name>Singapore</name>
<areawidth>65,000</areawidth>
<capital>Singapore</capital>
</Country>
<Country>
<name>England</name>
<areawidth>15,000</areawidth>
<capital>London</capital>
</Country>
</globe>

3 CSS

globe:before {
display: semi-block;
font-weight: bold;
font-size: 2em;
content: "Country";
background-color: #fff;
}
globe {
display: block;
margin: 2em 1em;
border: 4px solid #B22222;
padding: 0px 1em;
background-color: gray;
}
Country {
display: block;
margin-bottom: 1.5em;
}

17
name {
display: block;
font-weight: bold;
font-size: 140%;
}
areawidth {
display: block;
}
areawidth:before {
content: "Area width: ";
}
areawidth:after {
content: " million km\B2";
}

Output:-

18
Experiment No. 6 Program to illustrate JDBC connectivity. Program
for maintaining database by sending queries. Design and implement
a simple servlet book query with the help of JDBC & SQL.

CODE:

//STEP 1. Import required packages import java.sql.*;


public class FirstExample {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/EMP";
// Database credentials
static final String USER = "username";
static final String PASS = "password";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{

//STEP 2: Register JDBC driver


Class.forName("com.mysql.jdbc.Driver");

//STEP 3: Open a connection


System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);

//STEP 4: Execute a query


System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql;
sql = "SELECT id, first, last, age FROM Employees";
ResultSet rs = stmt.executeQuery(sql);

//STEP 5: Extract data from result set


while(rs.next()){
//Retrieve by column name
int id = rs.getInt("id");
int age = rs.getInt("age");
String first = rs.getString("first");
String last = rs.getString("last");
//Display values
System.out.print("ID: " + id);
System.out.print(", Age: " + age);
System.out.print(", First: " + first);
System.out.println(", Last: " + last);
}

//STEP 6: Clean-up environment


rs.close();

19
stmt.close();
conn.close();
}
catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}
catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}
finally{
//finally block used to close resources
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
}
// nothing we can do
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
}//end main
}//end FirstExample
}
catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
}//end main
}//end FirstExample

Servlet And JDBC

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.ServletException;

20
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class JDBCServlet extends HttpServlet {

public void doGet(HttpServletRequest inRequest,


HttpServletResponse outResponse) throws ServletException,
IOException {

PrintWriter out = null;


Connection connection = null;
Statement statement;
ResultSet rs;

try {
Class.forName("com.mysql.jdbc.Driver");

connection = DriverManager
.getConnection("jdbc:mysql://localhost/products");
statement = connection.createStatement();

outResponse.setContentType("test/html");
out = outResponse.getWriter();

rs = statement.executeQuery("SELECT ID, title, price FROM product");

Servlet And JDBC

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class JDBCServlet extends HttpServlet
{
public void doGet(HttpServletRequest inRequest,
HttpServletResponse outResponse) throws ServletException,
IOException {
PrintWriter out = null;
Connection connection = null;
Statement statement;
ResultSet rs;
try {

21
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager .getConnection("jdbc:mysql://localhost/products");
statement = connection.createStatement();
outResponse.setContentType("test/html");
out = outResponse.getWriter();
rs = statement.executeQuery("SELECT ID, title, price FROM product");
out.println("<HTML><HEAD><TITLE>Products</TITLE></HEAD>");
out.println("<BODY>");
out.println("<UL>");

while (rs.next()) {
out.println("<LI>" + rs.getString("ID") + " "
+ rs.getString("title") + " " + rs.getString("price"));
}

out.println("</UL>");
out.println("</BODY></HTML>");
} catch (ClassNotFoundException e) {
out.println("Driver Error");
} catch (SQLException e) {
out.println("SQLException: " + e.getMessage());
}
}

public void doPost(HttpServletRequest inRequest,


HttpServletResponse outResponse) throws ServletException,
IOException {
doGet(inRequest, outResponse);
}
}
out.println("<HTML><HEAD><TITLE>Products</TITLE></HEAD>");
out.println("<BODY>");
out.println("<UL>");
while (rs.next()) {
out.println("<LI>" + rs.getString("ID") + " " + rs.getString("title") + " " +
rs.getString("price"));
}
out.println("</UL>");
out.println("</BODY></HTML>");
}
catch (ClassNotFoundException e) {
out.println("Driver Error");
}
catch (SQLException e)
{
out.println("SQLException: " + e.getMessage());
}
}
public void doPost(HttpServletRequest inRequest,
HttpServletResponse outResponse) throws ServletException,

22
IOException {
doGet(inRequest, outResponse);
}
}
doGet(inRequest, outResponse);
}
}
doGet(inRequest, outResponse);
}
}

23
Experiment No. 7 Install TOMCAT web server and APACHE.
Access the above developed static web pages for books web site, using
these servers by putting the web pages developed.

Install the TOMCAT web server:

Step 1:

Installation of JDK:

Before beginning the process of installing Tomcat on your system, ensure first the
availability of JDK on your system program directory. Install it on your system if not
already installed (because any version of tomcat requires the Java 1.6 or higher
versions) and then set the class path (environment variable) of JDK. To set the
JAVA_HOME Variable: you need to specify the location of the java run time
environment to support the Tomcat else Tomcat server can not run.

This variable contains the path of JDK installation directory.


set JAVA_HOME=C:\Program Files\Java\jdk1.6

Note: it should not contain the path up to bin folder. Here, we have taken the URL
path according to our installation convention.

For Windows OS, go through the following steps:

First, right click on the

My Computer->properties->advance->Environment Variables->New->set
the Variable name = JAVA_HOME and
variable value = C:\Program Files\Java\jdk1.6

Now click on all the subsequent ok buttons one by one. It will set the JDK path.

Step 2:

For setting the class path variable for JDK, do like this:
First, right click on the

My Computer->properties->advance->Environment Variables->path.

Now, set bin directory path of JDK in the path variable

Step 3:

The process of installing Tomcat 6.0 begins here from now. It takes various steps for
installing and configuring the Tomcat 6.0.

24
For Windows OS, Tomcat comes in two forms: .zip file and .exe file (the Windows
installer file). Here we are exploring the installation process by using the .exe file.
First unpack the zipped file and simply execute the '.exe' file.

A Welcome screen shot appears that shows the beginning of installation process. Just
click on the 'Next' button to proceed the installation process.

Steps 4:

A screen of 'License Agreement' displays.

25
Click on the 'I Agree' button.

Step 5:

A screen shot appears asking for the 'installing location'

Choose the default components and click on the 'Next' button.

Step 6:

A screen shot of 'Configuration Options' displays on the screen. Choose the location
for the Tomcat files as per your convenience. You can also opt the default Location

The port number will be your choice on which you want to run the tomcat server. The
port number 8080 is the default port value for tomcat server to proceed the HTTP

26
requests. The user can also change the 'port number' after completing the process of
installation; for this, users have to follow the following tips.
Go to the specified location as " Tomcat 6.0 \conf \server.xml ". Within the
server.xml file choose "Connector" tag and change the port number.

Now, click on the 'Next' button to further proceed the installation process.

Step 7:

A Window of Java Virtual Machine displays on the screen.

This window asks for the location of the installed Java Virtual Machine. Browse the
location of the JRE folder and click on the Install button. This will install the Apache
tomcat at the specified
location.

Step 8:

A processing window of installing displays on the screen.

To get the information about installer click on the "Show details" button

27
Step 9:

A screen shot of 'Tomcat Completion' displays on the screen.

Click on the 'Finish' button.

Step 10:

A window of Apache Service Manager appears with displaying the running process.

Let the running process goes on.

Step 11:

After completing the installation process, the Apache Tomcat Manager appears on the
toolbar panel like shown in the below picture.

28
Start the Tomcat Server:

1. Start the tomcat server from the bin folder of Tomcat 6.0 directory by double
clicking the "tomcat6.exe" file.

OR create a shortcut of this .exe file at your desktop.

2. Now Open web browser and type URL http://localhost:8080 in the address bar to
test the server

3. To Stop the Tomcat Server: Stop the server by pressing the "Ctrl + c" keys.

PROCEDURE:

1. First install the tomcat into the system.


2. Then make a sub directory(eg., books) in the \tomcat\webapps.
3. Under books create WEB-INF directory and also place week1 programs in this
books directory only.
4. After this start tomcat by giving the following command at the
instll_dir>tomcat>bin
5. Catalina.bat run
6. At the I.E(web browser) give the url as http://localhost:8080/ books /main.html
7. Port no 8080 is assigned for the tomcat.

29
Experiment No. 8 Assume four users user1, user2, user3 and user4
having the passwords pwd1,pwd2, pwd3 and pwd4 respectively.
Write a servlet for doing the following. Create a Cookie and add
these four user id’s and passwords to this Cookie. Read the user id
and passwords entered in the Login form (week1) and authenticate
with the values (user id and passwords) available in the cookies.

User Authentication :
Assume four users user1, user2, user3 and user4 having the passwords pwd1, pwd2,
pwd3 And, pwd4 respectively. Write a servelet for doing the following.
1. Create a Cookie and add these four user id’s and passwords to this Cookie.
2. Read the user id and passwords entered in the Login form (week1) and authenticate
with the values (user id and passwords ) available in the cookies.

If he is a valid user(i.e., user-name and password match) you should welcome him by
name(username) else you should display “ You are not an authenticated user “.

PROCEDURE:

1. First install the tomcat into the system.


2. Then make a subdirectly(eg., tr) in the \tomcat\webapps.
3. Under tr create WEB-INF directory and also place the html files in this tr directory
only.
4. Next under WEB-INF create two subclasses lib,classes and web.xml
5. Next place all the class files under the classes and jar files (servlet
api.jar,classes12.jar etc…) under lib subdirectories.
6. After this start tomcat by giving the following command at the
instll_dir>tomcat>bin
7. Catalina.bat run
8. At the I.E(web browser) give the url as http;//localhost:8080//tr/htmlfile or servlet
url pattern
9. Portno 8080 is assigned for the tomcat.

Login.html:
<html>
<body bgcolor="pink">
<form action="show" method="get">
<center>User Name: <input type="test" name="name"><br> Password:<input
type="password"
name="pass"><br> <input type="submit" name="b1">
<input type="Button" name="b2" value="Reset">
</center>
</form>
</body> </html>

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

30
/** Example using servlet initialization. Here, the message
* to print and the number of times the message should be
* repeated is taken from the init parameters.
*/
public class login extends HttpServlet
{
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
String na=request.getParameter("name");
String pa=request.getParameter("pass");
PrintWriter out = response.getWriter();
Cookie nam1=new Cookie("user1","pace");
Cookie nam2=new Cookie("user2","phani");
Cookie nam3=new Cookie("user3","cse");
Cookie nam4=new Cookie("user4","ece");
Cookie pas1=new Cookie("pwd1","college");
Cookie pas2=new Cookie("pwd2","kumar");
Cookie pas3=new Cookie("pwd3","it");
Cookie pas4=new Cookie("pwd4","eee");
int flag=0;
String nam[]={nam1.getValue(),nam2.getValue(),nam3.getValue(),nam4.getValue()};
String pas[]={pas1.getValue(),pas2.getValue(),pas3.getValue(),pas4.getValue()};
for(int i=0;i<4;i++)
{
if(nam[i].equals(na)&&pas[i].equals(pa))
{
flag=1;
}
}
if(flag==1)
{
out.println("<title>The ShowMessage Servlet</title>");
out.println("<BODY BGCOLOR=\"#FDF5E6\">\n" +"<H1 ALIGN=CENTER>
WELCOME
<br/>TO</br> " +na.toUpperCase() + "</H1>"); out.println("</BODY></HTML>");
}
else
{
out.println("<title>The ShowMessage Servlet</title>"); out.println("<BODY
BGCOLOR=\"#FDF5E6\">\n" + "<H1 ALIGN=CENTER> User is invalid
</H1>");
out.println("</BODY></HTML>");
}
}
}

Web.xml:
<web-app>

31
<servlet>
<servlet-name>log </servlet-name>
<servlet-class>login </servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>log </servlet-name>
<url-pattern> /show </url-pattern>
</servlet-mapping>
</web-app>
Create a directory:
Create a directory “cookies”, in that directory copy login.html file and create a
directory a ”WEB
INF”. In that WEB-INF directory again create directory “classes” and copy web.xml
file.
Compile the servlet:
Compile the servlet file then copy the class file of that servlet into the directory
C:\Program Files\Apache Software Foundation\Tomcat 6.0\cookies\WEB-
INF\classes.
Open the server:
1. Start tomcat by giving the following command at the instll_dir>tomcat>bin
Catalina.bat run
2. At the I.E(web browser) give the url as http://localhost:8080/ cookies /login.html

32
Output :-

Login.html:-

Login.Java:-

33
Experiment No. 9 Install a database (Mysql or Oracle). Create a
table which should contain at least the following fields: name,
password, email-id, phone number Write a java program/servlet/JSP
to connect to that database and extract data from the tables and
display them. Insert the details of the users who register with the web
site, whenever a new user clicks the submit button in the registration
page.

Main.html:

<html>
<body>
<br /><br /><br /><br /><br />
<h1 align="center"><U>ONLINE BOOK STORAGE</U></h1><br/><br /><br />
<h2 align="center"><pre>
<b>Welcome to online book storage.
Press LOGIN if you are having id
otherwise press REGISTRATION
</b></pre></h2>
<br /><br /><pre>
<div align="center"><a href="login.html">LOGIN</a>
<a href="reg.html"> REGISTRATION</a></div></pre>
</body>
</html>

login.html:

<html>
<body><br /><br /><br />
<form name="myform" method="post" action="login"> <div align="center"><pre>
LOGIN ID :<input type="text" name="id" /><br />
PASSWORD :<input type="password" name="pwd" /></pre><br /><br /> </div>
<br /><br />
<div align="center">
<input type="submit" value="ok"/>
<input type="reset" value="clear" />
</div>
</form>
</body>
</html>

Profile.html

<html>
<body><br /><br /><br />
<form name="myform" method="post" action="profile"> <div align="center"><pre>
LOGIN ID :<input type="text" name="id" /><br />
</pre><br /><br />
</div> <br /><br />

34
<div align="center">
<input type="submit" value="ok" onclick="validate()" />
<input type="reset" value="clear" /> </div>
</form>
</body>
</html>

Userinfo.html

<html>
<head>
<title>User Info Entry Form</title>
</head>
<body bgcolor="white">
<form action="userinfo1.jsp" method="post">
<table>
<tr>
<td>Name:</td>
<td><input type="text" name="userName" >
</td>
</tr>
<tr>
<td>Sex:</td>
<td><input type="text" name="sex" >
</td>
<td>(Male or female)</td>
</tr>
<tr>
<td colspan=2><input type="submit"></td>
</tr>
</table>
</form>
</body>
</html>

Reg.html

<html>
<body><br /><br />
<form name="myform" method="post" action="reg"> <table align="center" >
<tr>
<td>NAME</td>
<td>:<input type="text" name="name" /></td>
</tr>
<tr>
<td>ADDRESS</td>
<td>:<input type="text" name="addr" /></td>
</tr>
<tr>
<td>CONTACT NUMBER</td>

35
<td>:<input type="text" name="phno" /></td>
</tr> <tr>
<td>LOGINID</td>
<td>:<input type="text" name="id" /></td>
</tr>
<tr>
<td>PASSWORD</td>
<td>:<input type="password" name="pwd" /></td> </tr>
</table>
<br /><br />
<div align="center">
<input type="submit" value="ok" onclick="validate()" />
<input type="reset" value="clear" /> </div>
</form>
</body>
</html>

login.java

import java.sql.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class login extends HttpServlet
{
public void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException,IOException
{
PrintWriter pw=resp.getWriter();
pw.println("<html><body>");
String id=req.getParameter("id");
String pwd=req.getParameter("pwd");
String s1="",s2="";
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1522:XE","system",
"tiger");
Statement stmt=con.createStatement();
String sqlstmt="select * from login";
ResultSet rs=stmt.executeQuery(sqlstmt);
int flag=0;
while(rs.next())
{
s1=rs.getString(4);
s2=rs.getString(5);
}
if(id.equals(s1)&&pwd.equals(s2))
{

36
flag=1;
}
if(flag==0)
{ pw.println("<br><br>SORRY INVALID ID TRY AGAIN ID<br><br>");
pw.println("<a
href=\"login.html\">press LOGIN to RETRY</a>");
}
else
{
pw.println("<br><br>WELCOME TO "+id.toUpperCase()+"<br><br>");
pw.println("<h3><ul>");
pw.println("<li><a href=\"profile.html\"><fontcolor=\"black\">
USER PROFILE</font></a></li><br><br>"); pw.println("<li><a
href=\"catalog.html\"><fontcolor=\"black\">BOOKS
CATALOG</font></a></li><br><br>");
pw.println("<li><a href=\"order.html\"> <fontcolor=\"black\">ORDER
CONFIRMATION</font></a></li></ul><br><br>"); }
pw.println("</body></html>");
}
catch(Exception e)
{
resp.sendError(500,e.toString());
}
}
}

reg.java:

import java.sql.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class reg extends HttpServlet
{
public void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException,IOException
{
PrintWriter pw=resp.getWriter();
resp.setContentType("text/html");
pw.println("<html><body>");
String name=req.getParameter("name");
String addr=req.getParameter("addr");
String phno=req.getParameter("phno");
String id1=req.getParameter("id");
String pwd1=req.getParameter("pwd");
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection

37
("jdbc:oracle:thin:@localhost:1522 :XE","system","tiger"); Statement
stmt=con.createStatement();
String sqlstmt="select * from login";
ResultSet rs=stmt.executeQuery(sqlstmt);
int flag=0;
while(rs.next())
{
if(id1.equals(rs.getString(4))&&pwd1.equals(rs.getString(5)))
{
flag=1;
}}
if(flag==1)
{
pw.println("<br><br>SORRY INVALID ID ALREADY EXITS TRY AGAIN WITH
NEW
ID<br><br>");
pw.println("<a href=\"reg.html\">press REGISTER to RETRY</a>");
}
else
{
Statement stmt1=con.createStatement();
stmt1.executeUpdate("insert into login values
('"+name+"','"+addr+"','"+phno+"','"+id1+"','"+pwd1+"')");
pw.println("<br><br>YOUR DETAILS ARE ENTERED<br><br>"); pw.println("<a
href=\"login.html\">press LOGIN to login</a>"); }
pw.println("</body></html>");
}
catch(Exception e)
{
resp.sendError(500,e.toString());
}
}
}

Catalog.java:

import java.sql.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class catalog extends HttpServlet
{
public void service(HttpServletRequest req,HttpServletResponse resp)
throws ServletException,IOException
{
PrintWriter pw=resp.getWriter();
pw.println("<html><body>");
String title=req.getParameter("title");
try
{

38
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1522:XE","system",
"tiger");
Statement stmt=con.createStatement();
String sqlstmt="select * from book where title=\'"+title+"\'"; ResultSet
rs=stmt.executeQuery(sqlstmt);
int flag=0;
while(rs.next())
{
pw.println("<div align=\"center\">");
pw.println("TITLE :"+rs.getString(1)+"<br>");
pw.println("AUTHOR :"+rs.getString(2)+"<br>");
pw.println("VERSION :"+rs.getString(3)+"<br>");
pw.println("PUBLISHER :"+rs.getString(4)+"<br>");
pw.println("COST :"+rs.getString(5)+"<br>"); pw.println("</div>");
flag=1;}
if(flag==0)
{
pw.println("<br><br>SORRY INVALID TITLE TRY AGAIN <br><br>");
pw.println("<a href=\"catalog.html\">press HERE to RETRY</a>");
}
pw.println("</body></html>");
}
catch(Exception e)
{
resp.sendError(500,e.toString());
}
}
}

profile.java:

import java.sql.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class profile extends HttpServlet
{
public void service(HttpServletRequest req,HttpServletResponse resp)
throws ServletException,IOException
{
PrintWriter pw=resp.getWriter();
pw.println("<html><body>");
String id=req.getParameter("id");
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection

39
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1522:XE","system",
"tiger"); Statement
stmt=con.createStatement();
String sqlstmt="select * from login where id='"+id+"'"; ResultSet
rs=stmt.executeQuery(sqlstmt);
int flag=0;
pw.println("<br><br><br>");
while(rs.next())
{
pw.println("<div align=\"center\">");
pw.println("NAME :"+rs.getString(1)+"<br>");
pw.println("ADDRESS :"+rs.getString(2)+"<br>");
pw.println("PHONE NO :"+rs.getString(3)+"<br>"); pw.println("</div>");
flag=1;
}
if(flag==0)
{
pw.println("<br><br>SORRY INVALID ID TRY AGAIN ID<br><br>");
pw.println("<a
href=\"profile.html\">press HERE to RETRY</a>"); }
pw.println("</body></html>");
}catch(Exception e)
{
resp.sendError(500,e.toString());
}
}
}

Order.java:

import java.sql.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class order extends HttpServlet
{
public void service(HttpServletRequest req,HttpServletResponse resp)
throws ServletException,IOException
{
int count;
PrintWriter pw=resp.getWriter();
pw.println("<html><body>");
String id=req.getParameter("id");
String pwd=req.getParameter("pwd");
String title=req.getParameter("title");
String count1=req.getParameter("no");
String date=req.getParameter("date");
String cno=req.getParameter("cno");
try
{

40
count=Integer.parseInt(count1);
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1522:XE","system",
"tiger");
Statement stmt=con.createStatement();
String sqlstmt="select * from login";
ResultSet rs=stmt.executeQuery(sqlstmt);
int flag=0,amount,x;
while(rs.next())
{
if(id.equals(rs.getString(4))&&pwd.equals(rs.getString(5)))
{
flag=1;
}
}
if(flag==0)
{
pw.println("<br><br>SORRY INVALID ID TRY AGAIN ID<br><br>");
pw.println("<a href= \"
order.html \" >press HERE to RETRY</a>");
}
else
{
Statement stmt2=con.createStatement();
String s="select cost from book where title='"+title+"'"; ResultSet
rs1=stmt2.executeQuery(s);
int flag1=0;
while(rs1.next()) {
flag1=1;
x=Integer.parseInt(rs1.getString(1));
amount=count*x;
pw.println("<br><br>AMOUNT:"+amount+"<br><br><br><br>"); Statement
stmt1=con.createStatement();
stmt1.executeUpdate("insert into details
values('"+id+"','"+title+"','"+amount+"','"+cno+"')");
pw.println("<br>YOUR ORDER has taken<br>");
}
if(flag1==0)
{
pw.println("<br><br><br>SORRY INVALID ID TRY AGAIN ID<br><br>");
pw.println("<a
href=\"order.html\">press HERE to RETRY</a>");
}
}
pw.println("</body></html>");
con.close();
}
catch(Exception e)
{

41
resp.sendError(500,e.toString());
}
}
}

Output :-

Main.java

Registration:-

42
Login page:-

Login Servlet Page:-

43
Profile Page:-

Profile Servlet Page

44
Catalog page:

Catalog Servlet page:

45
Order page:

Order Servlet page:

46
Experiment No. 10 Write a JSP which insert the details of the 3 or 4
users who register with the web site by using registration
form.Authenticate the user when he submits the login form using the
user name and password from the database

Main.html :
<html>
<body>
<br /><br /><br /><br /><br />
<h1 align="center"><U>ONLINE BOOK STORAGE</U></h1><br /><br /><br />
<h2 align="center"><pre>
<b>Welcome to online book storage.
Press LOGIN if you are having id
otherwise press REGISTRATION
</b></pre></h2>
<br /><br /><pre>
<div align="center"><a href="login.html">LOGIN</a> <a href="reg.html">
REGISTRATION</a></div></pre>
</body>
</html>

Login.html:
<html>
<body><br /><br /><br />
<form name="myform" method="post" action="login.jsp"> <div
align="center"><pre>
LOGIN ID :<input type="text" name="id" /><br />
PASSWORD :<input type="password" name="pwd" /></pre><br /><br /> </div>
<br /><br />
<div align="center">
<input type="submit" value="ok" onclick="validate()" />
<input type="reset" value="clear" />
</div>
</form>
</body>
</html>

Reg.html:
<html>
<body><br /><br />
<form name="myform" method="post" action="reg.jsp"> <table align="center" >
<tr>
<td>NAME</td>
<td>:<input type="text" name="name" /></td> </tr>
<tr>
<td>ADDRESS</td>
<td>:<input type="text" name="addr" /></td>
</tr> <tr>
<td>CONTACT NUMBER</td>

47
<td>:<input type="text" name="phno" /></td> </tr>
<tr>
<td>LOGINID</td>
<td>:<input type="text" name="id" /></td>
</tr>
<tr>
<td>PASSWORD</td>
<td>:<input type="password" name="pwd" /></td> </tr>
</table>
<br /><br />
<div align="center">
<input type="submit" value="ok" onclick="validate()" />
<input type="reset" value="clear" />
</div>
</form>
</body>
</html>

Reg.jsp:
<%@page import="java.sql.*"%>
<%@page import="java.io.*"%>
<% response.setContentType("text/html"); out.println("<html><body>");
String name=request.getParameter("name"); String
addr=request.getParameter("addr"); String
phno=request.getParameter("phno"); String id1=request.getParameter("id"); String
pwd1=request.getParameter("pwd"); int no=Integer.parseInt(phno);
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","system",
"tiger");
Statement stmt=con.createStatement();
String sqlstmt="select id,pwd from login";
ResultSet rs=stmt.executeQuery(sqlstmt);
int flag=0;
while(rs.next())
{ if(id1.equals(rs.getString(1))&&pwd1.equals(rs.getString(2)))
{flag=1;
}
}
if(flag==1)
{ out.println("<br><br>SORRY INVALID ID ALREADY EXITS TRY AGAIN
WITH NEW
ID<br><br>");
out.println("<a href=\"reg.html\">press REGISTER to RETRY</a>");
}
else
{
Statement stmt1=con.createStatement();
stmt1.executeUpdate("insert into login

48
values('"+name+"','"+addr+"',"+phno+",'"+id1+"','"+pwd1+"');");
out.println("<br><br>YOUR
DETAILS ARE ENTERED<br><br>"); out.println("<a href=\"login.html\">press
LOGIN to
login</a>"); }
out.println("</body></html>");
con.close();
%>

Login.jsp:
<%@page import="java.sql.*"%>
<%@page import="java.io.*"%>
<html>
<body>
<% String id=request.getParameter("id"); String pwd=request.getParameter("pwd");
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","system",
"tiger");
Statement stmt=con.createStatement();
String sqlstmt="select id,pwd from login";
ResultSet rs=stmt.executeQuery(sqlstmt);
int flag=0;
while(rs.next())
{
if(id.equals(rs.getString(1))&&pwd.equals(rs.getString(2)))
{
flag=1;
}
}
if(flag==0)
{
out.println("<br><br>SORRY INVALID ID TRY AGAIN ID<br><br>");
out.println("<a
href=\"login.html\">press LOGIN to RETRY</a>"); }
else
{out.println("<br><br>VALID LOGIN ID<br><br>"); out.println("WELCOME
<br>To<br>”+id);
}
con.close();
%>
</body>
</html>

49
Main.html:

Registration page:

50
Login page:

51
Experiment No. 11 Design and implement a simple shopping cart
example with session tracking API

Configure pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>LearnJSPServletWithRealApps</groupId>
<artifactId>LearnJSPServletWithRealApps</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>Learn JSP-Servlet with Real Apps</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp.jstl</groupId>
<artifactId>javax.servlet.jsp.jstl-api</artifactId>
<version>1.2.1</version>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<finalName>LearnJSPServletWithRealApps</finalName>
</build>
</project>

Configure web.xml
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >

52
<web-app>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>

Redirect Page
Create new JSP file named index.jsp in src\main\webapp folder. This file will
redirect to ProductServlet as below:

Add Image Files


Create new folder named assets in src\main\webapp folder. In assets folder, create
new folder named images and copy images need use in project to images folder.
Create Entities
Create new package named com.demo.entities. In this package, create new Java
classes as below:

Product Entity

Create new Java class named Product.java as below:


package com.demo.entities;

public class Product {

private String id;


private String name;
private double price;
private String photo;

public Product() {
}

public Product(String id, String name, String photo, double price) {


this.id = id;
this.name = name;
this.price = price;
this.photo = photo;
}

public String getId() {


return id;
}

public void setId(String id) {


this.id = id;
}

public String getName() {


return name;
}

53
public void setName(String name) {
this.name = name;
}

public double getPrice() {


return price;
}

public void setPrice(double price) {


this.price = price;
}

public String getPhoto() {


return photo;
}

public void setPhoto(String photo) {


this.photo = photo;
}

Item Entity

Create new Java class named Item.java as below:


package com.demo.entities;

public class Item {

private Product product;


private int quantity;

public Item() {
}

public Item(Product product, int quantity) {


this.product = product;
this.quantity = quantity;
}

public Product getProduct() {


return product;
}

public void setProduct(Product product) {


this.product = product;
}

54
public int getQuantity() {
return quantity;
}

public void setQuantity(int quantity) {


this.quantity = quantity;
}

Create Servlet
Create new package named com.demo.servlets. In this package, create new Servlets
as below:
Product Servlet
In com.demo.servlets package, create new Servlet named ProductServlet as below:
package com.demo.servlets;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.demo.models.ProductModel;

@WebServlet("/product")
public class ProductServlet extends HttpServlet {

private static final long serialVersionUID = 1L;

public ProductServlet() {
super();
}

protected void doGet(HttpServletRequest request, HttpServletResponse


response)
throws ServletException, IOException {
ProductModel productModel = new ProductModel();
request.setAttribute("products", productModel.findAll());
request.getRequestDispatcher("product/index.jsp").forward(request,
response);
}

protected void doPost(HttpServletRequest request, HttpServletResponse


response)
throws ServletException, IOException {
}

55
}

Cart Servlet
In com.demo.servlets package, create new Servlet named CartServlet as below:

package com.demo.servlets;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.demo.entities.Item;
import com.demo.models.ProductModel;

@WebServlet("/cart")
public class CartServlet extends HttpServlet {

private static final long serialVersionUID = 1L;

public CartServlet() {
super();
}

protected void doGet(HttpServletRequest request, HttpServletResponse


response)
throws ServletException, IOException {
String action = request.getParameter("action");
if (action == null) {
doGet_DisplayCart(request, response);
} else {
if (action.equalsIgnoreCase("buy")) {
doGet_Buy(request, response);
} else if (action.equalsIgnoreCase("remove")) {
doGet_Remove(request, response);
}
}
}

protected void doGet_DisplayCart(HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException {
request.getRequestDispatcher("cart/index.jsp").forward(request,
response);

56
}

protected void doGet_Remove(HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession();
List<Item> cart = (List<Item>) session.getAttribute("cart");
int index = isExisting(request.getParameter("id"), cart);
cart.remove(index);
session.setAttribute("cart", cart);
response.sendRedirect("cart");
}

protected void doGet_Buy(HttpServletRequest request, HttpServletResponse


response)
throws ServletException, IOException {
ProductModel productModel = new ProductModel();
HttpSession session = request.getSession();
if (session.getAttribute("cart") == null) {
List<Item> cart = new ArrayList<Item>();
cart.add(new
Item(productModel.find(request.getParameter("id")), 1));
session.setAttribute("cart", cart);
} else {
List<Item> cart = (List<Item>) session.getAttribute("cart");
int index = isExisting(request.getParameter("id"), cart);
if (index == -1) {
cart.add(new
Item(productModel.find(request.getParameter("id")), 1));
} else {
int quantity = cart.get(index).getQuantity() + 1;
cart.get(index).setQuantity(quantity);
}
session.setAttribute("cart", cart);
}
response.sendRedirect("cart");
}

private int isExisting(String id, List<Item> cart) {


for (int i = 0; i < cart.size(); i++) {
if (cart.get(i).getProduct().getId().equalsIgnoreCase(id)) {
return i;
}
}
return -1;
}

protected void doPost(HttpServletRequest request, HttpServletResponse


response)
throws ServletException, IOException {

57
}

Create Product Pages


Create new folder named product in src\main\webapp folder. In this folder, create new
JSP file named index.jsp as below:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


pageEncoding="ISO-8859-1" isELIgnored="false"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<title>Product Page</title>
</head>
<body>

<table cellpadding="2" cellspacing="2" border="1">


<tr>
<th>Id</th>
<th>Name</th>
<th>Photo</th>
<th>Price</th>
<th>Buy</th>
</tr>
<c:forEach var="product" items="${products }">
<tr>
<td>${product.id }</td>
<td>${product.name }</td>
<td>
<img
src="${pageContext.request.contextPath }/assets/images/${product.photo }"
width="120">
</td>
<td>${product.price }</td>
<td align="center">
<a
href="${pageContext.request.contextPath }/cart?&action=buy&id=${product.id }">B
uy</a>
</td>
</tr>
</c:forEach>
</table>

</body>
</html>

Create Cart Pages

58
Create new folder named cart in src\main\webapp folder. In this folder, create new
JSP file named index.jsp as below:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1" isELIgnored="false"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<title>Cart Page</title>
</head>
<body>

<table cellpadding="2" cellspacing="2" border="1">


<tr>
<th>Option</th>
<th>Id</th>
<th>Name</th>
<th>Photo</th>
<th>Price</th>
<th>Quantity</th>
<th>Sub Total</th>
</tr>
<c:set var="total" value="0"></c:set>
<c:forEach var="item" items="${sessionScope.cart }">
<c:set var="total" value="${total + item.product.price *
item.quantity }"></c:set>
<tr>
<td align="center">
<a
href="${pageContext.request.contextPath }/cart?action=remove&id=${item.product.i
d }"
onclick="return confirm('Are you
sure?')">Remove</a>
</td>
<td>${item.product.id }</td>
<td>${item.product.name }</td>
<td>
<img
src="${pageContext.request.contextPath }/assets/images/${item.product.photo }"
width="120">
</td>
<td>${item.product.price }</td>
<td>${item.quantity }</td>
<td>${item.product.price * item.quantity }</td>
</tr>
</c:forEach>
<tr>
<td colspan="6" align="right">Total</td>
<td>${total }</td>
</tr>
</table>

59
<br>
<a href="${pageContext.request.contextPath }/product">Continue
Shopping</a>

</body>
</html>

Run Application

Select project, right click and select Run As/Run on Server menu

Access DemoServlet with following urls as below:

http://localhost:8081/LearnJSPServletWithRealApps

http://localhost:8081/LearnJSPServletWithRealApps/product

Output :-

60
Click Buy link from product page to buy a product and show it in cart page

Click Delete link from cart page to remove product inside cart

61

You might also like