Web Technology Lab

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

lOMoARcPSD|35704443

WEB TECHNOLOGY LAB (KCS-652)


Practical List
Ex. Experiment Name Date of Date of Faculty
No Experiment Submission Signature
.
1 Write HTML/Java scripts code to display your CV in
navigator, your Institute website, Department website and
tutorial website for specific subject.

2 Design HTML form for keeping student record andvalidate


it using Java script. 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 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.

5 Write a Java applet to display the Application Program


screen i.e. calculator and other.

6 Create a Java Program to find out the IP address of your


machine.

7 Write a Java program to create an abstract class named Shape


that contains two integers and an empty method named print
Area (). Provide three classes named Rectangle, Triangle,
and Circle such that each one of the classes extends the class
Shape. Each one of the classes contains only the method
print Area () that prints the area of the given shape.

8 Write a Java program that implements a multi-thread


application that has three threads. First thread generates
random integer every 1 second and if the value is even,
second thread computes the square of the number and prints.
If the value is odd, the third thread will print the value of
cube of the number.

9 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.

10 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.
lOMoARcPSD|35704443

11 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.

12 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

13 Design and implement a simple shopping cart example with


session tracking API.
lOMoARcPSD|35704443

Experiment No:1

Objective: Write HTML/Javascript to display your CV in navigator and link


your Institute website, Department website and Tutorial website for specific
subject (HTML).

Source Code:
<html>
<head>
<h1>
<center>
<u>
<b>RESUME</u>
</b>
</center>
</h1>
</head>
<style> table, th, td
{
border: 1px solid black;
border-collapse: collapse;
}
</style>
</head>
<body>
<p>
<img src="pic.png" height="190" width="180" align="right" hspace="120"/>
<p align="middle">
<h3>
<b>NAME: ABCD</b>
</h3>
<h3>
<b>ADDRESS: Greater Noida</b>
</h3>
<h3>
<b>EMAIL: [email protected]</b>
</h3>
<h3>
<b>PHONE:0123456789</b>
</h3>
</p>
<p>
lOMoARcPSD|35704443

<hr/>
<p>
<h2>Career Objective:</h2> Seeking an engineering position that will
incorporate my undergraduate engineering coursework as well as my experience as an
administrator.</p>
<h2>Educational Qualification:</h2>
<table style="width:100%">
<tr>
<th>Course/Degree</th>
<th>Institute/College</th>
<th>Board/University</th>
<th>CGPA</th>
</tr>
<tr>
<td>10th</td>
<td>DPC School</td>
<td>CBSE</td>
<td>8.4</td>
</tr>
<tr>
<td>12th</td>
<td>Army School</td>
<td>CBSE</td>
<td>89%</td>
</tr>
<tr>
<td>B.tech</td>
<td>GL Bajaj Institute of Technology & Management
College</td>
<td>AKTU</td>
<td>79%</td>
</tr>
</table>
<h2>Technical Skills:</h2>
<ul>
<li><h3>Language Skills:</h3</li>
<ol>
<li>C</li>
<li>C++</li>
<li>Python</li>
<li>Java</li>
</ol>
<li>
<h3>Web Technology:</h3>
lOMoARcPSD|35704443

</ul>
</li> <li>HTML</li>
<ol> <li>CSS</li>

</ol> <h3>Database:</
<li> h3>

</li>
<ol> <li>DBMS</li>
<li>Oracle</li>
<li>MySql</li>

</ol>

<h2>Academic Project:</h2>
<ul>
<li>AQUA-BOT</li>
<li>Web development</li>
<li>Networking</li>
<li>INDIAHAAT</li>
</ul>
<h2>Internship:</h2>
<li>e-Yantra IIT Bombay</li>
<h2>Personal Details:</h2>
<p>NAME: ABCD</br>
ADDRESS: Greater Noida</br>
EMAIL:[email protected]</br>
PHONE: 0123456789</br>
</p>
<a href="https://glbitm.ac.in/">Institute Website</a>
<br>
<a href="https://glbitm.ac.in/">Tutorial Website</a>
<br>
<a
href="https://www.glbitm.org/dept_overview.aspx?mpgid=37&pgidtrail=37&sdeptid=21&ttype=dep
tview"> Department website</a>
<p>
<h2>
<pre>Date: Signature: </pre>
</h2>
</p>
</body>
</html>
lOMoARcPSD|35704443

OUTPUT
lOMoARcPSD|35704443

Experiment No: 2

Objective: Design HTML form for keeping student record and validate it
using javascript.

Source Code:

Main page:
<html>
<body>
<form action="f1.html" target="_top" method="get" "post"">
<center>
<fieldset>
<legend> STUDENT REGISTRATION FORM </legend>
USERNAME: <input type="text" name=" " id="name"></br></br>
PASSWORD: <input type="password" name="pass" minlength="10"
required/></br></br>
ADDRESS: <input type="text" placeholder="address" size="20%"/></br></br>
EMAIL: <input type="email" name="email" placeholder="email"/></br></br>
PHONE: <input type="number" maxlength="10" placeholder="phone"
name="num"/></br></br>
DATE OF BIRTH: <input type="date" placeholder="dd/mm/yyyy"
name="num"/></br></br>
GENDER: <input type="radio" value="male" name="gender" checked/>male
<input type="radio" value="female" name="gender"/>female </br></br>
CATEGORY: <input type="checkbox" value="sc" name="category" checked/> SC
<input type="checkbox" value="st" name="category"/> ST
<input type="checkbox" value="obc" name="category"/>OBC
<input type="checkbox" value="general"
name="category"/>GENERAL</br></br>
SELECT YOUR COURSE: <select name="subject" multiple size=2>
<option value="web technology"> web technology </option>
<option value=" computer network"> computer network
</option>
<option value="java"> java </option>
<option value="java"> JSP </option>
<option value="java"> Servlet </option>
</select></br></br>
<input type="button" onclick="submit it " value="submit"/>
<input type="button" onclick="submit it " value="reset"/>
</fieldset>
</center>
</form>
</body>
</html>
lOMoARcPSD|35704443

F1.html:
<html>
<body>
Sucessfully submitted the form.<br>
</body>
</html>

FORM VALIDATION:

<script>
function form()
{
var username = document.forms["RegForm"]["Name"];var email =
document.forms["RegForm"]["EMail"];
var phone = document.forms["RegForm"]["Telephone"];
var SelectYourCourse = document.forms["RegForm"]["Subject"];var password =
document.forms["RegForm"]["Password"];
var address = document.forms["RegForm"]["Address"];
var dateofbirth = document.forms["RegForm"]["DateOfBirth"];var gender =
document.forms["RegForm"]["Gender"];
var category = document.forms["RegForm"]["Category"];

if (username.value == "")
{
window.alert("Please enter your name.");username.focus();
return false;
}

if (address.value == "")
{
window.alert("Please enter your address.");address.focus();
return false;
}

if (email.value == "")
{
window.alert("Please enter a valid e-mail address.");email.focus();
return false;
}

if (phone.value == "")
{
window.alert("Please enter your telephone number.");phone.focus();
lOMoARcPSD|35704443

return false;
}

if (password.value == "")
{
window.alert("Please enter your password");
password.focus();return false;
}

if (dateofbirth.value ==””)
{
window.alert(“Please enter your date of birth.”);
dateofbirth.focus();return false;
}

if (gender.selectedIndex <1)
{
alert(“Please enter your gender.”);
gender.focus();return false;
}

if (category.selectedIndex <1)
{
alert(“please enter your category.”);
category.focus();return false;
}

if (SelectYourCourse.selectedIndex < 1)
{
alert("Please enter your course.");SelectYourCourse.focus();
return false;
}

return true;
}
</script>
lOMoARcPSD|35704443

OUTPUT :
lOMoARcPSD|35704443

Experiment No: 3

Objective: Write a program using javascript for Web page to display browser
Information

Source Code:-
<html>
<head>
<title>Browser Information</title>
</head>
<body>
<h1>Browser Information</h1>
<hr>
<p>
The <b>navigator</b> object contains the following information
about the browser you are using.
</p>
<ul>
<script LANGUAGE="JavaScript" type="text/javascript">
document.write("<li> <b>Code Name:</b> " +
navigator.appCodeName); document.write("<li> <b>App
Name:</b> " + navigator.appName);
document.write("<li>
<b>App Version:</b> " + navigator.appVersion); document.write("<li>
<b>User Agent:</b> " + navigator.userAgent); document.write("<li>
<b>Language:</b> " + navigator.language); document.write("<li>
<b>Platform:</b> " + navigator.platform);
</script>
</ul>
</body>
</html>
lOMoARcPSD|35704443

OUTPUT:-
lOMoARcPSD|35704443

Experiment No: 4

Objective: Write a program in XML for creation of DTD, which


specifies set of rules. Create a stylesheet in CSS/XSL and display the
document in internet explorer.[Book information]

Source code:

book.DTD

<!ELEMENT books (heading,book*)>


<!ELEMENT heading (#PCDATA)>
<!ELEMENT book ((bookname|title),author+,publisher?,edition,price)>
<!ELEMENT bookname (#PCDATA)>
<!ELEMENT title (#PCDATA)>
<!ELEMENT author (#PCDATA)>
<!ELEMENT publisher (#PCDATA)>
<!ELEMENT edition (#PCDATA)>
<!ELEMENT price (#PCDATA)>

book.css

books {
color: white; background-color:grey; width:100%;
}

heading {
color: green; font-size: 40px;
background-color: blue;
}

heading,title,author,publisher,edition,price{
display: block;
}

title{
font-size: 25px; font-weight: bold;
}

10
lOMoARcPSD|35704443

Book.xml

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


<?xml-stylesheet type="text/css" href="book.css"?>
<!DOCTYPE books SYSTEM "book.dtd">
<books>
<heading>xml with css</heading>
<book>
<title>Title: Web Technology</title>
<author>Author: Gopal</author>
<publisher>Publisher: PHI</publisher>
<edition>Edition : 2nd</edition>
<price>Price: Rs.200</price>
</book>
<book>
<title>Title: J2REE</title>
<author>Author: Santo</author>
<publisher>Publisher: APL</publisher>
<edition>Edition : 3rd</edition>
<price>Price: Rs.500</price>
</book>
</books>
lOMoARcPSD|35704443

OUTPUT:
lOMoARcPSD|35704443

Experiment No: 5

Objective: - Write a Java applet to display the Application Program screen


i.e. calculator and other.

Source Code

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;;
//<applet code="calculator" width=600 height=800>
//</applet>
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; 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");
lOMoARcPSD|35704443

GridLayout gb=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);
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);
}
lOMoARcPSD|35704443

public void paint()

{
setBackground(Color.blue);
}

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();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));
}
lOMoARcPSD|35704443

if(s.equals("Clear"))
{
t1.setText("");
}
}
public void textValueChanged(TextEvent e)
{
}
}
lOMoARcPSD|35704443

Output:-
lOMoARcPSD|35704443

Experiment No: 6

Objective:-Create a Java Program to find out the IP address of your


machine.

Source code:
import java.net.InetAddress;
import java.net.UnknownHostException;
public class LocalIPAddressExample
{
public static void main(String[] args)
{
try
{
InetAddress localhost = InetAddress.getLocalHost();

System.out.println("Local IP Address: " + localhost.getHostAddress());


}
catch (UnknownHostException ex)
{
ex.printStackTrace();
}
}
}
lOMoARcPSD|35704443

Output:-
lOMoARcPSD|35704443

Experiment No: 7

Objective: Write a Java program to create an abstract class named Shape that
contains two integers and an empty method named print Area (). Provide three
classes named Rectangle, Triangle, and Circle such that each one of the classes
extends the class Shape. Each one of the classes contains only the method print
Area () that prints the area of the given shape.

Source code:

abstract class Shape


{
int height;
int width;
int radius;
abstract int printArea();
}

class Rectangle extends Shape


{
Rectangle(int width,int height)
{
this.width=width;
this.height=height;
}
int printArea()
{
System.out.println("Inside Area for Rectangle.");
return height * width;
}
}
class Triangle extends Shape
{
Triangle(int width, int height)
{
this.width=width;
this.height=height;
}
int printArea()
{
System.out.println("Inside Area for Triangle.");
return height * width / 2;
lOMoARcPSD|35704443

}
}
class Circle extends Shape
{
Circle(int r)
{
radius=r;
}
int printArea()
{
System.out.println("Inside Area for
Circle."); int area=(int)(3.14*radius*radius);
return(area);
}
}
public class AbstractDemo
{
public static void main(String
args[]) {
Rectangle r = new Rectangle(10,
5); Triangle t = new Triangle(10,
8);
Circle c=new Circle(10);

System.out.println("Area is " +r.printArea());


System.out.println("Area is " +
t.printArea()); System.out.println("Area is "
+c.printArea());

}
lOMoARcPSD|35704443

Output:
lOMoARcPSD|35704443

Experiment No: 8

Objective: Write a Java program that implements a multi-thread application that


has three threads. First thread generates random integer every 1 second and if
the value is even, second thread computes the square of the number and prints. If
the value is odd, the third thread will print the value of cube of the number.

Source code:
import java.util.*;
class Even implements Runnable
{
public int x; public Even(int x)
{
this.x = x;
}
public void run()
{
System.out.println("New Thread "+ x +" is EVEN and Square of " + x + " is: " + x *
x); }
}
class Odd implements Runnable
{
public int x; public Odd(int x)
{
this.x = x;
}
public void run()
{
System.out.println("New Thread "+ x +" is ODD and Cube of " + x + " is: " + x *
x * x);
}
}
class A extends Thread
{
public void run()
{
int num = 0;
Random r = new Random(); try
{
for (int i = 0; i < 5; i++)
{
num = r.nextInt(100);
lOMoARcPSD|35704443

System.out.println("Main Thread and Generated Number is " +


num); if (num % 2 == 0)
{
Thread t1 = new Thread(new Even(num));
t1.start();
}
else
{
Thread t2 = new Thread(new Odd(num));
t2.start();
}
Thread.sleep(1000);
System.out.println("--------------- “);
}
}
Catch(Exception ex)
{
System.out.println(ex.getMessage());
}
}
}
public class ThreeThreadDemo
{
public static void main(String[] args)
{
A a = new A();
a.start();
}
}
lOMoARcPSD|35704443

Output:-

Main Thread and Generated Number is 87


New Thread 87 is ODD and Cube of 87 is: 658503

Main Thread and Generated Number is 6 New Thread 6 is EVEN and Square of 6 is: 36

Main Thread and Generated Number is 3 New Thread 3 is ODD and Cube of 3 is: 27

Main Thread and Generated Number is 80


New Thread 80 is EVEN and Square of 80 is: 6400

Main Thread and Generated Number is 1 New Thread 1 is ODD and Cube of 1 is: 1
lOMoARcPSD|35704443

Experiment No: 9

Objective: 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.

Source Code

Step1: Create a directory to keep all your works.

Step2: Download and Install TOMCAT


For Windows:
Goto http://tomcat.apache.org
Tomcat's Directories
● bin: contains the binaries; and startup script (startup.bat for Windows and startup.sh for Unixes
and Mac OS), shutdown script (shutdown.bat for Windows and shutdown.sh for Unix and Mac
OS), and other binaries and scripts.
● conf: contains the system-wide configuration files, such as server.xml, web.xml, and
context.xml.
● webapps: contains the webapps to be deployed. You can also place the WAR (Webapp Archive)
file for deployment here.
● lib: contains the Tomcat's system-wide JAR files, accessible by all webapps. You could also place
external JAR file (such as MySQL JDBC Driver) here.
● logs: contains Tomcat's log files. You may need to check for error messages here. ●
work: Tomcat's working directory used by JSP, for JSP-to-Servlet conversion.

Step 3: Create an Environment variable JAVA_HOME

Step 4: Cofigure TOMCAT Server


The Tomcat configuration files are located in the "conf" sub-directory of your Tomcat installed
directory, e.g. "c:\myWebProject\tomcat\conf" (for Windows).
There are 4 configuration files : server.xml,
web.xml, context.xml

Step 5: Start TOMCAT Server

Step 6: Develop and Deploy Web Application.


lOMoARcPSD|35704443

Write a Welcome Page


<html>

<head>
<title>My Home Page</title>
</head>

<body>
<h1>My Name is so and so. This is my HOME.</h1>
</body>

</html>

Write HelloWorld.java Servletimport java.io.*;


import javax.servlet.*; import javax.servlet.http.*;

public class HelloServlet extends HttpServlet {@Override


public void doGet(HttpServletRequest request, HttpServletResponse response)throws IOException,
ServletException {

// Set the response MIME type of the response messageresponse.setContentType("text/html"); //


Allocate a output writer to write the response message into the network socketPrintWriter out =
response.getWriter();

// Write the response message, in an HTML pagetry {


out.println("<html>");
out.println("<head><title>Hello, World</title></head>");out.println("<body>");
out.println("<h1>Hello, world!</h1>"); // says Hello
// Echo client's request information
out.println("<p>Request URI: " + request.getRequestURI() + "</p>"); out.println("<p>Protocol: " +
request.getProtocol() + "</p>"); out.println("<p>PathInfo: " + request.getPathInfo() + "</p>");
out.println("<p>Remote Address: " + request.getRemoteAddr() + "</p>");
// Generate a random number upon each request out.println("<p>A Random Number: <strong>" +
Math.random() +
"</strong></p>"); out.println("</body></html>");
} finally {
out.close(); // Always close the output writer
}
}
}

23
lOMoARcPSD|35704443

Configure Servlet's Request URL in


"webapps\hello\WEB-INF\web.xml" <?xml version="1.0"
encoding="ISO-8859-1"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web
app_3_0.xsd">

<!-- To save as "hello\WEB-INF\web.xml" -->


<servlet>
<servlet-name>HelloWorld</servlet-name>
<servlet-class>HelloServlet</servlet-class>
</servlet>

<!-- Note: All <servlet> elements MUST be grouped together andplaced IN FRONT of the <servlet
mapping> elements -->

<servlet-mapping>
<servlet-name>HelloWorld</servlet-name>
<url-pattern>/sayhello</url-pattern>
</servlet-mapping>
</web-app>
lOMoARcPSD|35704443

OUTPUT:
lOMoARcPSD|35704443

Experiment No: 10

Objective: 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.

Source Code:

Theory:

Creating JDBC Application

There are following six steps involved in building a JDBC application −

∙ Import the packages: Requires that you include the packages containing the JDBCclasses
needed for database programming. Most often, using import java.sql.* will suffice. ∙ Register
the JDBC driver: Requires that you initialize a driver so you can open a communication
channel with the database.
∙ Open a connection: Requires using the DriverManager.getConnection() method to create a
Connection object, which represents a physical connection with the database. ∙ Execute a
query: Requires using an object of type Statement for building and submittingan SQL statement
to the database.
∙ Extract data from result set: Requires that you use the appropriate ResultSet.getXXX()
method to retrieve the data from the result set.
∙ Clean up the environment: Requires explicitly closing all database resources versus
relying on the JVM's garbage collection.

Step 1: Let's create a MySQL database named „library’ with a table named „books’.

The table should have columnslike „id’, „title’, „author’, „price’, and „quantity’.

CREATE DATABASE library;


USE library;
CREATE TABLE books (
id INT PRIMARY KEY AUTO_INCREMENT,
title VARCHAR(255),
author VARCHAR(255),
price DECIMAL(10, 2),
quantity INT
);
lOMoARcPSD|35704443

Next, write the JDBC Connectivity Program:

import java.sql.*;

public class JDBCExample {


public static void main(String[] args) {
try {
// Load the JDBC driver
Class.forName("com.mysql.cj.jdbc.Driver");

// Establish connection
String url = "jdbc:mysql://localhost:3306/mydatabase";
String username = "username";
String password = "password";
Connection conn = DriverManager.getConnection(url, username, password);

// Create a statement
Statement stmt = conn.createStatement();

// Execute a query
String sqlQuery = "SELECT * FROM books";
ResultSet rs = stmt.executeQuery(sqlQuery);

// Process the result set


while (rs.next()) {
int id = rs.getInt("id");
String title = rs.getString("title");
String author = rs.getString("author");
double price = rs.getDouble("price");
System.out.println("ID: " + id + ", Title: " + title + ", Author: " + author + ",
Price: $" + price);
}

// Close resources
rs.close();
stmt.close();
conn.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}

26
lOMoARcPSD|35704443

Next, write Servlet for Book Query:

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;

public class BookQueryServlet extends HttpServlet {


public void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();

try {
// Load the JDBC driver
Class.forName("com.mysql.cj.jdbc.Driver");

// Establish connection
String url = "jdbc:mysql://localhost:3306/mydatabase";
String username = "username";
String password = "password";
Connection conn = DriverManager.getConnection(url, username, password);

// Create a statement
Statement stmt = conn.createStatement();

// Execute a query
String sqlQuery = "SELECT * FROM books";
ResultSet rs = stmt.executeQuery(sqlQuery);

// Display the result in HTML format


out.println("<html><head><title>Book Query Results</title></head><body>");
out.println("<h1>Book Query Results</h1>");
out.println("<table
border='1'><tr><th>ID</th><th>Title</th><th>Author</th><th>Price</th></tr>");

while (rs.next()) {
int id = rs.getInt("id");
String title = rs.getString("title");
String author = rs.getString("author");
double price = rs.getDouble("price");
out.println("<tr><td>" + id + "</td><td>" + title + "</td><td>" + author +
"</td><td>$" + price + "</td></tr>");
}
27
lOMoARcPSD|35704443

out.println("</table></body></html>");

// Close resources
rs.close();
stmt.close();
conn.close();
} catch (Exception e) {
out.println("Error: " + e.getMessage());
}
}
}

Note: Replace jdbc:mysql://localhost:3306/mydatabase with your database URL, and provide the
correct username and password.

28
lOMoARcPSD|35704443

Experiment No: 11

Objective: Install a database MySql. 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.

Source Code
Step 1: Database Installation (MySQL)

1. Download and install MySQL from the official website according to your operating system. 2.
Once installed, start the MySQL server and open a terminal or command prompt. 3. Log in to
MySQL using the command mysql -u username -p, where username is your MySQL username.
4. Create a new database for our example, e.g., CREATE DATABASE mywebsite_db;.
5. Switch to the newly created database: USE mywebsite_db;.
6. Create a table named users with the required fields:

CREATE TABLE users (


id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
password VARCHAR(255) NOT NULL,
email VARCHAR(255) NOT NULL,
phone VARCHAR(15) NOT NULL
);

Step 2: JSP Code for Database Connectivity and User Registration

1. Create a new JSP file, e.g., register.jsp, in your web application directory. 2. Add the
following code to establish a connection to the MySQL database and insert user registration
details:

Registration.html:
<html>
<head>
<title>Registration page</title>
</head>
<body bgcolor="#00FFFf">
<form METHOD="POST" ACTION="register">
<CENTER>
<table>
29

<center>
lOMoARcPSD|35704443

<tr>
<td> Username </td>
<td><input type="text" name="usr"> </td>
</tr>
<tr>
<td> Password </td>
<td><input type="password" name="pwd"> </td>
</tr>
<tr>
<td>Age</td>
<td><input type="text" name="age"> </td>
</tr>
<tr>
<td>Address</td>
<td> <input type="text" name="add"> </td>
</tr>
<tr>
<td>email</td>
<td> <input type="text" name="mail"> </td>
</tr>
<tr>
<td>Phone</td>
<td> <input type="text" name="phone"> </td>
</tr>
<tr>
<td colspan=2 align=center> <input type="submit" value="submit"> </td>
</tr>
</center>
</table>
</form>
</body>
Login.html
<html>
<head>
<title>Registration page</title>
</head>
<body bgcolor=pink>
<center>
<table>
<form METHOD="POST" ACTION="authent">
<tr>
<td> Username </td>

30
lOMoARcPSD|35704443

<td><input type="text" name="usr"></td>


</tr>
<tr>
<td> Password </td>
<td> <input type="password" name="pwd"> </td>
</tr>
<tr>
<td align=center colspan="2"><input type="submit" value="submit"></td>
</tr>
</table>
</center>
</form>
</body>
</html>

Ini.java:
import javax.servlet.*;
import java.sql.*;
import java.io.*;
public class Ini extends GenericServlet
{
private String user1,pwd1,email1;
public void service(ServletRequest req,ServletResponse res) throws ServletException,IOException
{
user1=req.getParameter("user");
pwd1=req.getParameter("pwd");
email1=req.getParameter("email");
res.setContentType("text/html");
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection ("jdbc:oracle:thin:@195.100.101.158:1521:cclab",
"scott","tiger")
;
PreparedStatement st=con.prepareStatement("insert into personal values(?,?,?,?,?,?)");
st.setString(1,user1);
st.setString(2,pwd1);
st.setString(3,"25");
st.setString(4,"hyd");
st.setString(5,email1);
st.setString(6,"21234");
st.executeUpdate();
con.close();
}
31
lOMoARcPSD|35704443

catch(SQLException s)
{ out.println("not found "+s);
}
catch(ClassNotFoundException c)
{
out.println("not found "+c);
}
}}

web.xml:
<web-app>
<servlet>
<servlet-name>init1</servlet-name>
<servlet-class>Ini</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>init1</servlet-name>
<url-pattern>/regis</url-pattern>
</servlet-mapping>
</web-app>
lOMoARcPSD|35704443

OUTPUT:
lOMoARcPSD|35704443

Experiment No: 12

Objective: 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

Source Code

Login.html:

<!--Home.html-->
<html>
<body>
<center><h1>XYZ Company Ltd.</h1></center>
<table border="1" width="100%" height="100%">
<tr>
<td valign="top" align="center"><br/>
<form action="auth.jsp"><table>
<tr>
<td colspan="2" align="center"><b>Login Page</b></td>
</tr>
<tr>
<td colspan="2" align="center"><b>&nbsp;</td>
</tr>
<tr>
<td>User Name</td>
<td><input type="text" name="user"/></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="pwd"/></td>
</tr>
<tr>
<td>&nbsp;</td>
<td>&nbsp;</td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="LogIN"/></td>
</tr>
</table>
34
lOMoARcPSD|35704443

</form>
</td>
</tr>
</table>

</body>
</html>

Auth.jsp:
<%@page import="java.sql.*;"%>
<html>
<head>
<title>
This is simple data base example in JSP</title>
</title>
</head>
<body bgcolor="yellow">
<%!String uname,pwd;%>
<%
uname=request.getParameter("user");
pwd=request.getParameter("pwd");
try
{
// Establish database connection
Class.forName("com.mysql.cj.jdbc.Driver");
String dbUrl = "jdbc:mysql://localhost:3306/mywebsite_db";
String dbUsername = "username";
String dbPassword = "password";
Connection con = DriverManager.getConnection(dbUrl, dbUsername, dbPassword);

Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select name,password from personal where
name='"+uname+"' and password='"+pwd+"'");
if(rs.next())
{
out.println("Authorized person");
}
else
{
out.println("UnAuthorized person");
}
con.close();
35
lOMoARcPSD|35704443

catch(Exception e){out.println(""+e);}
%>
</body>
</html>
lOMoARcPSD|35704443

OUTPUT:

36
lOMoARcPSD|35704443

Experiment No: 13

Objective: Design and implement a simple shopping cart examplewith


session tracking API.

Source Code

ShoppingCart.html

<h3>Cookie Example through Shopping Cart</h3>


<body>
<form method="get" action="http://localhost:8888/india/SC">

Enter Item Name <input type="text" name="item"><br> Enter Item Quantity <input type="text"
name="qty"><br>
<input type="submit" value="Add Cookie" name="add">
<input type="submit" value="List Cookies" name="list">

</form>
</body>

web.xml entry for ShoppingCart servlet


<servlet>
<servlet-name>snrao1</servlet-name>
<servlet-class>ShoppingCart</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>snrao1</servlet-name>
<url-pattern>/SC</url-pattern>
</servlet-mapping>

ShoppingCart.java
import java.io.*; import javax.servlet.*;
import javax.servlet.http.*;
public class ShoppingCart extends HttpServlet
{
public void service(HttpServletRequest req,HttpServletResponse res) throwsServletException,

37
lOMoARcPSD|35704443

IOException
{
String str1 = req.getParameter("item");
// item name String str2 = req.getParameter("qty");
// item quantity
String str3 = req.getParameter("add"); // submit button by name addString str4 =
req.getParameter("list"); // submit button by name list

res.setContentType("text/html");PrintWriter out = res.getWriter();

if(str3 != null)
{
Cookie c1 = new Cookie(str1, str2); res.addCookie(c1);
res.sendRedirect("ShoppingCart.html"); }
else if(str4 != null)
{
Cookie clientCookies[] = req.getCookies();for( int i = 0; i < clientCookies.length; i++) {
out.print("<B>" + clientCookies[i].getName() + " : " + clientCookies[i].getValue()
+"</B><BR>"); }
}
out.close( ) ;
}
}
lOMoARcPSD|35704443

OUTPUT:-

You might also like