0% found this document useful (0 votes)
31 views

Lab Mnanual Web Tech (KCS-652)

Uploaded by

Tarun Srivastava
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views

Lab Mnanual Web Tech (KCS-652)

Uploaded by

Tarun Srivastava
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 38

AJAY KUMAR GARG ENGINEERING COLLEGE

GHAZIABAD

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

LAB MANUAL

NAME : RAGHIB ANEES ANSARI


COURSE : B.Tech. (CSE(AIML))
SEMESTER : VI
ROLL NUMBER : 2100271530060
SUBJECT : WEB TECHNOLOGY LAB
SUBJECT CODE : KCS 652
SUBMITTED TO : Mrs NIHARIKA TRIPATHI

1
. Experiment No. 1

Program Name:Write HTML/Java scripts to display your CV in navigator, your Institute website,
Department Website and Tutorial website for specific subject.

Theory Concepts: Use of HTML tags and CSS to develop resume.

Implementation:
<html>
<head>
<title></title>
<style>
<!--
li.MsoNormal
{mso-style-parent:"";
margin-bottom:.0001pt;
font-size:12.0pt;
font-family:"Times New Roman";
margin-left:0in; margin-right:0in; margin-top:0in}
-->
</style>
</head>

<body>

<div align="center">
<center>
<table border="0" cellpadding="0" cellspacing="0" style="border-collapse: collapse"
bordercolor="#111111" width="70%" id="AutoNumber1" height="822">
<tr>
<tdalign="center" height="26"><b><font size="5">RAGHIB SRIVASTAVA</font></b></td>
</tr>
<tr>
<tdalign="center" height="17">
<span style="font-size: 11.0pt; font-family: Times New Roman">Room
No:-045, Senior Boys Hostel,</span></td>
</tr>
<tr>
<tdalign="center" height="17">
<p class="MsoNormal" align="center" style="text-align:center">
2
<span style="font-size:11.0pt">Ajay</span><span style="font-size:
11.0pt"></span><span style="font-size:11.0pt">Kumar Garg Engineering College,</span></td>
</tr>
<tr>
<tdalign="center" height="17">
<p class="MsoNormal" align="center" style="text-align:center">
<span style="font-size:11.0pt">Ghaziabad (U.P.)-201009.</span></td>
</tr>
<tr>
<tdalign="center" height="17">
<p class="MsoNormal" align="center" style="text-align:center">
<span style="font-size:11.0pt">Contact No.:- +919891498261</span></td>
</tr>
<tr>
<tdalign="center" height="17">
<p class="MsoNormal" align="center" style="text-align:center">
<span style="font-size:11.0pt">E-mail:-<a href="[email protected]"><span style="color:blue; text-
decoration:none">[email protected]</span></a></span></td>
</tr>
<tr>
<tdalign="center" height="19">&nbsp;</td>
</tr>
<tr>
<tdalign="center" bgcolor="#808080" height="20"><b><font size="4">
Objectives</font></b></td>
</tr>
<tr>
<tdalign="center" height="38">
<p align="left">
<span style="font-size: 12.0pt; font-family: Times New Roman">To work in a
challenging and motivating environment where I can use my potential to the
very best and work towards refining my technical skills, knowledge and
personality.</span></td>
</tr>
<tr>
<tdalign="center" height="19">&nbsp;</td>
</tr>
<tr>
<tdalign="center" bgcolor="#808080" height="20"><font size="4"><b>
Qualification</b></font></td>
</tr>
<tr>
<tdalign="center" height="99">
<ul style="margin-top: 0in; margin-bottom: 0in" type="disc">
<li class="MsoNormal">
<p align="left">Pursuing Bachelor of Technology (<b>Computer Science and
Engineering</b>) from Ajay Kumar Garg Engineering College, Ghaziabad.
Uttar Pradesh Technical University, Luckhnow.&nbsp; Aggregate Percentage
till 6<sup>th</sup> semester 75.0.</li>
<li class="MsoNormal">
<p align="left">
<span style="font-size: 12.0pt; font-family: Times New Roman">intermediate
<b></b> with 74% from v.s.e.cawadhpuri (u.p.board)</span></li>
<li class="MsoNormal">

3
<p align="left">

<span style="font-size: 12.0pt; font-family: Times New Roman">High


School with 71% from V.s.e.c.,awadhpuri(U.P. Board) in 2002.</span></li>
</ul>
</td>
</tr>
</body>
</html>

Output / Conclusion:Type the program in notepad and save the program with .html extension. Run the
program in Internet Explorer to display resume.

4
Experiment No. 2

Program Name: 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 Concepts: Use basic HTML tags to develop all programs and JDBC connectivity.

Implementation:
1. Index.html

<html>
<head>
<title>Pet Details</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>

<body>
<form name="petDetails" method="post" action="SavePetDetails1">
Enter pet details
Name: <input type="text" name="name"/><BR>
Owner:<input type="text" name="owner"/><BR>
Species: <input type="text" name="species"/><BR>
Sex: <input type="text" name="sex"/><BR>
Birth: <input type="text" name="birth"/><BR>
Death: <input type="text" name="death"/><BR>
<input type="submit" name="submit"/>
</form>
</body>

</html>

2. SaveDetails.java

public class SaveDetails {


public void saveDetails(String name,Stringowner,Stringspecies,Stringsex,Stringbirth,String death)
{
try{

5
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
java.util.DatebdateStr = formatter.parse(birth);
java.sql.DatebdateDB = new java.sql.Date(bdateStr.getTime());

java.util.DateddateStr = formatter.parse(death);
java.sql.DateddateDB = new java.sql.Date(ddateStr.getTime());

Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/db1?autoReconnect=true&useSSL=false","root","root");
String insString="INSERT INTO db1.pet VALUES (?,?,?,?,?,?)";

PreparedStatementinsStmt=con.prepareStatement(insString);

insStmt.setString(1, name);
insStmt.setString(2, owner);
insStmt.setString(3, species);
insStmt.setString(4, sex);
insStmt.setDate(5, bdateDB);
insStmt.setDate(6, ddateDB);

insStmt.executeUpdate();

con.close();
System.out.println("statement executed");
}catch(Exception e){ System.out.println(e);}
}

3. SavePetDetails.java

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
*
* @author nghan
*/
@WebServlet(urlPatterns = {"/SavePetDetails1"})
public class SavePetDetails extends HttpServlet {

/**
*
* @param request
* @param response
* @throws ServletException

6
* @throws IOException
*/

protected void processRequest(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
String name= request.getParameter("name");
String owner= request.getParameter("owner");
String species= request.getParameter("species");
String sex= request.getParameter("sex");
String birth= request.getParameter("birth");
String death= request.getParameter("death");

System.out.println("Inside servlet"+name+owner+species+sex+birth+death);

SaveDetails s= new SaveDetails();


s.saveDetails(name,owner,species,sex,birth,death);
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet SavePetDetails</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Data saved to database");
out.println("</body>");
out.println("</html>");
}
}

// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit
the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}

/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs

7
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}

/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>

Output / Conclusion:

Step 1: After entering the data on the Pet form

Step 2: After clicking on Submit Query and the data saved successfully, following page is displayed.

8
Experiment No. 3

Program Name: Write programs using Java script for Web Page to display browsers information.

Theory Concepts:Java script helps to access browser information.

Implementation:

<head>
<head>
<title> Browser Information </title>
<script language=javascript>

function show()
{
document.write("Name "+navigator.appName+"<br>");
document.write("Version "+navigator.appVersion +"<br>");
document.write("Codename " +navigator.appCodeName +"<br>");
document.write("Cookie enable"+navigator.cookieEnabled +"<br>");
document.write("Java Enable"+navigator.javaEnabled +"<br>");
document.write("Mime type"+navigator.mimeTypes +"<br>");
document.write("Platform"+navigator.platform +"<br>");
document.write("Plug ins"+navigator.plugins +"<br>");
document.write("System Language"+navigator.systemLanguage +"<br>");
document.write("User language"+navigator.userAgent +"<br>");
document.write("User Agent"+navigator.userAgent +"<br>");
}
</script>
</head>
<body>
<form id="form1">
<div>
<input id="Button1" type="button" value="Click me" onclick="show()" />
9
</div>
</form>
</body>
</html>

Output / Conclusion: Save the above program as .html file and when user clicks on show following
page is displayed

1
0
Experiment No. 4

Program Name: Write a program in Java to allot rooms in the hostel using Inheritance. Incorporate method
overloading and method overriding concepts in the program.

Theory Concepts:Overloading: In same class, if name of the method remains common but the number
and type of parameters are different, then it is called method overloading in Java.Overriding: A method is
said to be overridden when one is in parent class and another is in child class with the same name, same
return type, and same parameter.
Inheritance :
Single level inheritance e.g. (class B extends Class A).
Multilevel inheritance e.g. (class C extends class B and class B extends Class A).
Multiple inheritance is not possible in JAVA.

Implementation:
1. Base abstract class Room

public abstract class Room {


private int room_no;
booleanalotted;

public int getRoom_no()


{
return room_no;
}
public void setRoom_no(int rm)
{
this.room_no=rm;
}
public booleangetAlotted()
{
return alotted;
}
public void setAlloted(boolean allot)
{
this.alotted=allot;

}
public booleanallotRoom(String[] allotee)
1
1
{
return true;
}
public booleanallotRoom(String allotee)
{
return true;
} }

2. Class SingleBedRoom
public class SingleBedRoom extends Room{
private String allotedTo;
public booleanallotRoom(String allotee)
{
setAllotedTo(allotee);
System.out.println("Room allotted successfully");

return true;
}
public void setAllotedTo(String allotee)
{
this.allotedTo=allotee;
}
}
3. Class DoubleBedRoom
public class DoubleBedRoom extends Room{
private String allotedTo;
public booleanallotRoom(String[] allotee)
{
System.out.println("Room allotted successfully");

for(int i=0;i<allotee.length;i++)
{
setAllotedTo(allotee[i]);
}
System.out.println("Room allotted successfully");

return true;
}

public void setAllotedTo(String allotee)


{
this.allotedTo=allotee;
}
}

1
2
4. Class RoomReserve
public class RoomReserve {
public static void main(String[] args)
{
Scanner userInput =new Scanner(System.in) ;
System.out.println("Which type of room do you want to reserve");
String roomType = userInput.nextLine();

if(roomType.equals("Single"))
{
Room singleBed= new SingleBedRoom();
System.out.println("Enter the name of person");
String userName=userInput.nextLine();
singleBed.allotRoom(userName);
}
else
{
Room doubleBed= new DoubleBedRoom();
System.out.println("Enter the name of persons");
String userName=userInput.nextLine();
doubleBed.allotRoom(userName);
}
userInput.close();

}
}

1
3
Output / Conclusion:

Step 1: When user enters room type as Single, single bedroom is reserved.

Step 2: When user enters room type as double, double bedroom is reserved.

1
4
Experiment No. 5

Program Name:Develop a program in Java to run three threads of the program simultaneously using
multithreading. Include try, catch block in the program.

Theory Concepts:Create a class which implements Runnable interface. Create three threads for the
implemented class’s object and observe their behavior.

Implementation:

public class T1 implements Runnable {


public void run() {
try {
for(int n = 5; n > 0; n--) {
Thread t = Thread.currentThread();
String name = t.getName();
System.out.println("name=" + name +n);Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println("Child thread interrupted");
}
}
public static void main(String args[]) {
try {
T1 a1 =new T1();
Thread t1 = new Thread(a1, "First Thread"); t1.start();
T1 a2 =new T1();
Thread t2 = new Thread(a2, "Second Thread"); t2.start();
T1 a3 =new T1();
Thread t3 = new Thread(a3, "Third Thread"); t3.start();
for(int n = 5; n > 0; n--) {
System.out.println("main thread"+n);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println("Main thread interrupted");
}
}
}

1
5
Output / Conclusion:The threads will execute the run method simultaneously.

name=First Thread5
name=Third Thread5
name=Second Thread5
main thread5
name=First Thread4
name=Second Thread4
main thread4
name=Third Thread4
name=First Thread3
main thread3
name=Second Thread3
name=Third Thread3
name=First Thread2
main thread2
name=Second Thread2
name=Third Thread2
name=First Thread1
name=Second Thread1
main thread1
name=Third Thread1

Experiment No. 6

Program Name: Write a Java applet to display the Application Program screen i.e. calculator and
other.

Theory Concepts:java.applet.Applet class is used to create a user defined applet.

Implementation:
import java.applet.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.TextEvent;
import java.awt.event.TextListener;;
public class calculator extends Applet implements ActionListener, TextListener

{
String s,s1,s2,s3,s4;
Button b1,b2,b3,b4,b5,b6,b7,b8,b9,b0;
Button add,sub,eq,cl,mul,div;
1
6
TextField t1;
int a,b,c;

public void init()


{
t1=new TextField(10);
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("-");
mul=new Button("*");
div=new Button("/");
eq=new Button("=");
cl=new Button("Clear");

GridLayoutgb=new GridLayout(4,5);
setLayout(gb);

add(t1);
add(b1);
add(b2);
add(b3);
add(b4);
add(b5);
add(b6);
add(b7);
add(b8);
add(b9);
add(b0);
add(add);
add(sub);
add(mul);
add(div);
add(eq);
add(cl);

b1.addActionListener(this);
b2.addActionListener(this);

1
7
b3.addActionListener(this);
b4.addActionListener(this);
b5.addActionListener(this);
b6.addActionListener(this);
b7.addActionListener(this);
b8.addActionListener(this);
b9.addActionListener(this);
b0.addActionListener(this);
add.addActionListener(this);
sub.addActionListener(this);
mul.addActionListener(this);
div.addActionListener(this);
eq.addActionListener(this);
cl.addActionListener(this);
paint();
//t1.addTextListener(this);
}
public void paint()
{
setBackground(Color.green);
}

public void actionPerformed(ActionEvent e)


{
s=e.getActionCommand();
if(s.equals("0")||s.equals("1")||s.equals("2")||
s.equals("3")||s.equals("4")||s.equals("5")||s.equals("6")||s.equals("7")||s.equals("8")||
s.equals("9")||s.equals("0"))
{
s1=t1.getText()+s;
t1.setText(s1);
}
if(s.equals("+"))
{
s2=t1.getText();
t1.setText("");
s3="+";
}
if(s.equals("-"))
{
s2=t1.getText();
t1.setText("");
s3="-";
}
if(s.equals("*"))
{
s2=t1.getText();

1
8
t1.setText("");
s3="*";
}
if(s.equals("*"))
{
s2=t1.getText();
t1.setText("");
s3="*";
}
if(s.equals("="))
{
s4=t1.getText();
a=Integer.parseInt(s2);
b=Integer.parseInt(s4);
if(s3.equals("+"))
c=a+b;
if(s3.equals("-"))
c=a-b;

t1.setText(String.valueOf(c));
}
if(s.equals("Clear"))
{
t1.setText("");
}
}
public void textValueChanged(TextEvent e)
{

}
}

Output / Conclusion:

1
9
Experiment No. 7

Program Name: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.

Theory Concepts: An XML file is created with DTD. A style sheet in CSS format is also created for that
XML file. XML With DTD and CSS files are combined together to check the output on browser’s screen.

Implementation:
1. XML With DTD

<?xml version="1.0"?>
<!DOCTYPE note [
<!ELEMENT note (to,from,heading,body)>
<!ELEMENT to (#PCDATA)>
<!ELEMENT from (#PCDATA)>
<!ELEMENT heading (#PCDATA)>
<!ELEMENT body (#PCDATA)>
]>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend</body>
</note>

2. CSS for XML

products {font-size:80%; margin:0.5em; font-family: Verdana; display:block}


product {display:block; border: 1px solid silver; margin:0.5em; padding:0.5em; background-
color:whitesmoke;}
name, price, stock, country {display:block}
name {color:red; text-decoration: underline}
price {color:green}
stock {color:brown}
2
0
country {color:blue}

/* IE supports the ID selector also for XML */


product#p4 {text-align:right}
/* Alternative in: Firefox, Opera, Google Chrome *
/product[id=p4] {text-align:right}

/* IE supports the class attribute for XML */


product.special {background-color:mistyrose}
/* Alternative in: Firefox, Opera, Google Chrome */
product[class=special] {background-color:mistyrose}

3. XML With CSS

<?xml version="1.0" encoding="UTF-8"?>


<?xml-stylesheet type="text/css" href="products.css"?>
<products>
<product id="p1" class="special">
<name>Delta</name>
<price>800</price>
<stock>4</stock>
<country>Denmark</country>
</product>
<product id="p2">
<name>Golf</name>
<price>1000</price>
<stock>5</stock>
<country>Germany</country>
</product>
<product id="p3">
<name>Alpfa</name>
<price>1200</price>
<stock>19</stock>
<country>Germany</country>
</product>
<product id="p4">
<name>Foxtrot</name>
<price>1500</price>
<stock>5</stock>
<country>Australia</country>
</product>
<product id="p5" class="special">
<name>Tango</name>
<price>1225</price>
<stock>3</stock>
<country>Japan</country>

2
1
</product>
</products>

Output / Conclusion:

(XML Without CSS)

(XML With CSS)

2
2
Experiment No. 8

Program Name: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.

Theory Concepts:Java DataBase Connectivity is used to connect Java to Database. Clsss.forName ()


method register the database driver to JDBC for connection. DriverManager.getConnection() method is used
to connect to particular database. Statement and ResultSet objects are used to execute query and to store
result of the query respectively.

Implementation:

package javaapplication;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Connect {

public static void main(String[] args) {

// variables
Connection connection = null;
Statement statement = null;
ResultSetresultSet = null;

// Step 1: Loading or registering Oracle JDBC driver class


try {

Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
}
catch(ClassNotFoundExceptioncnfex) {

System.out.println("Problem in loading or "


+ "registering MS Access JDBC driver");
cnfex.printStackTrace();
}

// Step 2: Opening database connection


try {

String msAccDB = "C:/users/admin/Documents/JavaDatabase.accdb";


String dbURL = "jdbc:ucanaccess://" + msAccDB;

// Step 2.A: Create and get connection using DriverManager class


connection = DriverManager.getConnection(dbURL);

2
3
// Step 2.B: Creating JDBC Statement
statement = connection.createStatement();

// Step 2.C: Executing SQL &amp; retrieve data into ResultSet


resultSet = statement.executeQuery("SELECT * FROM PLAYERS");

System.out.println("ID\tPlayerName\tAge\tRuns");
System.out.println("==\t===========\t===\t=======");

// processing returned data and printing into console


while(resultSet.next()) {
System.out.println(resultSet.getInt(2) + "\t" +
resultSet.getString(3) + "\t" +
resultSet.getString(4) + "\t" +
resultSet.getString(5));
}
}
catch(SQLExceptionsqlex){
sqlex.printStackTrace();
}
finally {

// Step 3: Closing database connection


try {
if(null != connection) {

// cleanup resources, once after processing


resultSet.close();
statement.close();

// and then finally close connection


connection.close();
}
}
catch (SQLExceptionsqlex) {
sqlex.printStackTrace();
}
}
}
}

Output / Conclusion:

2
4
Experiment No. 9

Program Name: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

Theory Concepts:Configuring & Using Apache Tomcat 4. A Tutorial on Installing and Using Tomcat
for Servlet and JSP Development.

Explanation:-

Install the JDK


Your first step is to download and install Java. The servlet 2.3 specification requires Java 2; I suggest JDK
1.3 or later. See the following sites for download and installation information. Once you've installed Java,
confirm that everything including your PATH is configured properly by opening a DOS window and typing
"java -version" and "javac -help". You should see a real result both times, not an error message about an
unknown command. Or, if you use an IDE, compile and run a simple program to confirm that the IDE
knows where you installed Java.
 JDK 1.3 (Windows, Linux, Solaris): http://java.sun.com/j2se/1.3/.
 JDK 1.4 (Windows, Linux, Solaris): http://java.sun.com/j2se/1.4/download.html. Be sure you
download the full Software Development Kit (SDK) from entries in the right hand column, not just
the JRE (Java Runtime Environment). The JRE is only for running already-compiled class files, and
lacks a compiler.
 Java 2 (Other platforms): http://java.sun.com/cgi-bin/java-ports.cgi.

2
5
Configure Tomcat

Configuring Tomcat involves seven steps:


1. Downloading the Jakarta Tomcat software.
2. Enabling the ROOT Context.
3. Changing the port from 8080 to 80.
4. Telling Tomcat to reload servlets when they are modified.
5. Setting the JAVA_HOME variable.
6. Changing the DOS memory settings.
7. Setting the CATALINA_HOME variable.

Details of each step are given below.

1. Download the Tomcat Software

Go to http://jakarta.apache.org/builds/jakarta-tomcat-4.0/release/, select the latest version number, and


choose "binary". Download the zip file to your PC and unzip it into a location of your choice. You specify
the top-level directory (e.g., C:\). The zip file has embedded subdirectories (e.g., jakarta-tomcat-4.0.1). Thus,
C:\jakarta- tomcat- 4.0.1 is a common resultant installation directory. Note: from this point forward, I'll refer
to that location as install_dir.

2. Enable the ROOT Context

The ROOT context is the default Web application in Tomcat, and is convenient to use when you are first
learning about servlets and JSP (although you'll use your own Web applications once you're more
experienced). The default Web application is already enabled in Tomcat, Tomcat 4.0.1-4.0.3, and Tomcat
4.1. But, in Tomcat 4.0.4 it is disabled by default. To enable it, uncomment the following line in
install_dir/conf/server.xml:

<Context path="" docBase="ROOT" debug="0"/>

3. Change the Port to 80

Assuming you have no other server already running on port 80, you'll find it convenient to configure Tomcat
to run on the default HTTP port (80) instead of 8080. Making this change lets you use URLs of the form
http://localhost/blah instead of http://localhost:8080/blah. Note that you need admin privileges to make this
change on Unix. Also note that Windows XP automatically starts IIS on port 80. So, if you use XP and want
to use port 80 for Tomcat, you'll need to disable IIS.

To change the port, edit install_dir/conf/server.xml and change the port attribute of the Connector element
from 8080 to 80, yielding the result below.

<Connector

className="org.apache.catalina.connector.http.HttpConnector"
port="80" ...
... />

4. Turn on Servlet Reloading

The next step is to tell Tomcat to check the modification dates of the class files of requested servlets and
reload ones that have changed since they were loaded into the server's memory. This degrades performance
in deployment situations, so is turned off by default. However, if you fail

2
6
to turn it on for your development server, you'll have to restart the server every time you recompile a
servlet that has already been loaded into the server's memory.

To turn on servlet reloading, edit install_dir/conf/server.xml and add a DefaultContextsubelement to the


main Service element and supply true for the reloadable attribute. The easiest way to do this is to find the
following comment:

<!-- Define properties for each web application. This is only needed if you want to set non-default
properties, or have web application document roots in places other than the virtual host's appBase directory.
-->

and insert the following line just below it:

<DefaultContext reloadable="true"/>

Be sure to make a backup copy of server.xml before making the above change.

5. Set the JAVA_HOME Variable

Next, you must set the JAVA_HOME environment variable to tell Tomcat where to find Java. Failing to
properly set this variable prevents Tomcat from handling JSP pages. This variable should list the base JDK
installation directory, not the bin subdirectory. For example, if you are on Windows 98/Me and installed the
JDK in C:\JDK1.3_01, you might put the following line in your autoexec.bat file.

set JAVA_HOME=C:\JDK1.3_01

On Windows NT/2000/XP, you would go to the Start menu and select Settings, then Control Panel, then
System, then Environment. Then, you would enter the JAVA_HOME value.

Rather than setting the JAVA_ HOME environment variable globally in the operating system, some
developers prefer to edit the startup script to set it there. If you prefer this strategy, edit
install_dir/bin/catalina.bat and change the following:

if not "%JAVA_HOME%" == "" gotogotJavaHome

echo You must set JAVA_HOME to point at ...


goto cleanup
:gotJavaHome

to:

if not "%JAVA_HOME%" == "" gotogotJavaHome

set JAVA_HOME=C:\JDK1.3_01
:gotJavaHome

Be sure to make a backup copy of catalina.bat before making the changes. Also note that the exact details of
the existing catalina.bat file change a bit in different minor releases of Tomcat 4.

6. Change DOS Memory Settings

If you use Windows, you may also have to change the DOS memory settings for the startup and shutdown
scripts. If you get an "Out of Environment Space" error message when you start the server, you will need to
right-click on install_dir/bin/startup.bat, select Properties, select Memory, and change the Initial

2
7
Environment entry from Auto to at least 2816. Repeat the process for install_dir/bin/shutdown.bat.

7. Set the CATALINA_HOME Variable

If you are going to make copies of the Tomcat startup or shutdown scripts, it is also helpful to set the
CATALINA_HOME environment variable to refer to the top-level directory of the Apache Tomcat
installation (e.g. C:\jakarta- tomcat- 4.0). This variable identifies the Tomcat installation directory to the
server. However, if you are careful to avoid copying the server startup scripts and you use only shortcuts
(called "symbolic links" on Unix/Linux) instead, you are not required to set this variable.

Experiment No. 10

Program Name: 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.

Theory Concepts:Java DataBase Connectivity is used to connect Java to Database. Clsss.forName ()


method register the database driver to JDBC for connection. DriverManager.getConnection() method is used
to connect to particular database. Statement and ResultSet objects are used to execute query and to store
result of the query respectively.

Implementation:
/* HTML page to capture user data - Part:1 */
<html>
<head>
<title>Experiment No. 10</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form action = "HelloForm" method = "GET">
User 1: <input type = "text" name = "u1"><br />
password: <input type = "text" name = "p1" />
User 2: <input type = "text" name = "u2"><br />
password: <input type = "text" name = "p2" />
User 3: <input type = "text" name = "u3"><br />
password: <input type = "text" name = "p3" />
User 4: <input type = "text" name = "u4"><br />
password: <input type = "text" name = "p4" />
<input type = "submit" value = "Submit" /></form>
</body>
</html>

2
8
/* Servlet to process the result, create cookies and set it in the response - Part:2 */

import java.io.IOException;
import java.io.PrintWriter;
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 java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

@WebServlet(urlPatterns = {"/HelloForm"})
public class HelloForm extends HttpServlet {

protected void processRequest(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {

Cookie u1 = new Cookie("u1", request.getParameter("u1"));


Cookie p1 = new Cookie("p1", request.getParameter("p1"));
Cookie u2 = new Cookie("u2", request.getParameter("u2"));
Cookie p2 = new Cookie("p2", request.getParameter("p2"));
Cookie u3 = new Cookie("u3", request.getParameter("u3"));
Cookie p3 = new Cookie("p3", request.getParameter("p3"));
Cookie u4 = new Cookie("u4", request.getParameter("u4"));
Cookie p4 = new Cookie("p4", request.getParameter("p4"));

// Set expiry date after 24 Hrs for both the cookies.


u1.setMaxAge(60*60*24);
p1.setMaxAge(60*60*24);
u2.setMaxAge(60*60*24);
p2.setMaxAge(60*60*24);
u3.setMaxAge(60*60*24);
p3.setMaxAge(60*60*24);
u4.setMaxAge(60*60*24);
p4.setMaxAge(60*60*24);

// Add both the cookies in the response header.

response.addCookie( u1 );
response.addCookie( p1 );
response.addCookie( u2 );
response.addCookie( p2 );
response.addCookie( u3 );
response.addCookie( p3 );
response.addCookie( u4 );
response.addCookie( p4 );
}
}

2
9
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}

@Override
public String getServletInfo() {
return "Short description";
}

/* Servlet to read the cookies data - Part:3 */

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class ReadCookies extends HttpServlet {

protected void processRequest(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {

Cookie cookie = null;


Cookie[] cookies = null;
// Get an array of Cookies associated with this domain

cookies = request.getCookies();
response.setContentType("text/html");

if( cookies != null ) {


for (int i = 0; i<cookies.length; i++) {
cookie = cookies[i];

3
0
out.print("Name : " + cookie.getName( ) + ", ");
out.print("Value: " + cookie.getValue( ) + " <br/>"); }
} else
{ out.println("<h2>No cookies founds</h2>"); }

}
}

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}

@Override
public String getServletInfo() {
return "Short description";
}

/* Web.xml file to store servlet mappings- Part:4 */


<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-
app_3_1.xsd">
<servlet>
<servlet-name>HelloForm</servlet-name>
<servlet-class>HelloForm</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloForm</servlet-name>
<url-pattern>/HelloForm</url-pattern>
</servlet-mapping>

<servlet>
<servlet-name>ReadCookies</servlet-name>
<servlet-class>ReadCookies</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ReadCookies</servlet-name>
<url-pattern>/ReadCookies</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>

3
1
</session-config>
<welcome-file-list>
<welcome-file>
index.html
</welcome-file>
</welcome-file-list>
</web-app>

Output / Conclusion:The following is the page displayed for capturing information from the user.
Step 1: Run index.html file

Step 2: After filling information in the form

Step 3: After reading cookies data by runningReadCookies Servlet

3
2
3
3
Experiment No. 11
Program Name: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.

Theory Concepts: This program is basic login page which takes data from the user and inserts it in the
database table. It also fetches the details of the data that has already been inserted in the table.

Implementation:

Index.html

<html>
<head>
<title>JspWithMysql</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form action="registration.jsp" method="post">
username:
<input type="text" name="username" >
password:
<input type="password" name="password" >
email:
<input type="text" name="email" >
phoneNo:
<input type="text" name="phone">
<input type="submit" name="submit">
</form>
</body>
</html>

Registration.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>


<%@ page import = "java.io.*,java.util.*,java.sql.*"%>
<%@ page import = "javax.servlet.http.*,javax.servlet.*" %>
<%@ tagliburi="http://java.sun.com/jsp/jstl/core" prefix = "c"%>
<%@ tagliburi="http://java.sun.com/jsp/jstl/sql" prefix = "sql"%>
<html>
<head>
<title>Registration</title>
</head>
<body>
<sql:setDataSource var = "snapshot" driver = "com.mysql.jdbc.Driver"
url = "jdbc:mysql://localhost/TEST"
user = "root"/>
<sql:updatedataSource = "${snapshot}" var = "result">
INSERT INTO users VALUES ('<%= request.getParameter("username")%>', '<%=
request.getParameter("phone")%>', '<%= request.getParameter("email")%>', '<%=
request.getParameter("password")%>');
3
4
</sql:update>
<sql:querydataSource = "${snapshot}" var = "result">
SELECT * from users;
</sql:query>

<table border = "1" width = "100%">


<tr>
<th>username</th>
<th>email</th>
<th>phone</th>
<th>password</th>
</tr>

<c:forEach var = "row" items = "${result.rows}">


<tr>
<td><c:out value = "${row.username}"/></td>
<td><c:out value = "${row.email}"/></td>
<td><c:out value = "${row.phone}"/></td>
<td><c:out value = "${row.password}"/></td>
</tr>
</c:forEach>
</table>

</body>
</html>

Output / Conclusion

After Registration

Experiment – 12
Program Name: 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.

Theory Concepts: This program demonstrates how the JSP can be used to insert the data in the database
3
5
tables. Later when login is to be performed how the data from the database can be used to authenticate the
user.
Implementation:

Index.html

<html>
<head>
<title>JspWithMysql</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body
<form action="registration.jsp" method="post">
username:
<input type="text" name="username" >
password:
<input type="password" name="password" >
<input type="submit" value="login">
</form>
</body>
</html>

registration.jsp

<html>
<head>
<title>Registration</title>
</head>
<body>
<sql:setDataSource var = "snapshot" driver = "com.mysql.jdbc.Driver"
url = "jdbc:mysql://localhost/TEST"
user = "root"/>

<sql:querydataSource = "${snapshot}" var = "result">


SELECT * from users;
</sql:query>
<p> Login Status: </p><br>
Login :<c:out value= "${param.username}" /><br>
Password: <c:out value= "${param.password}" /><br>
<c:set var = "flag" scope = "session" value = "${0}"/>
<c:forEach var = "row" items = "${result.rows}">
<c:if test= "${row.username == param.username&&row.password == param.password}">
<c:out value= "Login Success"/>
<c:set var = "flag" scope = "session" value = "${1}"/>
</c:if>
</c:forEach>
<c:if test= "${flag == 0}">
<c:out value= "Login &Passowrd Not Valid... Try Again"/>
</c:if>
</body>
</html>

Output / Conclusion
3
6
Experiment – 13
Program Name: Write a program to implement a simple shopping cart example with session tracking
API in JSP

Theory Concepts: The program is demonstrating example of shopping cart using session tracking in
JSP.

Implementation:

<%@page contentType="text/html" pageEncoding="UTF-8"%>


<%@ page import = "java.io.*,java.util.*,java.sql.*"%>
<%@ page import = "javax.servlet.http.*,javax.servlet.*" %>

<!DOCTYPE html>
<html>
<head>
<title>Sesssion in JSP </title>
</head>
<body>
<h1>Hello World!</h1>
<TABLE>
<% String [] titles = {"SamsungGalaxy", "FastTrackWatch", "ParkAvenue", "RacingCar",
"DollHouse"};
for (int j=0; j <titles.length; j++)
{
%>
<TR>
<TD><%= titles[j] %></TD>
<TD><A HREF=ShoppingCart.jsp?itemName=<%= titles[j]%>>
Add to Shopping Cart</A></TD>
3
7
</TR>
<% } %>
</TABLE>

<% String item = request.getParameter("itemName");


if(item != null)
{
String attributeName = item;
session.setAttribute (attributeName, item);
}
%>
<HR>
Currently Selected Item :
<%= session.getAttribute(item) %>
<HR>
<HR>
Your shopping cart contains:
<% Enumeration keys = session.getAttributeNames();
while (keys.hasMoreElements())
{
String key = (String) keys.nextElement();
out.println(key + ": " + session.getValue(key) + "<br>");
}
%>
<HR>
</body>
</html>

Output / Conclusion:

3
8

You might also like