You are on page 1of 61

1

………….. …………..

1. Write a Java program to implement Filter streams using


BufferedInputStream and BufferedOutputStream

FilterStreamApplication.java
import java.io.*;
public class FilterStreamApplication {
public static void main(String[] args) {
try {
//reading-side
FileInputStream fis = new FileInputStream("source.txt"); // a low-level
stream
FilterInputStream filterIn = new BufferedInputStream(fis); // a high-level
stream
// writing-side
FileOutputStream fos = new FileOutputStream("destination.txt"); // a low-
level stream
FilterOutputStream filterOut = new BufferedOutputStream(fos); // a high-
level stream
//read data, convert to uppercase, write data
int data;
while( ( data = filterIn.read() ) != -1 ) {
data = Character.toUpperCase((char) data);
filterOut.write(data);
System.out.print((char) data);
}
filterIn.close();
filterOut.close();
fis.close();
fos.close();
} catch (IOException ie) {
System.err.println("Exception in filtering:"+ie.getMessage());
}}}

Source.txt
hello
OUTPUT
2
………….. …………..

2. Write a program to implement pipe streams using PipedInputStream and


PipedOutputStream

import java.io.IOException;
import java.io.PipedInputStream;
import
java.io.PipedOutputStream;

public class PipeStreamApplication


{ public static void main(String[] args) {
final PipedInputStream pis = new PipedInputStream();
final PipedOutputStream pos = new PipedOutputStream();
try {
pos.connect(pis);
Thread producer = new Thread()
{ public void run() {
try {
for (int i = 1; i <= 10; i++)
{ pos.write((byte) i);
pos.flush();
System.out.println("Writing: " + i);
Thread.sleep(500); // Pause the thread execution for 500
milliseconds.
}
pos.close();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};

// creating one thread consumer which consumes the data


Thread consumer = new Thread() {
public void run()
{ try {
int data;
while ((data = pis.read()) != -1)
{ System.out.println("Reading: " + data);
}
pis.close();
} catch (IOException e) {
3
………….. …………..

e.printStackTrace();
}
}
};

// starting both threads


producer.start();
consumer.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
4
………….. …………..

OUTPUT
5
………….. …………..
6
………….. …………..

3. Write a program to implement thread synchronization using synchronized


method.

MultiThreadSynchronizedExample.java

package program5;
public class MultiThreadExample {
public static void main(String args[]) {
//these two threads are accessing the same resource
Thread t1 = new Thread() {
public void run() {
printCount(5);
}
};
Thread t2 = new Thread() {
public void run() {
printCount(10);
}
};
//start both threads
t1.start();
t2.start();
// wait for the threads to be finished completely
try {
t1.join();
t2.join();
} catch ( Exception e) {
System.out.println("Interrupted");
}
}
public static synchronized void printCount(int n) {
try {
for(int i = 1; i < 5; i++)
{ System.out.println("Counting --- " + n*i );
}
} catch (Exception e)
{ System.out.println("Thread
interrupted.");
}
}
}
7
………….. …………..

Output
8
………….. …………..

4. Write a Java program to implement Object Serialization and Object De-


Serialization

SerializeExample.java

package program10;

import java.io.FileOutputStream;
import java.io.ObjectOutputStream;

public class SerializeExample {


public static void main(String[] args) {

//Creates an object to serialize


Person person = new Person("Robert Weber", 30);

try {
//Create file output stream
FileOutputStream fileOut = new FileOutputStream("person.dat");
//Create object output stream
ObjectOutputStream out = new ObjectOutputStream(fileOut);

//Serialize object
out.writeObject(person);

//Close output streams


out.close();
fileOut.close();

System.out.println("Object has been serialized");

}catch (Exception e) {
e.printStackTrace();
}
}
}
9
………….. …………..

DeSerializeExample.java

package program10;
import java.io.FileInputStream;
import java.io.ObjectInputStream;

public class DeSerializeExample {


public static void main(String[] args)
{ try {

//Create file input stream


FileInputStream fileIn = new FileInputStream("person.dat");

//Create object input stream


ObjectInputStream objIn = new ObjectInputStream(fileIn);

//De-serialize object
Person person = (Person) objIn.readObject();

//Print de-serialized object's details


System.out.println("Object has been deserialized...");
System.out.println("Person Name: " + person.getName());
System.out.println("Person Age: " + person.getAge());

// Close input streams


objIn.close();
fileIn.close();

}catch (Exception e) {
e.printStackTrace();
}
}
}
10
………….. …………..

Person .java

package program10;

import java.io.Serializable;
public class Person implements Serializable
{ private static final long serialVersionUID =
1L; private String name;
private int age;
transient long b;
public Person(String name, int age) {
super();
this.name = name;
this.age = age;
}
public void setName(String name)
{ this.name = name;
}
public String getName() {
return name;
}
public void setAge(int age)
{ this.age = age;
}
public int getAge()
{ return age;
}
}
11
………….. …………..

Output
12
………….. …………..

5. Write a Java program to implement the various operations regarding JAR


file creation
1. Create a jar file: jar command with cvfm option
2. View the jar file: jar command with tf option
3. Extract the jar file: jar command with xvf option

Student.java

package prgm11;
public class Student {
private String name;
private int id;

public Student(String name, int id) {


super();
this.name = name;
this.id = id;
}

public String getName()


{ return name;
}
public void setName(String name)
{ this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
//other methods as needed
}

Course.java
package prgm11;
public class Course {
private String name;
13
………….. …………..

private String courseId;

public String getName()


{ return name;
}
public void setName(String name)
{ this.name = name;
}
public String getCourseId()
{ return courseId;
}
public void setCourseId(String courseId)
{ this.courseId = courseId;
}

Main.java

package prgm11;
public class Main {

public static void main(String[] args)


{ System.out.println("Student app main method");
//crate array of students
Student students[] = new Student[2];
//Adding students to the array
students[0] = new Student("John", 345);
students[1] = new Student("Robert", 247);

for (Student student: students) {


System.out.println("Name: "+student.getName()+ " ID:"+student.getId());
}
}
}
14
………….. …………..

OUTPUT
15
………….. …………..

6. Write a Java Servlet Program to implement and demonstrate GET method


(Using HttpServlet Class).

index.html
<!DOCTYPE html>
<html>
<head>
<title>HTTP Request Method Example</title>
</head>
<body>
<h2>GET Request Example</h2>
<a href="/pgm12/get-method.html">GET Method Example</a>
</body>
</html>

get-method.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>GET Servlet Example</title>
</head>
<body>
<h2>Enter Your Name</h2>
<form action="/pgm12/GetServlet" method="get">
<label for="name">Name:</label>
<input type="text" id="name" name="name"><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>

GetServlet.java

package pgm12;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
16
………….. …………..

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/GetServlet")
public class GetServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

public GetServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {

//Set response content type


response.setContentType("text/html");

//Get the parameter value from the request


String name = request.getParameter("name");

//Prepare the response message


String title = "Using GET Method to Read Form Data";
String message = "Hello, " + name + "! Welcome to our website.";

//Write the response


PrintWriter out = response.getWriter();
out.println("<html><body>");
out.println("<head><title>" + title + "</title></head>");
out.println("<h1>" + message + "</h1>");
out.println("</body></html>");
}
}
17
………….. …………..

OUTPUT
18
………….. …………..

7. Write a Java Servlet Program to implement and demonstrate POST method


(Using HttpServlet Class).

index.html
<!DOCTYPE html>
<html>
<head>
<title>POST Request Form</title>
</head>
<body>
<h2>POST Request Example</h2>
<a href="/servlet-example/post-method.html">POST Method Example</a></body>
</html>
Post-method.html
<!DOCTYPE html>
<html>
<head>
<title>POST Request Form</title>
</head>
<body>
<h2>Enter Your Name</h2>
<form action="/pgm13/PostServlet" method="post">
<label for="name">Name:</label>
<input type="text" id="name" name="name"><br><br>
<input type="submit" value="Submit">
</form>
</body>
19
………….. …………..

</html>

PostServlet.java
package pgm13;
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;
@WebServlet("/PostServlet")
public class PostServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

public PostServlet() {
super();
// TODO Auto-generated constructor stub
}
protected void doPost(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
//Set response content type
response.setContentType("text/html");
//Get the parameter values from the request
String name = request.getParameter("name");
//Prepare the response message
String title = "Using POST Method to Read Form Data";
20
………….. …………..

String message = "Hello," + name + "! Your name was submitted via POST
request";
//Write the response
PrintWriter out = response.getWriter();
out.println("<html><body>");
out.println("<head><title>" + title + "</title></head>");
out.println("<h1>" + message + "</h1>");
out.println("</body></html>");
}
}
21
………….. …………..

OUTPUT
22
………….. …………..

8. Design the front-end page for an online web application. The web application
consists of a home page, user registration page and login page of an online web
application. The user registration page includes fields for Username, Name,
Email, Password, Confirm Password, Date of Birth, Gender, and Country.
Index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>User Registration and Login</title>
</head>
<body>
<h2>User Registration and Login</h2>
<ul>
<li><a href="registration.html">Register</a></li>
<li><a href="login.html">Login</a></li>
</ul>
</body>
</html>

registration.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
23
………….. …………..

<title>User Registration</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<form action="#" method="post">
<a href="/pgm16"><img src="logo-store.JPG" alt="Home"></a>
<h2>User Registration</h2>
<label for="username">Username:</label>
<input type="text" id="username" name="username"><br>

<label for="name">Name:</label>
<input type="text" id="name" name="name"><br>

<label for="email">Email:</label>
<input type="email" id="email" name="email"><br>

<label for="password">Password:</label>
<input type="password" id="password" name="password"><br>

<label for="confirm_password">Confirm Password:</label>


<input type="password" id="confirm_password" name="confirm_password"><br>

<label for="dob">Date of Birth:</label>


<input type="date" id="dob" name="dob"><br>

<label for="gender">Gender:</label>
<select id="gender" name="gender">
24
………….. …………..

<option value="">Select Gender</option>


<option value="male">Male</option>
<option value="female">Female</option>
<option value="other">Other</option>
</select><br>

<label for="country">Country:</label>
<select id="country" name="country">
<option value="">Select Country</option>
<option value="india">India</option>
<option value="usa">USA</option>
<option value="uk">UK</option>
<option value="canada">Canada</option>
<option value="australia">Australia</option>
</select><br><br>

<input type="submit" value="Register">


</form>
</body>
</html>

login.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
25
………….. …………..

<title>Login Page</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<form action="/login" method="post">
<a href="/pgm16"><img src="logo-store.JPG" alt="Home"></a>
<h2>Login</h2>
<label for="username">Username:</label>
<input type="text" id="username" name="username"><br><br>
<label for="password">Password:</label>
<input type="password" id="password" name="password"><br>
<input type="submit" value="Login">
</form>
</body>
</html>
style.css
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
background-color: #f2f2f2;
}/*
form {
width: 400px;
padding: 20px;
26
………….. …………..

border: 1px solid #ccc;


background-color: #fff;
border-radius: 8px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
input[type="text"],
input[type="email"],
input[type="password"],
select {
width: calc(100% - 12px);
padding: 6px;
margin: 6px 0;
border: 1px solid #ccc;
border-radius: 4px;
}*/
input[type="submit"] {
width: 100%;
padding: 10px;
margin-top: 10px;
background-color: #007bff;
color: #fff;
border: none;
border-radius: 4px;
cursor: pointer;
}
input[type="submit"]:hover
{ background-color: #0056b3; }
27
………….. …………..

OUTPUT
28
………….. …………..
29
………….. …………..

9. Add the JavaScript to the user registration page of an online web application.
index.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>User Registration</title>
</head>
<body>
<h2>User Registration</h2>
<ul>
<li><a href="registration.html">Register</a></li>
</ul>
</body>
</html>

registration.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>User Registration</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script>
function validateForm(form) {
var username = document.getElementById("username").value;
var email = document.getElementById("email").value;
var password = document.getElementById("password").value;
var confirm_password = document.getElementById("confirm_password").value;
var dob = document.getElementById("dob").value;
var gender = document.getElementById("gender").value;
var country = document.getElementById("country").value;
30
………….. …………..

// Check if any field is empty


if (username === "" || email === "" || password === "" || dob === "" ||
gender === "" || country === "") {
alert("All fields are required");
return false;
}

// Check if password matches confirm password


if (password !== confirm_password) {
alert("Password and confirm password do not match");
return false;
}

// Validation successful
alert("All validations successful");
return true;
}
</script>
</head>
<body>
<form action="/registration" method="post" onsubmit="return validateForm()">
<a href="/pgm17"><img src="logo-store.JPG" alt="Home"></a>
<h2>User Registration</h2>
<label for="username">Username:</label>
<input type="text" id="username" name="username"><br>

<label for="name">Name:</label>
<input type="text" id="name" name="name"><br>

<label for="email">Email:</label>
<input type="email" id="email" name="email"><br>

<label for="password">Password:</label>
<input type="password" id="password" name="password"><br>
31
………….. …………..

<label for="confirm_password">Confirm Password:</label>


<input type="password" id="confirm_password" name="confirm_password"><br>

<label for="dob">Date of Birth:</label>


<input type="date" id="dob" name="dob"><br>

<label for="gender">Gender:</label>
<select id="gender" name="gender">
<option value="">Select Gender</option>
<option value="male">Male</option>
<option value="female">Female</option>
<option value="other">Other</option>
</select><br>

<label for="country">Country:</label>
<select id="country" name="country">
<option value="">Select Country</option>
<option value="india">India</option>
<option value="usa">USA</option>
<option value="uk">UK</option>
<option value="canada">Canada</option>
<option value="australia">Australia</option>
</select><br><br>

<input type="submit" value="Register">


</form>
</body>
</html>
32
………….. …………..

style.css

body {

display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
background-color: #f2f2f2;
}/*
form {
width: 400px;
padding: 20px;
border: 1px solid #ccc;
background-color: #fff;
border-radius: 8px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
input[type="text"],
input[type="email"],
input[type="password"],
select {
width: calc(100% - 12px);
padding: 6px;
margin: 6px 0;
border: 1px solid #ccc;
border-radius: 4px;
33
………….. …………..

}*/
input[type="submit"] {
width: 100%;
padding: 10px;
margin-top: 10px;
background-color: #007bff;
color: #fff;
border: none;
border-radius: 4px;
cursor: pointer;
}
input[type="submit"]:hover
{ background-color:
#0056b3;
}
34
………….. …………..

OUTPUT
35
………….. …………..
36
………….. …………..

10. Convert the static user registration page of an online web application into
dynamic web pages using JSP. Utilize SimpleDateFormat to present the date
of birth in the desired format.

Index.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>User Registration</title>
</head>
<body>
<h2>User Registration</h2>
<ul>
<li><a href="registration.html">Register</a></li>
</ul>
</body>
</html>

registration.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>User Registration</title>
<link rel="stylesheet" type="text/css" href="style.css">
37
………….. …………..

<script>
function validateForm(form) {
var username = document.getElementById("username").value;
var email = document.getElementById("email").value;
var password = document.getElementById("password").value;
var confirm_password = document.getElementById("confirm_password").value;
var dob = document.getElementById("dob").value;
var gender = document.getElementById("gender").value;
var country = document.getElementById("country").value;
// Check if any field is empty
if (username === "" || email === "" || password === "" || dob === "" ||
gender === "" || country === "") {
alert("All fields are required");
return false;
}

// Check if password matches confirm password


if (password !== confirm_password) {
alert("Password and confirm password do not match");
return false;
}
// Validation successful
alert("All validations successful");
return true;
}
</script>
</head>
38
………….. …………..

<body>
<form action="registration.jsp" method="post" onsubmit="return validateForm()">
<a href="/pgm18"><img src="logo-store.JPG" alt="Home"></a>
<h2>User Registration</h2>
<label for="username">Username:</label>
<input type="text" id="username" name="username"><br>

<label for="name">Name:</label>
<input type="text" id="name" name="name"><br>

<label for="email">Email:</label>
<input type="email" id="email" name="email"><br>

<label for="password">Password:</label>
<input type="password" id="password" name="password"><br>

<label for="confirm_password">Confirm Password:</label>


<input type="password" id="confirm_password" name="confirm_password"><br>

<label for="dob">Date of Birth:</label>


<input type="date" id="dob" name="dob"><br>
39
………….. …………..

<label for="gender">Gender:</label>
<select id="gender" name="gender">
<option value="">Select Gender</option>
<option value="male">Male</option>
<option value="female">Female</option>
<option value="other">Other</option>
</select><br>

<label for="country">Country:</label>
<select id="country" name="country">
<option value="">Select Country</option>
<option value="india">India</option>
<option value="usa">USA</option>
<option value="uk">UK</option>
<option value="canada">Canada</option>
<option value="australia">Australia</option>
</select><br><br>

<input type="submit" value="Register">


</form>
</body>
</html>
40
………….. …………..

style.css

body {

display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
background-color: #f2f2f2;
}/*
form {
width: 400px;
padding: 20px;
border: 1px solid #ccc;
background-color: #fff;
border-radius: 8px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
input[type="text"],
input[type="email"],
input[type="password"],
select {
width: calc(100% - 12px);
padding: 6px;
margin: 6px 0;
border: 1px solid #ccc;
border-radius: 4px;
41
………….. …………..

}*/
input[type="submit"] {
width: 100%;
padding: 10px;
margin-top: 10px;
background-color: #007bff;
color: #fff;
border: none;
border-radius: 4px;
cursor: pointer;
}
input[type="submit"]:hover
{ background-color:
#0056b3;
}

Registration.jsp

<%@page import="java.text.ParseException"%>
<%@page import="java.util.Date"%>
<%@page import="java.text.SimpleDateFormat"%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>User Registration using JSP</title>
</head>
<%-- Method to format date of birth --%>
<%!
42
………….. …………..

private String formatDateOfBirth(String dob)


{ try {
//Assuming dob is in yyyy-MM-dd format
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date = sdf.parse(dob);
sdf.applyPattern("dd/MM/yyyy");
return sdf.format(date);
} catch (ParseException e)
{ return dob;
}
}
%>
<body>
<h2>User Registration Result</h2>
<%
//Retrieving form field values from request parameters
String username = request.getParameter("username");
String name = request.getParameter("name");
String email = request.getParameter("email");
String password = request.getParameter("password");
String dob = request.getParameter("dob");
String gender = request.getParameter("gender");
String country = request.getParameter("country");
%>
<p><b>Username: </b><%= username %></p>
<p><b>Name: </b> <%= name %></p>
<p><b>Email: </b> <%= email %></p>
43
………….. …………..

<p><b>Date of Birth: </b> <%= formatDateOfBirth(dob) %></p>


<p><b>Gender: </b><%= gender %></p>
<p><b>Country: </b><%= country %></p>
</body>
</html>
44
………….. …………..

OUTPUT
45
………….. …………..

11. Create a user database for the user registration page and insert data into user
table using JDBC when submitting the registration page.

MySQL Database:

create database imcab6db;


use imcab6db;
CREATE TABLE `user` (
`id` INT NOT NULL AUTO_INCREMENT,
`username` VARCHAR(50) NOT NULL,
`name` VARCHAR(100) NOT NULL,
`email` VARCHAR(100) NOT NULL,
`password` VARCHAR(100) NOT NULL,
`dob` DATE NOT NULL,
`gender` ENUM('Male', 'Female', 'Other') NOT NULL,
`country` VARCHAR(50) NOT NULL,
PRIMARY KEY (`id`)
);

Index.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>User Registration</title>
</head>
<body>
<h2>User Registration</h2>
<ul>
<li><a href="registration.html">Register</a></li>
</ul>
</body>
</html>
46
………….. …………..

registration.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>User Registration</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script>
function validateForm(form) {
var username = document.getElementById("username").value;
var email = document.getElementById("email").value;
var password = document.getElementById("password").value;
var confirm_password = document.getElementById("confirm_password").value;
var dob = document.getElementById("dob").value;
var gender = document.getElementById("gender").value;
var country = document.getElementById("country").value;

// Check if any field is empty


if (username === "" || email === "" || password === "" || dob === "" ||
gender === "" || country === "") {
alert("All fields are required");
return false;
}

// Check if password matches confirm password


if (password !== confirm_password) {
alert("Password and confirm password do not match");
return false;
}

// Validation successful
alert("All validations successful");
return true;
}
</script>
47
………….. …………..

</head>
<body>
<form action="registration.jsp" method="post" onsubmit="return validateForm()">
<a href="/pgm19 "><img src="logo-store.JPG" alt="Home"></a>
<h2>User Registration</h2>
<label for="username">Username:</label>
<input type="text" id="username" name="username"><br>

<label for="name">Name:</label>
<input type="text" id="name" name="name"><br>

<label for="email">Email:</label>
<input type="email" id="email" name="email"><br>

<label for="password">Password:</label>
<input type="password" id="password" name="password"><br>

<label for="confirm_password">Confirm Password:</label>


<input type="password" id="confirm_password" name="confirm_password"><br>

<label for="dob">Date of Birth:</label>


<input type="date" id="dob" name="dob"><br>

<label for="gender">Gender:</label>
<select id="gender" name="gender">
<option value="">Select Gender</option>
<option value="male">Male</option>
<option value="female">Female</option>
<option value="other">Other</option>
</select><br>

<label for="country">Country:</label>
<select id="country" name="country">
<option value="">Select Country</option>
48
………….. …………..

<option value="india">India</option>
<option value="usa">USA</option>
<option value="uk">UK</option>
<option value="canada">Canada</option>
<option value="australia">Australia</option>
</select><br><br>

<input type="submit" value="Register">


</form>
</body>
</html>

registration.jsp

<%@page import="java.sql.Date"%>
<%@page import="java.sql.DriverManager"%>
<%@page import="java.sql.PreparedStatement"%>
<%@page import="java.sql.Connection"%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Insert Data into User Table</title>
</head>
<body>
<h2>User Registration Result</h2>
<%
//Retrieving form field values from request parameters
String username = request.getParameter("username");
String name = request.getParameter("name");
String email = request.getParameter("email");
String password = request.getParameter("password");
String dob = request.getParameter("dob");
String gender = request.getParameter("gender");
String country = request.getParameter("country");
%>
<p><b>Username: </b><%= username %></p>
<p><b>Name: </b> <%= name %></p>
<p><b>Email: </b> <%= email %></p>
<p><b>Date of Birth: </b> <%= dob %></p>
49
………….. …………..

<p><b>Gender: </b><%= gender %></p>


<p><b>Country: </b><%= country %></p>

<h2>Insert Data into User Table</h2>

<%
Connection conn = null;
PreparedStatement pstmt = null;

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

//Define connection URL with necessary connection parameters


String url = "jdbc:mysql://localhost:3306/imcadb6";
String db_username = "root";
String db_password = "root";

//Establish a connection to the MySQL database


conn = DriverManager.getConnection(url, db_username, db_password);

//Prepare the SQL statement for insertion


String sql = "INSERT INTO user (username, name, email, password, dob,
gender, country) VALUES (?, ?, ?, ?, ?, ?, ?)";
pstmt = conn.prepareStatement(sql);

//Set values for the parameters in the SQL statement


pstmt.setString(1, username);
pstmt.setString(2, name);
pstmt.setString(3, email);
pstmt.setString(4, password);
pstmt.setDate(5, Date.valueOf(dob)); // Assuming date format is YYYY-MM-DD
pstmt.setString(6, gender); // Assuming gender
pstmt.setString(7, country);

//Execute the SQL statement


int rowsAffected = pstmt.executeUpdate();

out.println("<p>" + rowsAffected + " row(s) inserted successfully.</p>");


50
………….. …………..

} catch (Exception e) {
out.println("<p>Exception: " + e.getMessage() + "</p>");
} finally {
// Close the connection and release resources
try {
if (pstmt != null) pstmt.close();
if (conn != null) conn.close();
} catch (Exception e) {
out.println("<p>Exception: " + e.getMessage() + "</p>");
}
}
%>

</body>
</html>
51
………….. …………..

OUTPUT
52
………….. …………..

index.html

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>User Registration</title>

</head>

<body>

<h2>User Registration</h2>

<ul>

<li><a href="registration.html">Register</a></li>

</ul>

</body>

</html>

registration.html

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>User Registration</title>

<link rel="stylesheet" type="text/css" href="style.css">


53
………….. …………..
<script>

function validateForm(form) {

var username = document.getElementById("username").value;

var email = document.getElementById("email").value;

var password = document.getElementById("password").value;

var confirm_password = document.getElementById("confirm_password").value;

var dob = document.getElementById("dob").value;

var gender = document.getElementById("gender").value;

var country = document.getElementById("country").value;

// Check if any field is empty

if (username === "" || email === "" || password === "" || dob === "" || gender === "" || country === "") {

alert("All fields are required");

return false;

// Check if password matches confirm password

if (password !== confirm_password) {

alert("Password and confirm password do not match");

return false;

// Validation successful

alert("All validations successful");

return true;

</script>
54
………….. …………..

</head>

<body>

<form action="registration.jsp" method="post" onsubmit="return validateForm()">

<a href="/pgm17-jsp-jdbc"><img src="logo-store.JPG" alt="Home"></a>

<h2>User Registration</h2>

<label for="username">Username:</label>

<input type="text" id="username" name="username"><br>

<label for="name">Name:</label>

<input type="text" id="name" name="name"><br>

<label for="email">Email:</label>

<input type="email" id="email" name="email"><br>

<label for="password">Password:</label>

<input type="password" id="password" name="password"><br>

<label for="confirm_password">Confirm Password:</label>

<input type="password" id="confirm_password" name="confirm_password"><br>

<label for="dob">Date of Birth:</label>

<input type="date" id="dob" name="dob"><br>

<label for="gender">Gender:</label>

<select id="gender" name="gender">

<option value="">Select Gender</option>

<option value="male">Male</option>

<option value="female">Female</option>

<option value="other">Other</option>
55
………….. …………..

</select><br>

<label for="country">Country:</label>

<select id="country" name="country">

<option value="">Select Country</option>

<option value="india">India</option>

<option value="usa">USA</option>

<option value="uk">UK</option>

<option value="canada">Canada</option>

<option value="australia">Australia</option>

</select><br><br>

<input type="submit" value="Register">

</form>

<button onclick="window.location.href='select.jsp'">View All</button>

</body>

</html>
56
………….. …………..

registration.jsp

<%@page import="java.sql.Date"%>

<%@page import="java.sql.DriverManager"%>

<%@page import="java.sql.PreparedStatement"%>

<%@page import="java.sql.Connection"%>

<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<html>

<head>

<title>Insert Data into User Table</title>

</head>

<body>

<h2>User Registration Result</h2>

<%

//Retrieving form field values from request parameters

String username = request.getParameter("username");

String name = request.getParameter("name");

String email = request.getParameter("email");

String password = request.getParameter("password");

String dob = request.getParameter("dob");

String gender = request.getParameter("gender");

String country = request.getParameter("country");

%>

<p><b>Username: </b><%= username %></p>

<p><b>Name: </b> <%= name %></p>

<p><b>Email: </b> <%= email %></p>

<p><b>Date of Birth: </b> <%= dob %></p>


57
………….. …………..
<p><b>Gender: </b><%= gender %></p>

<p><b>Country: </b><%= country %></p>

<h2>Insert Data into User Table</h2>


<%

Connection conn = null;

PreparedStatement pstmt = null;

try {

//Load the MySQL JDBC driver

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

//Define connection URL with necessary connection parameters

String url = "jdbc:mysql://localhost:3306/imcab6db";

String db_username = "root";

String db_password = "windows";

//Establish a connection to the MySQL database

conn = DriverManager.getConnection(url, db_username, db_password);

//Prepare the SQL statement for insertion

String sql = "INSERT INTO user (username, name, email, password, dob, gender, country) VALUES
(?, ?, ?, ?, ?, ?, ?)";

pstmt = conn.prepareStatement(sql)

//Set values for the parameters in the SQL statement

pstmt.setString(1, username);

pstmt.setString(2, name);

pstmt.setString(3, email);

pstmt.setString(4, password);

pstmt.setDate(5, Date.valueOf(dob)); // Assuming date format is YYYY-MM-DD

pstmt.setString(6, gender); // Assuming gender

pstmt.setString(7, country);

//Execute the SQL statement


58
………….. …………..

int rowsAffected = pstmt.executeUpdate();

out.println("<p>" + rowsAffected + " row(s) inserted successfully.</p>");

} catch (Exception e) {

out.println("<p>Exception: " + e.getMessage() + "</p>");

} finally {

// Close the connection and release resources

try {

if (pstmt != null) pstmt.close();

if (conn != null) conn.close();

} catch (Exception e) {

out.println("<p>Exception: " + e.getMessage() + "</p>");

%>

</body>

</html>
59
………….. …………..

select.jsp

<%@page import="java.sql.ResultSet"%>

<%@page import="java.sql.Statement"%>

<%@page import="java.sql.DriverManager"%>

<%@page import="java.sql.Connection"%>

<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<html>

<head>

<title>Retrieve Data from User Table</title>

</head>

<body>

<h2>Retrieve Data from User Table</h2>

<%

Connection conn = null;

Statement stmt = null;

ResultSet rs = null;

try {

//Load the MySQL JDBC driver

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

//Define connection URL with necessary connection parameters

String url = "jdbc:mysql://localhost:3306/imcab6db"; // Updated database name

String db_username = "root";

String db_password = "windows";


60
………….. …………..

//Establish a connection to the MySQL database

conn = DriverManager.getConnection(url, db_username, db_password);

//Create a SQL statement for selecting data

stmt = conn.createStatement();

String sql = "SELECT * FROM user";

//Execute the SQL statement

rs = stmt.executeQuery(sql);

%>

<table border="1">

<tr>

<th>Username</th>

<th>Name</th>

<th>Email</th>

<th>Date of Birth</th>

<th>Gender</th>

<th>Country</th>

</tr>

<% while (rs.next()) { %>

<tr>

<td><%= rs.getString("username") %></td>

<td><%= rs.getString("name") %></td>

<td><%= rs.getString("email") %></td>


61
………….. …………..
<td><%= rs.getDate("dob") %></td>

<td><%= rs.getString("gender") %></td>

<td><%= rs.getString("country") %></td>

</tr>

<% } %>

</table>

<%

} catch (Exception e) {

out.println("<p>Exception: " + e.getMessage() + "</p>");

} finally {

// Close the connection and release resources

try {

if (rs != null) rs.close();

if (stmt != null) stmt.close();

if (conn != null) conn.close();

} catch (Exception e) {

out.println("<p>Exception: " + e.getMessage() + "</p>");

%>

</body>

</html>

You might also like