0% found this document useful (0 votes)
8 views45 pages

Advanced Java Programming Lab Guide

The document outlines a lab manual for an Advanced Java Programming course, detailing various experiments related to Java programming concepts such as socket programming, applet programming, multi-threading, and Java Beans. Each experiment includes an aim, theory, code examples, and expected outputs. The manual is structured with an index and is intended for students in the Department of Computer Science and Engineering.

Uploaded by

Chudel pikachu
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views45 pages

Advanced Java Programming Lab Guide

The document outlines a lab manual for an Advanced Java Programming course, detailing various experiments related to Java programming concepts such as socket programming, applet programming, multi-threading, and Java Beans. Each experiment includes an aim, theory, code examples, and expected outputs. The manual is structured with an index and is intended for students in the Department of Computer Science and Engineering.

Uploaded by

Chudel pikachu
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

DR.

AKHILESH DAS GUPTA INSTITUTE OF


PROFESSIONAL STUDIES

ADVANCE JAVA PROGRAMMING LAB


(CIE-306P)

DEPARTMENT OF COMPUTER SCIENCE &


ENGINEERING

Submitted To: Submitted By:


Mr. Faisal Rais Aman Malik
Assistant Professor 03315602722
Department of CSE CSE T1
INDEX

[Link] EXPERIMENT NAME Page DATE OF DATE OF SIGNATURE


No. PERFOMANCE CHECKING / REMARKS
1 Write a Java program to
demonstrate the concept 1-4 13/02/2025 27/02/2025
of socket programming
2 Write a Java program to
demonstrate the concept 5-7 27/02/2025 20/03/2025
of applet programming
3 Write a Java program to
demonstrate the concept 8-10 20/03/2025 27/03/2025
of multi-threading
4 Write a Java program to
implement multiple 11-14 27/03/2025 03/04/2025
inheritance using
interface.
5 Write a Java program to
demonstrate the use of 15-18 03/04/2025 17/04/2025
Java Beans
6 Write a Java program to
insert data into a table 19-22 03/04/2025 17/04/2025
using JSP
7 Write JSP program to
implement form data 23-27 17/04/2025 24/04/2025
validation
8 Write a Java program to
show user validation 28-31 17/04/2025 24/04/2025
using Servlet
9 Write a program to set
cookie information using 32-36 24/04/2025 28/04/2025
Servlet
10 Develop a small web
program using Servlets, 37-43 24/04/2025 28/04/2025
JSPs with Database
connectivity
EXPERIMENT -1

AIM :- Write a Java program to demonstrate the concept of socket


programming.

THEORY :
Socket programming enables communication between two machines over a
network. It is a fundamental concept in networking, allowing applications to
exchange data using TCP (Transmission Control Protocol) or UDP (User
Datagram Protocol).

CODE :

1. Server Program (Java TCP Server)


import [Link].*;

import [Link].*;

public class Server {

public static void main(String[] args) {

int port = 5000; // Define port number

try {

ServerSocket serverSocket = new ServerSocket(port);

[Link]("Server is running... Waiting for client connection.");

Socket socket = [Link](); // Accept client connection

[Link]("Client connected!");

// Read message from client

BufferedReader input = new BufferedReader(new


InputStreamReader([Link]()));

String clientMessage = [Link]();

[Link]("Client says: " + clientMessage);

Name : Aman Malik pg. 1 Enroll No. :03315602722


// Send response to client

PrintWriter output = new PrintWriter([Link](), true);

[Link]("Hello Client! Message received.");

// Close resources

[Link]();

[Link]();

[Link]();

[Link]();

} catch (IOException e) {

[Link]();

2. Client Program (Java TCP Client)


import [Link].*;

import [Link].*;

import [Link].*;

public class Client {

public static void main(String[] args) {

String serverAddress = "localhost"; // Change if server is on a different machine

int port = 5000; // Port number

try {

Socket socket = new Socket(serverAddress, port);

[Link]("Connected to server.");

Name : Aman Malik pg. 2 Enroll No. :03315602722


// Send message to server

PrintWriter output = new PrintWriter([Link](), true);

[Link]("Hello Server!");

// Receive response from server

BufferedReader input = new BufferedReader(new


InputStreamReader([Link]()));

String serverMessage = [Link]();

[Link]("Server says: " + serverMessage);

// Close resources

[Link]();

[Link]();

[Link]();

} catch (IOException e) {

[Link]();

Name : Aman Malik pg. 3 Enroll No. :03315602722


OUTPUT :

Name : Aman Malik pg. 4 Enroll No. :03315602722


EXPERIMENT -2

AIM :- Write a Java program to demonstrate the concept of applet


programming.

THEORY :
An applet is a small Java program that runs within a web browser or an applet
viewer. Unlike standalone applications, applets do not have a main() method;
instead, they rely on predefined lifecycle methods provided by the Applet or
JApplet class..

CODE :

1. Java Applet Program


import [Link];

import [Link].*;

public class SimpleApplet extends Applet {

public void init() {

setBackground([Link]);

public void paint(Graphics g) {

for (int i = 0; i < getHeight(); i++) {

int seed = (int) (255 - (i / (double) getHeight()));

[Link](new Color(seed, 0, 255 - seed));

[Link](0, i, getWidth(), 1);

Name : Aman Malik pg. 5 Enroll No. :03315602722


Font titleFont = new Font("Serif", [Link], 24);

Font textFont = new Font("SansSerif", [Link], 18);

[Link](titleFont);

[Link]([Link]);

[Link]("Welcome to Java Applet!", 50, 50);

[Link]([Link]);

[Link](new Font("Monospaced", [Link], 16));

[Link]("Applets are now outdated, but still fun!", 50, 80);

2. HTML Code for Running Applet


<html>
<body>
<applet code="[Link]" width="300" height="200">
</applet>
</body>
</html>

Name : Aman Malik pg. 6 Enroll No. :03315602722


OUTPUT :

Name : Aman Malik pg. 7 Enroll No. :03315602722


EXPERIMENT -3

AIM :- Write a Java program to demonstrate the concept of applet


programming.

THEORY :
Multi-threading is a Java feature that allows concurrent execution of two or
more parts of a program. Each part is called a thread, and each thread runs in
parallel, improving the performance of applications.
Java provides two ways to create threads:
1. Extending the Thread class.
2. Implementing the Runnable interface.

CODE :
// Using Thread class

class MyThread extends Thread {

public void run() {

for (int i = 0; i < 5; i++) {

[Link]([Link]().getName() + " - Count: " + i);

try {

[Link](500); // Pause for 500ms

} catch (InterruptedException e) {

[Link](e);

Name : Aman Malik pg. 8 Enroll No. :03315602722


// Using Runnable interface

class MyRunnable implements Runnable {

public void run() {

for (int i = 0; i < 5; i++) {

[Link]([Link]().getName() + " - Count: " + i);

try {

[Link](500);

} catch (InterruptedException e) {

[Link](e);

}}}

public class MultiThreadingDemo {

public static void main(String[] args) {

// Creating threads using Thread class

MyThread thread1 = new MyThread();

MyThread thread2 = new MyThread();

// Creating threads using Runnable interface

Thread thread3 = new Thread(new MyRunnable());

Thread thread4 = new Thread(new MyRunnable());

// Start the threads

[Link]();

[Link]();

[Link]();

[Link]();

Name : Aman Malik pg. 9 Enroll No. :03315602722


OUTPUT :

Name : Aman Malik pg. 10 Enroll No. :03315602722


EXPERIMENT -4

AIM :- Write a Java program to implement multiple inheritance using


interface.

THEORY :
Java does not support multiple inheritance through classes to avoid ambiguity.
However, it allows multiple inheritance using interfaces. Interfaces contain
abstract methods that must be implemented by classes. A class can implement
multiple interfaces, thus inheriting their behaviours and achieving multiple
inheritance.

CODE :
// First interface: Animal behavior

interface Animal {

void eat();

void sleep();

// Second interface: Bird behavior

interface Bird {

void fly();

void layEggs();

// Third interface: Mammal behavior

interface Mammal {

void giveBirth();

Name : Aman Malik pg. 11 Enroll No. :03315602722


// Class implementing multiple interfaces

class Bat implements Animal, Bird, Mammal {

@Override

public void eat() {

[Link]("Bat eats insects and fruits.");

@Override

public void sleep() {

[Link]("Bat sleeps during the day (nocturnal).");

@Override

public void fly() {

[Link]("Bat flies using its wings.");

@Override

public void layEggs() {

[Link]("Bats do not lay eggs; they give birth to live young.");

@Override

public void giveBirth() {

[Link]("Bat gives birth to live offspring.");

// Additional method

public void useEcholocation() {

[Link]("Bat uses echolocation to navigate in the dark.");

Name : Aman Malik pg. 12 Enroll No. :03315602722


}

// Main class to test the program

public class MultipleInheritanceExample {

public static void main(String[] args) {

Bat myBat = new Bat();

// Calling inherited methods

[Link]("Bat Characteristics:");

[Link]();

[Link]();

[Link]();

[Link]();

[Link]();

[Link](); // Bat-specific method

Name : Aman Malik pg. 13 Enroll No. :03315602722


OUTPUT :

Name : Aman Malik pg. 14 Enroll No. :03315602722


EXPERIMENT -5

AIM :- Write a Java program to demonstrate the concept of applet


programming.

THEORY :
Java Beans are reusable software components that follow specific conventions
and can be easily integrated into various applications. A Java Bean must meet
the following requirements:
1. Encapsulation: All properties are private, accessed via getter and setter
methods.
2. Default Constructor: A no-argument constructor should be provided.
3. Serializable: The class must implement the Serializable interface to
allow object persistence.
4. Public Getter and Setter Methods: These methods allow controlled
access to private fields.

CODE :
import [Link];

// Java Bean Class

class EmployeeBean implements Serializable {

private static final long serialVersionUID = 1L; // Serializable version ID

private String name;

private int age;

private double salary;

// Default Constructor

public EmployeeBean() {

Name : Aman Malik pg. 15 Enroll No. :03315602722


// Parameterized Constructor

public EmployeeBean(String name, int age, double salary) {

[Link] = name;

[Link] = age;

[Link] = salary;

// Getter and Setter Methods

public String getName() {

return name;

public void setName(String name) {

[Link] = name;

public int getAge() {

return age;

public void setAge(int age) {

[Link] = age;

public double getSalary() {

return salary;

public void setSalary(double salary) {

[Link] = salary;

Name : Aman Malik pg. 16 Enroll No. :03315602722


// Main Class to Demonstrate Java Bean

public class JavaBeanDemo {

public static void main(String[] args) {

// Creating Java Bean objects

EmployeeBean emp1 = new EmployeeBean();

[Link]("Aman Malik");

[Link](21);

[Link](5000000.0);

EmployeeBean emp2 = new EmployeeBean("Abhinav Mishra", 20, 4000000.0);

// New Employee Entry

EmployeeBean emp3 = new EmployeeBean("Aditya Tiwari", 21, 3000000.0);

// Displaying Employee Details

[Link]("Employee 1 Details:");

[Link]("Name: " + [Link]());

[Link]("Age: " + [Link]());

[Link]("Salary: " + [Link]());

[Link]("\nEmployee 2 Details:");

[Link]("Name: " + [Link]());

[Link]("Age: " + [Link]());

[Link]("Salary: " + [Link]());

[Link]("\nEmployee 3 Details:");

[Link]("Name: " + [Link]());

[Link]("Age: " + [Link]());

[Link]("Salary: " + [Link]());

Name : Aman Malik pg. 17 Enroll No. :03315602722


OUTPUT :

Name : Aman Malik pg. 18 Enroll No. :03315602722


EXPERIMENT -6

AIM :- Write a Java program to insert data into a table using JSP.

THEORY :
JSP (Java Server Pages) is a server-side technology that enables developers to
create dynamic web pages using Java. To insert data into a database, JSP works
with JDBC (Java Database Connectivity), which allows Java applications to
interact with databases.

CODE :

1. JSP Program
<%@ page import="[Link].*" %>

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

<!DOCTYPE html>

<html>

<head>

<title>User Registration</title>

</head>

<body>

<h2>User Registration</h2>

<form action="[Link]" method="post">

Name: <input type="text" name="name" required><br><br>

Email: <input type="email" name="email" required><br><br>

Password: <input type="password" name="password" required><br><br>

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

</form>

<br>

Name : Aman Malik pg. 19 Enroll No. :03315602722


<div>

<%

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

String user = "root";

String password = "NewSecurePassword123";

Connection conn = null;

PreparedStatement pstmt = null;

if ([Link]().equalsIgnoreCase("POST")) {

String name = [Link]("name");

String email = [Link]("email");

String pass = [Link]("password");

try {

[Link]("[Link]");

conn = [Link](url, user, password);

String sql = "INSERT INTO users (name, email, password) VALUES (?, ?, ?)";

pstmt = [Link](sql);

[Link](1, name);

[Link](2, email);

[Link](3, pass);

int rowsInserted = [Link]();

if (rowsInserted > 0) {

[Link]("<p style='color: green; font-weight: bold;'>" + name + "


registered successfully!</p>");

} else {

[Link]("<p style='color: red; font-weight: bold;'>Registration failed.


Try again.</p>");

Name : Aman Malik pg. 20 Enroll No. :03315602722


}

} catch (Exception e) {

[Link]("<p style='color: red; font-weight: bold;'>Error: " +


[Link]() + "</p>");

} finally {

if (pstmt != null) [Link]();

if (conn != null) [Link]();

%>

</div>

</body>

</html>

2. MySql Query to create database and table


Create database mydb;

use mydb;

CREATE TABLE users (

id INT AUTO_INCREMENT PRIMARY KEY,

name VARCHAR(100),

email VARCHAR(100) UNIQUE,

password VARCHAR(255)

);

Name : Aman Malik pg. 21 Enroll No. :03315602722


OUTPUT :

Name : Aman Malik pg. 22 Enroll No. :03315602722


EXPERIMENT -7

AIM :- Write JSP program to implement form data validation.

THEORY :
Java Server Pages (JSP) is a server-side technology used for creating dynamic
web applications. Form validation in JSP ensures that user inputs are checked
before processing them on the server. Validation can be performed in two ways:
1. Client-Side Validation: Using JavaScript to validate form fields before
submission.
2. Server-Side Validation: Using JSP to check for valid input after form
submission.

CODE :

1. HTML Form ([Link])


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

<!DOCTYPE html>

<html>

<head>

<title>Form Validation in JSP</title>

</head>

<body>

<h2>Registration Form</h2>

<form action="[Link]" method="post">

Name: <input type="text" name="name"><br><br>

Email: <input type="text" name="email"><br><br>

Password: <input type="password" name="password"><br><br>

Name : Aman Malik pg. 23 Enroll No. :03315602722


Age: <input type="text" name="age"><br><br>

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

</form>

</body>

</html>

2. Server-Side Validation ([Link])


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

<%@ page import="[Link].*" %>

<!DOCTYPE html>

<html>

<head>

<title>Validation Result</title>

</head>

<body>

<h2>Validation Results</h2>

<%

String name = [Link]("name");

String email = [Link]("email");

String password = [Link]("password");

String ageStr = [Link]("age");

int age = 0;

boolean hasErrors = false;

String errorMsg = "";

Name : Aman Malik pg. 24 Enroll No. :03315602722


// Name Validation

if (name == null || [Link]().isEmpty()) {

errorMsg += "Name is required.<br>";

hasErrors = true;

// Email Validation

String emailRegex = "^[A-Za-z0-9+_.-]+@(.+)$";

Pattern emailPattern = [Link](emailRegex);

Matcher emailMatcher = [Link](email);

if (email == null || ![Link]()) {

errorMsg += "Invalid email format.<br>";

hasErrors = true;

// Password Validation

if (password == null || [Link]() < 6) {

errorMsg += "Password must be at least 6 characters long.<br>";

hasErrors = true;

// Age Validation

try {

age = [Link](ageStr);

if (age <= 0) {

Name : Aman Malik pg. 25 Enroll No. :03315602722


errorMsg += "Age must be a positive number.<br>";

hasErrors = true;

} catch (NumberFormatException e) {

errorMsg += "Age must be a valid number.<br>";

hasErrors = true;

// Display Errors or Success Message

if (hasErrors) {

[Link]("<p style='color:red;'>" + errorMsg + "</p>");

[Link]("<a href='[Link]'>Go Back</a>");

} else {

[Link]("<p style='color:green;'>Form submitted successfully!</p>");

[Link]("<p>Name: " + name + "</p>");

[Link]("<p>Email: " + email + "</p>");

[Link]("<p>Age: " + age + "</p>");

%>

</body>

</html>

Name : Aman Malik pg. 26 Enroll No. :03315602722


OUTPUT :

Name : Aman Malik pg. 27 Enroll No. :03315602722


EXPERIMENT -8

AIM :- Write a Java program to show user validation using Servlet.

THEORY :
Servlets are server-side Java programs that handle client requests and generate
dynamic responses. In this program, we use:
1. HTML form: Allows users to enter a username and password.
2. Servlet ([Link]): Processes the login request, validates
credentials, and responds accordingly.
3. Deployment descriptor ([Link]): Maps the servlet to a URL pattern.
The servlet receives form data via HTTP POST, validates it against predefined
credentials (or a database), and redirects the user to either a success or error
page.

CODE :

1. Validation code ([Link])


import [Link].*;

import [Link].*;

import [Link].*;

public class ValidateServlet extends HttpServlet {

protected void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

String username = [Link]("username");

String password = [Link]("password");

String validUsername = "admin";

String validPassword = "password123";


[Link]("text/html");

Name : Aman Malik pg. 28 Enroll No. :03315602722


PrintWriter out = [Link]();

if ([Link](validUsername) && [Link](validPassword)) {

[Link]("<h2>Welcome, " + username + "!</h2>");

[Link]("<p>You have successfully logged in.</p>");

} else {

[Link]("<h2>Login Failed</h2>");

[Link]("<p>Invalid username or password. Please try again.</p>");

2. HTML Code ([Link])


<!DOCTYPE html>

<html>

<head>

<title>User Validation</title>

</head>

<body>

<h2>User Login</h2>

<form action="ValidateServlet" method="post">

Username: <input type="text" name="username" required><br><br>

Password: <input type="password" name="password" required><br><br>

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

</form>

</body>

</html>

Name : Aman Malik pg. 29 Enroll No. :03315602722


3. XML Code ([Link])
<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns="[Link]

xmlns:xsi="[Link]

xsi:schemaLocation="[Link]

[Link]

version="3.0">

<servlet>

<servlet-name>ValidateServlet</servlet-name>

<servlet-class>ValidateServlet</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>ValidateServlet</servlet-name>

<url-pattern>/ValidateServlet</url-pattern>

</servlet-mapping>

</web-app>

Name : Aman Malik pg. 30 Enroll No. :03315602722


OUTPUT :

Name : Aman Malik pg. 31 Enroll No. :03315602722


EXPERIMENT -9

AIM :- Write a program to set cookie information using Servlet

THEORY :
A cookie is a small piece of data that a web server sends to a client’s browser
and is stored on the client’s machine. The browser sends this data back to the
server in subsequent requests. In Java Servlets, cookies are handled using the
[Link] class.

CODE :

1. Set Cookie Servlet ([Link])


import [Link].*;

import [Link].*;

import [Link];

import [Link].*;

@WebServlet("/SetCookieServlet")

public class SetCookieServlet extends HttpServlet {

private static final long serialVersionUID = 1L;

protected void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

[Link]("text/html");

PrintWriter out = [Link]();

String username = [Link]("username");

Cookie userCookie = new Cookie("username", username);

[Link](60 * 60 * 24); // Cookie expiration set to 1 day

[Link](userCookie);

Name : Aman Malik pg. 32 Enroll No. :03315602722


[Link]("<h2>Cookie set successfully!</h2>");

[Link]("<a href='GetCookieServlet'>Go to Welcome Page</a>");

[Link]();

2. Get Cookie Servlet ([Link])


import [Link].*;

import [Link].*;

import [Link];

import [Link].*;

@WebServlet("/GetCookieServlet")

public class GetCookieServlet extends HttpServlet {

private static final long serialVersionUID = 1L;

protected void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

[Link]("text/html");

PrintWriter out = [Link]();

Cookie[] cookies = [Link]();

String username = null;

if (cookies != null) {

for (Cookie cookie : cookies) {

if ("username".equals([Link]())) {

username = [Link]();

break;

Name : Aman Malik pg. 33 Enroll No. :03315602722


}

if (username != null) {

[Link]("<h2>Welcome back, " + username + "!</h2>");

} else {

[Link]("<h2>No cookie found. Please set your name first.</h2>");

[Link]();

3. HTML Code ([Link])


<!DOCTYPE html>

<html>

<head>

<title>Set Cookie Example</title>

</head>

<body>

<h2>Enter Your Name</h2>

<form action="setCookieServlet" method="post">

<label>Name:</label>

<input type="text" name="username" required>

<br>

<br>

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

</form>

</body>

</html>

Name : Aman Malik pg. 34 Enroll No. :03315602722


4. XML Code ([Link])
<web-app xmlns="[Link] version="3.0">

<servlet>

<servlet-name>SetCookieServlet</servlet-name>

<servlet-class>SetCookieServlet</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>SetCookieServlet</servlet-name>

<url-pattern>/SetCookieServlet</url-pattern>

</servlet-mapping>

<servlet>

<servlet-name>GetCookieServlet</servlet-name>

<servlet-class>GetCookieServlet</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>GetCookieServlet</servlet-name>

<url-pattern>/GetCookieServlet</url-pattern>

</servlet-mapping>

</web-app>

Name : Aman Malik pg. 35 Enroll No. :03315602722


OUTPUT :

Name : Aman Malik pg. 36 Enroll No. :03315602722


EXPERIMENT -10

AIM :- Develop a small web program using Servlets, JSPs with Database
connectivity.

THEORY :
Java Servlets and JavaServer Pages (JSP) are essential technologies for
building dynamic web applications in Java EE.
• Servlets: Java programs that handle client requests and generate dynamic
web content. They run on a web server (Tomcat, GlassFish, etc.).
• JSP (JavaServer Pages): A technology used to create dynamic web
content with embedded Java code in HTML.
• JDBC (Java Database Connectivity): An API that connects Java
applications to databases like MySQL, PostgreSQL, etc.

CODE :

1. User Servlet ([Link])


import [Link].*;

import [Link].*;

import [Link].*;

import [Link].*;

import [Link].*;

import [Link].*;

@WebServlet("/UserServlet")

public class UserServlet extends HttpServlet {

private static final String URL = "jdbc:mysql://localhost:3306/user_db";

private static final String USER = "root";

private static final String PASSWORD = "123456";

Name : Aman Malik pg. 37 Enroll No. :03315602722


protected void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

String name = [Link]("name");

String email = [Link]("email");

try (Connection conn = [Link](URL, USER, PASSWORD);

PreparedStatement stmt = [Link]("INSERT INTO users


(name, email) VALUES (?, ?)")) {

[Link](1, name);

[Link](2, email);

[Link]();

} catch (Exception e) {

[Link]();

[Link]("UserServlet");

protected void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

List<String[]> users = new ArrayList<>();

try (Connection conn = [Link](URL, USER, PASSWORD);

PreparedStatement stmt = [Link]("SELECT * FROM users");

ResultSet rs = [Link]()) {

while ([Link]()) {

[Link](new String[] {

[Link]("name"),

[Link]("email")

});

Name : Aman Malik pg. 38 Enroll No. :03315602722


} catch (Exception e) {

[Link]();

[Link]("users", users);

RequestDispatcher dispatcher = [Link]("[Link]");

[Link](request, response);

2. JSP Code ([Link])


<%@ page language="java" import="[Link].*" %>

<!DOCTYPE html>

<html>

<head>

<title>User Registration</title>

</head>

<body>

<h2>Register User</h2>

<form action="UserServlet" method="post">

Name: <input type="text" name="name"><br>

Email: <input type="email" name="email"><br>

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

</form>

<h2>Registered Users</h2>

<table border="1">

Name : Aman Malik pg. 39 Enroll No. :03315602722


<tr>

<th>Name</th>

<th>Email</th>

</tr>

<%

List<String[]> users = (List<String[]>) [Link]("users");

if (users != null) {

for (String[] user : users) {

%>

<tr>

<td><%= user[0] %></td>

<td><%= user[1] %></td>

</tr>

<%

%>

</table>

</body>

</html>

Name : Aman Malik pg. 40 Enroll No. :03315602722


3. XML Code ([Link])
<web-app xmlns="[Link] version="3.0">

<servlet>

<servlet-name>UserServlet</servlet-name>

<servlet-class>UserServlet</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>UserServlet</servlet-name>

<url-pattern>/UserServlet</url-pattern>

</servlet-mapping>

<welcome-file-list>

<welcome-file>[Link]</welcome-file>

</welcome-file-list>

</web-app>

4. MySql Query (Create Database)


CREATE DATABASE user_db;

USE user_db;

CREATE TABLE users (

id INT AUTO_INCREMENT PRIMARY KEY,

name VARCHAR(100) NOT NULL,

email VARCHAR(100) UNIQUE NOT NULL

);

Name : Aman Malik pg. 41 Enroll No. :03315602722


OUTPUT :

Name : Aman Malik pg. 42 Enroll No. :03315602722


Name : Aman Malik pg. 43 Enroll No. :03315602722

You might also like