0% found this document useful (0 votes)
6 views53 pages

Advanced Java Programming Lab Report

The document is a certificate and practical report for a student enrolled in Advanced Java Programming at Sigma University. It outlines various practical assignments completed by the student, including applet development, GUI creation, and database applications. Each practical includes a description, code snippets, and expected outputs, demonstrating the student's proficiency in Java programming concepts.

Uploaded by

toxicraul01
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)
6 views53 pages

Advanced Java Programming Lab Report

The document is a certificate and practical report for a student enrolled in Advanced Java Programming at Sigma University. It outlines various practical assignments completed by the student, including applet development, GUI creation, and database applications. Each practical includes a description, code snippets, and expected outputs, demonstrating the student's proficiency in Java programming concepts.

Uploaded by

toxicraul01
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

Enrollment No: -23DIT0055 Advanced Java Programming

SIGMA UNIVERSITY

CERTIFICATE

THIS IS CERTIFY THAT MR./MS.

ENROLLMENT NO. OF BRANCH

HAS SATISFACTORILY COMPLETED THE LABORATORY WORK IN ADVANCED JAVA

PROGRAMMING WITHIN SIGMA UNIVERSITY ON DATE: -

BHUMI ATALIYA HOD KALYANI ADAWADKAR

1
Enrollment No: -23DIT0055 Advanced Java Programming

SIGMA UNIVERSITY (050)

Branch: Semester :

Subject Name: Subject Code :

[Link]. PRACTICAL NAME DATE SIGN

1 Develop an applet that draws a circle. The dimension of the


applet should be 500 x 300 pixels. The circle should be centered
in the applet and have a radius of 100 pixels. Display your name
centered in a circle.( using drawOval() method)

2 Draw ten red circles in a vertical column in the center of the


applet.

3 Built an applet that displays a horizontal rectangle in its center.


Let the rectangle fill with color from left to right.

4 Develop an applet that display the position of the mouse at


the upper left corner of the applet when it is dragged or
moved. Draw a 10x10 pixel rectangle filed with black at the
current mouse position

5 Develop an applet that uses the mouse listener, which overrides


only two methods which are mousePressed and mouseReleased.

6 Develop a program that has only one button in the frame, clicking
on the button cycles through the colors: red->green- >blue and so
on. One color changes per click.(use getBackGround() method to
get the current color)

2
Enrollment No: -23DIT0055 Advanced Java Programming

7 Develop an program that contains three check boxes and 30 x 30


pixel [Link] three checkboxes should be labeled “Red”,
“Green”,”Blue”. The selection of the check boxes determine the
color of the canvas. For example, if the user selects both “Red”
and “Blue”, the canvas should be purple.

8 Create an application that displays a frame with a menu bar.


When a user selects any menu or menu item, display that
selection on a text area in the center of the frame

9 Develop a program that draws two sets of ever-decreasing


rectangles one in outline form and one filled alternately in black
and white.

10 Develop a database application that uses any JDBC driver

11 Develop a Graphical User Interface that performs the following


SQL operations: a) Insert b) Delete c)Update.

12 Develop a program to present a set of choice for user to select a


product and display the price of product.

13 Develop a simple servlet program which maintains a counter for


the number of times it has been accessed since its loading,
initialize the counter using deployment descriptor.

14 Create a web form which processes servlet and demonstrates use


of cookies and sessions.

15 Develop a simple JSP program for user registration and then


control will be transfer it into second page.

16 Develop a simple JSP program for user login form with static and
dynamic database.

17 Develop a JSP program to display the grade of a student by


accepting the marks of five subjects.

Submitted by :

3
Enrollment No: -23DIT0055 Advanced Java Programming

Student Name : Enrollment No :

Submitted to :
Faculty Name : Bhumi Ataliya HOD Name : Kalyani Adawadkar

4
5
Enrollment No:23DIT0055 Advanced Java Programming

Practical-1

Aim :- Develop an applet that draws a circle. The dimension of the applet should be
500 x 300 pixels. The circle should be centered in the applet and have a radius of 100
pixels. Display your name centered in a circle.( using drawOval() method)

import [Link].*;
import
[Link].*;
public class CircleSwing extends
JPanel {
@Override public void
paintComponent(Graphics g) {
[Link](g);
int width =
1000; int
height = 1000;
int radius = 100;
// Calculate
center int
centerX = width / 5;
int centerY = height / 5;
// Draw circle
[Link](centerX - radius, centerY - radius, 2
* radius, 2 * radius);
// Draw name inside the circle
[Link](new Font("Arial", [Link], 16));
[Link]("Ansh", centerX - 35, centerY + 5); //
adjust for centering
} public static void main(String[] args)
{ JFrame frame = new JFrame("Centered
Circle"); CircleSwing panel = new
CircleSwing();
[Link](500,
300);

6
Enrollment No:23DIT0055 Advanced Java Programming

[Link](JFrame.EXIT_ON_CLOSE);
[Link](panel); [Link](true);
}
}

Output :

7
Enrollment No:23DIT0055 Advanced Java Programming

Practical-2

Aim :- Draw ten red circles in a vertical column in the center of the applet

import [Link].*;
import
[Link].*;
public class Circles extends
JPanel
{
@Override
public void paintComponent(Graphics g){
[Link](g);
[Link]([Link]); [Link](275, 50,
50, 50);
[Link]([Link]);
[Link](275, 105, 50, 50);
[Link]([Link]);
[Link](275, 160, 50, 50);
[Link]([Link]);
[Link](275, 215, 50, 50);
[Link]([Link]);
[Link](275, 270, 50, 50);
[Link]([Link]);
[Link](275, 325, 50, 50);
[Link]([Link]);
[Link](275, 380, 50, 50);
[Link]([Link]);
[Link](275, 434, 50, 50);
[Link]([Link]);
[Link](275, 490, 50, 50);
[Link]([Link]);
[Link](275, 545, 50, 50);
} public static void
main(String[] args) { Circles c =

8
Enrollment No:23DIT0055 Advanced Java Programming

new Circles(); JFrame f = new


JFrame();
[Link]("Extra");
[Link](600,400);
[Link](true);
[Link](JFrame.EXIT_ON_CLOSE);
[Link](c);
}
}

Output :

9
Enrollment No:23DIT0055 Advanced Java Programming

Practical-3

Aim :- Built an applet that displays a horizontal rectangle in its center. Let the rectangle
fill with color from left to right.

import [Link].*;
import
[Link].*;
public class Rectangle
extends JPanel { public
void paintComponent(Graphics
g){
[Link](g);
[Link]([Link]);
[Link](175, 100, 250, 100);
}
public static void main(String[] args) {
Rectangle r = new
Rectangle(); JFrame f = new
JFrame();
[Link]("Shapes");
[Link](400,600);
[Link](true);
[Link](JFrame.EXIT_ON_CLOSE);
[Link](r);
}
}
Output :

10
Enrollment No:23DIT0055 Advanced Java Programming

Practical-4

Aim : Develop an swing that display the position of the mouse at the upper left corner
of the applet when it is dragged or moved. Draw a 10x10 pixel rectangle filled with
black at the current mouse position.

import [Link].*; import


[Link].*;
import [Link].*;
public class MouseTracker extends
JFrame { private int mouseX = 0;
private int mouseY = 0;
public MouseTracker() { setTitle("Mouse
Tracker"); setSize(400, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
DrawingPanel panel = new DrawingPanel();
add(panel);

setVisible(true);
} class DrawingPanel extends
JPanel implements
MouseMotionListener {
public DrawingPanel() {
addMouseMotionListener(this);
}
@Override
protected void
paintComponent(Graphics g) {
[Link](g);
// Show mouse position at top-left
[Link]([Link]);
[Link]("Mouse at (" + mouseX + ", " + mouseY
+
")", 10, 20);
// Draw black 10x10 square at mouse position

11
Enrollment No:23DIT0055 Advanced Java Programming

[Link](mouseX, mouseY, 10, 10);


}
@Override
public void
mouseMoved(MouseEvent e) {
mouseX = [Link]();
mouseY = [Link]();
repaint();
}
@Override public
void mouseDragged(MouseEvent e)
{ mouseX =
[Link](); mouseY =
[Link]();
repaint();
}
} public static void
main(String[] args) {
[Link](MouseTracker::new);
}
}

Output :

12
Enrollment No:23DIT0055 Advanced Java Programming

Practical-5

Aim : Develop an swing that uses the mouse listener, which overrides only two
methods which are mousePressed and mouseReleased.

import [Link].*; import


[Link].*;

public class practical_5


{
public static void main(String args[]) {
JFrame frame = new JFrame("Pop-up Trigger Example");
[Link](400, 300);
[Link](JFrame.EXIT_ON_CLOSE);
JPopupMenu popupmenu = new JPopupMenu();
JMenuItem item1 = new JMenuItem("Option
1"); JMenuItem item2 = new
JMenuItem("Option 2");
[Link](item1); [Link](item2);
[Link](new MouseAdapter() {
public void mousePressed(MouseEvent e) {
showPopup(e); }
public void mouseReleased(MouseEvent e)
{ showPopup(e); }
private void showPopup(MouseEvent e) {
if ([Link]()) {
[Link]([Link](), [Link](),
[Link]());
}
}
});

[Link](true);
}
}

13
Enrollment No:23DIT0055 Advanced Java Programming

Output :

14
Enrollment No:23DIT0055 Advanced Java Programming

Practical-6

Aim : Develop a program that has only one button in the frame, clicking on the button
cycles through the colors: red->green- >blue and so on. One color changes per click.(use
getBackGround() method to get the current color)

import [Link].*; import


[Link].*;
import [Link].*;
public class
practical_6
{
public static void main(String args[])
{
JFrame frame=new JFrame("Practical-6");
[Link](400,300);
[Link](JFrame.EXIT_ON_CLOSE);
[Link](true); [Link](null);
[Link]().setBackground([Link]); JButton
button=new JButton("Change Color"); [Link](125, 125,
150, 20);
[Link](new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
Color c=[Link]().getBackground();
if([Link]([Link]))
{
[Link]().setBackground([Link]);
}
else if([Link]([Link]))
{
[Link]().setBackground([Link]);
} else
{

15
Enrollment No:23DIT0055 Advanced Java Programming

[Link]().setBackground([Link]);
}
}
});
[Link](button);
}
}
Output :

My Initial Page will be of color cyan

Then, when I press the button(Change Color) the panel changes it’s color to RED

Then if I again press the button the panel changes it’s color to GREEN

16
Enrollment No:23DIT0055 Advanced Java Programming

And if I press the button present on the panel for the third time it changes it’s color to
BLUE

But when I again press the button it changes panel’s color to RED as per our code.

17
Enrollment No:23DIT0055 Advanced Java Programming

Practical-7

Aim : Develop an program that contains three check boxes and 30 x 30 pixel
[Link] three checkboxes should be labeled “Red”, “Green”,”Blue”. The selection of
the check boxes determine the color of the canvas. For example, if the user selects both
“Red” and “Blue”, the canvas should be purple.

import [Link].*; import


[Link].*;
import [Link].*;
public class practical_7 extends
JPanel
{ public static void
main(String args[])
{

JFrame frame=new JFrame("Practical-7");


[Link](400,300);
[Link](JFrame.EXIT_ON_CLOSE)
; [Link](new FlowLayout());
JCheckBox red=new JCheckBox("Red");
JCheckBox blue=new JCheckBox("Blue");
JCheckBox green=new JCheckBox("Green");
JPanel panel=new JPanel();
[Link](new
Dimension(30,30));
[Link]([Link]);
ActionListener colorchange = e -> { int
redValue = [Link]() ? 255 : 0;
int greenValue = [Link]() ? 255
: 0; int blueValue = [Link]() ?
255 : 0;
[Link](new Color(redValue, greenValue,
blueValue));
};

18
Enrollment No:23DIT0055 Advanced Java Programming

[Link](colorchange);
[Link](colorchange);
[Link](colorchange);
[Link](red);
[Link](blue);
[Link](green);
[Link](panel);
[Link](true);
}
}

Output :

When I run the code the initial Frame that pops up will be as follows:

Then, If I select the Red checkbox the color RED appears on the preferred panel(30x30)

After that when I remove my selection of red and select on the blue checkbox the BLUE
color appears on the preferred panel

19
Enrollment No:23DIT0055 Advanced Java Programming

At last when I again remove my selection and go for the Green checkbox the GREEN
color will appear on the preferred panel.

After removing all my selection the preferred panel becomes BLACK as we have not set
the panel Background at the end.

From this you can select multiple checkbox and create new colors too, For Example:

20
Enrollment No:23DIT0055 Advanced Java Programming

21
Enrollment No:23DIT0055 Advanced Java Programming

Practical 8

Aim : Create an application that displays a frame with a menu bar. When a user selects
any menu or menu item, display that selection on a text area in the center of the frame.

import [Link].*; import


[Link].*;
import [Link].*;
public class Practical8 extends JFrame
implements
ActionListener { JLabel centerLabel;
Practical8() {
setTitle("Menu
Example");
setSize(400, 300);
setDefaultCloseOperation(EXIT_ON_CLOSE); setLayout(new
BorderLayout());

centerLabel = new JLabel("",


[Link]);
[Link](new Font("Arial", [Link],
18)); add(centerLabel,
[Link]);

JMenuBar bar = new JMenuBar();


JMenu file = new JMenu("File");
JMenu edit = new JMenu("Edit");
JMenu help = new JMenu("Help");
JMenuItem newItem = new JMenuItem("New");
JMenuItem openItem = new JMenuItem("Open");
JMenuItem exitItem = new JMenuItem("Exit");
JMenuItem cutItem = new JMenuItem("Cut");
JMenuItem copyItem = new JMenuItem("Copy");
JMenuItem pasteItem = new JMenuItem("Paste");
JMenuItem aboutItem = new JMenuItem("About");
[Link](newItem); [Link](openItem); [Link](exitItem);

22
Enrollment No:23DIT0055 Advanced Java Programming

[Link](cutItem); [Link](copyItem); [Link](pasteItem);


[Link](aboutItem);
[Link](file); [Link](edit);
[Link](help); setJMenuBar(bar);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](this);

setVisible(true);
} public void
actionPerformed(ActionEvent e) {
String cmd = [Link]();
if ([Link]("Exit")) [Link](0);
else [Link]("You selected: " +
cmd); } public static void
main(String[] args) { new
Practical8();
}
}

Output :

When User Selected Open in File menu

23
Enrollment No:23DIT0055 Advanced Java Programming

When User Selected Copy in Edit menu

When the user clicks Exit,


→ the application closes immediately

24
Enrollment No:23DIT0055 Advanced Java Programming

Practical 9

Aim : Develop a program that draws two sets of ever-decreasing rectangles — one in
outline form and one filled alternately in black and white.

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class Practical9 extends
JPanel {
@Override
protected void paintComponent(Graphics g) {
[Link](g);
int
x1 = 40;
int y1 = 40;
int width1 =
200;
int height1 =
120;
for (int i =
0; i < 5; i++)
{
[Link]([Link]);
[Link](x1, y1, width1, height1);
x1 += 10; y1 += 10; width1 -
= 20;
height1 -= 20;
} int x2 =
280; int y2 =
40; int width2 =
200; int
height2 = 120;
for (int i = 0; i < 5;
i++) { if

25
Enrollment No:23DIT0055 Advanced Java Programming

(i % 2 == 0) {
[Link]([Link]);
} else {
[Link]([Link]);
}
[Link](x2, y2, width2,
height2); x2 += 10;
y2 += 10; width2 -= 20;
height2 -= 20;
}
}
public static void main(String[] args) {
JFrame frame = new JFrame();
[Link](JFrame.EXIT_ON_CLO
SE);

Practical9 drawingPanel = new Practical9();


[Link](new Dimension(520, 200));

[Link](drawingPanel);
[Link]();
[Link](null);
[Link](true);
}
}
Output :

26
Enrollment No:23DIT0055 Advanced Java Programming

Practical 10

Aim : Develop a database application that uses any JDBC driver

import [Link].*;
class Practical_10 { public static
void main(String args[]) { try {
[Link]("[Link]");
Connection con =
[Link]("jdbc:mysql://localhost:3306/testdb
"
, "root", "root1234");
Statement st = [Link]();
[Link]("CREATE TABLE IF NOT EXISTS student(id
INT, name VARCHAR(30))");
[Link]("INSERT INTO student VALUES(1,'Ansh')");
ResultSet rs = [Link]("SELECT * FROM
student"); while ([Link]()) {
[Link]([Link](1) + " " +
[Link](2));
}

[Link]();
[Link]("Done");
} catch (Exception e) {
[Link](e);
}
}
}

Output :

27
Enrollment No:23DIT0055 Advanced Java Programming

28
Enrollment No:23DIT0055 Advanced Java Programming

Practical 11

Aim : Develop a Graphical User Interface that performs the following SQL
operations: a) Insert b) Delete c)Update.

import [Link].*; import


[Link].*; import
[Link].*; import
[Link].*; class
Practical_11 extends
JFrame implements
ActionListener {
JTextField t1, t2;
JButton b1, b2, b3;
Connection con;
Statement st;
Practical_11() {
setTitle("JDBC GUI
Example");
setSize(350, 200);
setLayout(new FlowLayout());
add(new
JLabel("ID:")); t1 =
new JTextField(10);
add(t1);
add(new
JLabel("Name:")); t2 =
new JTextField(10);
add(t2);
b1 = new
JButton("Insert"); b2 =
new JButton("Update");
b3 = new JButton("Delete");

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

29
Enrollment No:23DIT0055 Advanced Java Programming

[Link](this);
[Link](this);
[Link](this); try
{
[Link]("[Link]");
con =
[Link]("jdbc:mysql://localhost:3306/mydb",
"root", "root1234");
st = [Link]();
[Link]("CREATE TABLE IF NOT EXISTS student(id
INT PRIMARY
KEY, name VARCHAR(30))");
} catch (Exception e) {
[Link](e);
}
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
public void
actionPerformed(ActionEvent ae) {
try { int id =
[Link]([Link]());
String name = [Link]();
if ([Link]() ==
b1) {
[Link]("INSERT INTO student
VALUES(" + id + ",'" + name +
"')");
[Link](this, "Record
Inserted");
} else if ([Link]() == b2) {
[Link]("UPDATE student SET name='" + name + "' WHERE
id=" + id);
[Link](this, "Record
Updated");
} else if ([Link]() == b3) {
[Link]("DELETE FROM student WHERE
id="

30
Enrollment No:23DIT0055 Advanced Java Programming

+ id); [Link](this,
"Record Deleted");
}
} catch (Exception e) {
[Link](this,
[Link]());
}
} public static void
main(String args[]) { new
Practical_11();
}
}
Output :
Record Updated where ID = 1

Record Deleted where ID = 1

31
Enrollment No:23DIT0055 Advanced Java Programming

Practical 12

Aim : Develop a program to present a set of choice for user to select a product
and display the price of product.

import [Link].*; import


[Link].*;
import [Link].*;
class Practical_12 extends JFrame implements
ActionListener {
JRadioButton p1, p2, p3;
JButton show;
JLabel result;
Practical_12() {
setTitle("Product Price
Display");
setSize(300, 200);
setLayout(new FlowLayout());
add(new JLabel("Select a
Product:"));
p1 =
new
JRadioButton("Mobile"); p2
= new JRadioButton("Laptop");
p3 = new JRadioButton("Headphones");
ButtonGroup bg = new
ButtonGroup(); [Link](p1);
[Link](p2); [Link](p3);

add(p1);
add(p2); add(p3);
show = new JButton("Show
Price");
result = new JLabel("Price will appear here.");
add(show); add(result);

[Link](this);

32
Enrollment No:23DIT0055 Advanced Java Programming

setDefaultCloseOperation(EXIT_ON_CLOSE)
; setVisible(true);
} public void
actionPerformed(ActionEvent e) { if
([Link]())
[Link]("Price: ₹15,000"); else
if
([Link]())
[Link]("Price: ₹55,000"); else if
([Link]())
[Link]("Price: ₹2,000");
else [Link]("Please select a
product.");
} public static void
main(String args[]) { new
Practical_12();
}
}

Output :

33
Enrollment No:23DIT0055 Advanced Java Programming

Practical 13

Aim : Develop a simple servlet program which maintains a counter for the
number of times it has been accessed since its loading, initialize the counter
using deployment descriptor

import [Link]; import


[Link]; import
[Link]; import
[Link]; import
[Link]; import
[Link];
public class CounterServlet extends
HttpServlet { @Override
public void init() throws ServletException
{ [Link]();
String initialCountStr =
getServletContext().getInitParameter("initialAccessCount");
int initialCount = 0; if (initialCountStr
!= null) {
try { initialCount =
[Link]([Link]());
} catch (NumberFormatException e) {
[Link]("Error parsing initial count
from [Link]. Defaulting to 0.");
}
}

getServletContext().setAttribute("accessCount",
initialCount);
[Link]("Application Counter initialized to:
" + initialCount);
}

@Override protected void


doGet(HttpServletRequest request, HttpServletResponse

34
Enrollment No:23DIT0055 Advanced Java Programming

response) throws ServletException,


IOException {
Integer currentCount;
synchronized
(getServletContext()) {
currentCount =
(Integer)
getServletContext().getAttribute("accessCount");

currentCount++;

getServletContext().setAttribute("accessCount",
currentCount);

}
[Link]("text/html");
PrintWriter out = [Link]();
[Link]("<!DOCTYPE
html>");
[Link]("<html>");
[Link]("<body>");
[Link]("<h1>Application Access Counter</h1>");
[Link]("<p>Total times this application has been
accessed: <strong>" + currentCount + "</strong></p>");
[Link]("<p>The counter started from the value defined in
[Link].</p>"); [Link]("</body>");
[Link]("</html>");
}
}

Output :

This servlet has been accessed 11 times.

35
Enrollment No:23DIT0055 Advanced Java Programming

This servlet has been accessed 12 times.

36
Enrollment No:23DIT0055 Advanced Java Programming

Practical 14

Aim : Create a web form which processes servlet and demonstrates use of
cookies and sessions.

import [Link]; import


[Link]; import
[Link]; import
[Link]; import
[Link]; import
[Link];
import [Link];
import [Link];
public class AuthServlet extends
HttpServlet {
@Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {

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


Cookie nameCookie = new Cookie("user_name", userName);
[Link](60 * 60); // Set cookie lifetime
[Link](nameCookie); // Send cookie to the client
browser

HttpSession session = [Link]();

[Link]("session_user", userName);
Integer visitCount = (Integer)
[Link]("visit_count"); if
(visitCount == null) { visitCount = 1;
} else {
visitCount++;
}

37
Enrollment No:23DIT0055 Advanced Java Programming

[Link]("visit_count",
visitCount);
[Link]("text/html");
PrintWriter out = [Link]();
[Link]("<!DOCTYPE html>");
[Link]("<html>");
[Link]("<head><title>Status Page</title></head>");
[Link]("<body>");
[Link]("<h1>Hello, " + userName + "!</h1>");
[Link]("<h2>Session and Cookie Demonstration:</h2>");
[Link]("<hr>");
[Link]("<h3>1. Session Tracking
(Current Visit Status):</h3>");
[Link]("<p><b>Status:</b> You are logged in for this
session.</p>"); [Link]("<p><b>Session ID:</b> " +
[Link]() + "</p>"); [Link]("<p><b>Session
Page Views:</b> " + visitCount + "</p>");
[Link]("<h3>2. Cookie
Usage (Long-term Persistence):</h3>");
[Link]("<p>Your name is saved in a **Cookie** on your
browser.</p>"); [Link]("<p>If you close your
browser and come back later, the server can still retrieve the
cookie data (if not expired).</p>");
[Link]("<p><b>Cookie Name Saved:</b> " +
[Link]() + "</p>");

[Link]("</body>");
[Link]("</html>");
}
}

Output :

If the user enters their name on the first page, the second page displays that name
using a Cookie.

38
Enrollment No:23DIT0055 Advanced Java Programming

39
Enrollment No:23DIT0055 Advanced Java Programming

Practical 15

Aim : Develop a simple JSP program for user registration and then control will
be transfer it into second page.

[Link]

<!DOCTYPE html>
<html>
<head>
<title>User Registration</title>
</head>
<body>
<h1>New User Registration</h1>
<form action="[Link]" method="POST">
<label for="userName">Name:</label>
<input type="text" id="userName"
name="userName" required><br><br>
<label for="userEmail">Email:</label>
<input type="email" id="userEmail" name="userEmail"
required><br><br> <button type="submit">Register and
Proceed</button>
</form>
</body>
</html>

[Link]
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>Welcome Page</title>
</head>
<body>
<%

40
Enrollment No:23DIT0055 Advanced Java Programming

// Retrieve the data submitted from the previous


page ([Link]) // Note: The input names
('userName' and 'userEmail') are used here.
String name = [Link]("userName");
String email = [Link]("userEmail");
// Simple validation check if (name == null ||
[Link]().isEmpty() || email == null || [Link]().isEmpty())
{
%>
<h1>Error: Registration Failed</h1>
<p>Please go back and fill out all fields.</p>
<p><a href="[Link]">Go Back to
Registration</a></p> <%
} else {
%>
<h1>Welcome, <%= name %>!</h1>
<h2>Registration Successful</h2>
<p>Thank you for registering. Your details are:</p>
<ul>
<li><strong>Name:</strong> <%= name %></li>
<li><strong>Email:</strong> <%= email %></li>
</ul>
<p>This demonstrates the transfer of control and
data between two JSP pages.</p>
<%
}
%>
</body>
</html>
Output :

41
Enrollment No:23DIT0055 Advanced Java Programming

Practical 16

Aim : Develop a simple JSP program for user login form with static and
dynamic database

[Link](For static login)

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


pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>User Login</title>
</head>
<body>
<h1>User Login</h1>
<%
// 1. Check if the form has been submitted
String username = [Link]("username");
if
(username != null &&
![Link]().isEmpty()) { // If
submitted, forward control to the dynamic logic
page // for validation (or include
the logic directly here).
// We will use request dispatcher to forward
control to the validation page.
%>
<jsp:forward page="validate_static.jsp" />
<%
} else {
// If not submitted, display the form
%>
<form action="[Link]" method="post">
<label for="username">Username:</label>
<input type="text" id="username" name="username"
required><br><br>

42
Enrollment No:23DIT0055 Advanced Java Programming

<label
for="password">Password:</label>
<input type="password" id="password" name="password"
required><br><br>
<button type="submit">Login</button>
</form>
<%
}
%>
</body>
</html>

[Link](For Dynamic login)

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


pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>User Login</title>
</head>
<body>
<h1>User Login</h1>
<%
// 1. Check if the form has been submitted
String username = [Link]("username");
if
(username != null &&
![Link]().isEmpty()) { // If
submitted, forward control to the dynamic logic
page // for validation (or include
the logic directly here).
// We will use request dispatcher to forward
control to the validation page.
%>
<jsp:forward page="validate_dynamic.jsp" />
<%

43
Enrollment No:23DIT0055 Advanced Java Programming

} else {
// If not submitted, display the form
%>
<form action="[Link]" method="post">
<label for="username">Username:</label>
<input type="text" id="username" name="username"
required><br><br>
<label
for="password">Password:</label>
<input type="password" id="password" name="password"
required><br><br>
<button type="submit">Login</button>
</form>
<%
}
%>
</body>
</html>

Validate_static.jsp

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


pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>Static Login Result</title>
</head>
<body>
<%
// Retrieve parameters forwarded from [Link]
String user = [Link]("username");
String pass = [Link]("password");
// --- Static Credentials ---
String STATIC_USER = "Ansh";
String STATIC_PASS = "12345";

44
Enrollment No:23DIT0055 Advanced Java Programming

if
([Link](STATIC_USER) &&
[Link](STATIC_PASS)) { %>
<h1> Welcome, <%= user %>!</h1>
<p>You have been successfully logged in using
**Static Credentials**.</p> <p>Control was
transferred from **[Link]**.</p>
<%
} else {
%>
<h1> Login Failed!</h1>
<p>Invalid username or password.</p>
<p><a href="[Link]">Try Again</a></p>
<%
}
%>
</body>
</html>

Validate_dynamic.jsp

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


pageEncoding="UTF-8"%>
<%@ page import="[Link].*" %>
<!DOCTYPE html>
<html>
<head>
<title>Dynamic Login Result</title>
</head>
<body>
<%
// 1. Retrieve parameters
String user = [Link]("username");
String pass = [Link]("password");

// --- Database Configuration (UPDATE THESE


VALUES) --- String DB_URL =

45
Enrollment No:23DIT0055 Advanced Java Programming

"jdbc:mysql://localhost:3306/mydatabase";
String DB_USER = "dbuser";
String DB_PASS = "dbpassword";
Connection conn =
null;
PreparedStatement ps = null;
ResultSet rs = null;
boolean authenticated
= false;
try {
// 2. Load the JDBC Driver (for newer versions,
this step is often optional)
[Link]("[Link]");
// 3. Establish connection
conn = [Link](DB_URL, DB_USER,
DB_PASS);

// 4. Prepare and execute the query (Preventing SQL


Injection using
PreparedStatement)
String sql = "SELECT username FROM users
WHERE username = ? AND password = ?"; ps =
[Link](sql); [Link](1,
user); [Link](2, pass);
rs =
[Link]();
// 5. Check if a
user was found
if ([Link]()) {
authenticated = true;
}

} catch (Exception e) {
%>
<h1> Database Error</h1>
<p>Could not connect to the database or run the
query.</p>
<p>Error: <%= [Link]() %></p>

46
Enrollment No:23DIT0055 Advanced Java Programming

<%
return; // Stop execution on error
} finally {
// 6. Close all resources try { if (rs
!= null) [Link](); } catch
(SQLException ignored) {} try { if (ps != null)
[Link](); } catch
(SQLException ignored) {} try { if (conn != null)
[Link](); } catch (SQLException ignored) {}
} if
(authenticated) {
%>
<h1> Welcome, <%= user %>!</h1>
<p>You have been successfully logged in using a
**Dynamic Database** connection.</p>
<p>Control was transferred from **[Link]**.</p>
<%
} else {
%>
<h1> Login Failed!</h1>
<p>Invalid username or password (checked against
the
database).</p> <p><a href="[Link]">Try
Again</a></p>
<%
}
%>
</body>
</html>

Output :
For Static Login :

47
Enrollment No:23DIT0055 Advanced Java Programming

For Dynamic Login :

48
Enrollment No:23DIT0055 Advanced Java Programming

Practical 17

Aim : Develop a JSP program to display the grade of a student by accepting


the marks of five subjects.

<%@ page language="java" contentType="text/html;


charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>Student Grading System</title>
<style> body { font-family:
Arial, sans-serif;
}
.result { border: 1px solid #ccc; padding: 15px;
margin-top: 20px; background-color: #f9f9f9; }
.success { color: green; font-weight: bold; }
.fail { color: red; font-weight: bold; }
</style>
</head>
<body>
<h1>Student Grade Calculator</h1>
<%
// 1. Check if the form has been submitted (by
checking if any mark parameter exists)
String mark1Str = [Link]("mark1");
if (mark1Str
!= null) {
// --- Logic for Grade Calculation ---
double
totalMarks = 0; int
numSubjects = 5;

49
Enrollment No:23DIT0055 Advanced Java Programming

String grade = "N/A";


boolean valid = true;
// Collect marks safely
try {
// Get marks from request, ensuring they
are valid numbers double mark1 =
[Link](mark1Str); double
mark2 =
[Link]([Link]("mark2"));
double mark3 =
[Link]([Link]("mark3"));
double mark4 =
[Link]([Link]("mark4"));
double mark5 =
[Link]([Link]("mark5"));

// Sum the marks


totalMarks = mark1 + mark2 + mark3 + mark4 +
mark5;

// Calculate Average Percentage (assuming


Max Marks per subject is 100)
double maxTotal = numSubjects * 100;
double averagePercent = (totalMarks / maxTotal) * 100;

// 2. Determine the
Grade if
(averagePercent >= 90) { grade
= "A+ (Excellent)";
} else if (averagePercent >= 80)
{ grade = "A
(Very Good)"; }
else

50
Enrollment No:23DIT0055 Advanced Java Programming

if (averagePercent >= 70) { grade


= "B (Good)";
} else if
(averagePercent >= 60) { grade
= "C (Satisfactory)";
} else if (averagePercent >= 50)
{
grade = "D (Pass)";
} else {
grade = "F (Fail)";
}
%>
<div class="result">
<h2>Results Summary</h2>
<p>Total Marks Obtained (out of <%=
maxTotal %>): <strong><%= totalMarks %></strong></p>
<p>Average Percentage: <strong><%=
[Link]("%.2f", averagePercent)
%>&#37;</strong></p>
<p>Final Grade: <span class="<%=
(averagePercent >= 50 ?
"success" : "fail") %>">
<%= grade %>
</span></p>
</div>
<%
} catch (NumberFormatException e) {
// Handle non-numeric input error
%>
<div class="result fail">
<h2>Input Error</h2>
<p>Please enter valid numerical values for
all five subjects.</p>

51
Enrollment No:23DIT0055 Advanced Java Programming

</div>
<%
} // End try-catch
} // End if (form submitted)
%>
<hr>
<form action="calculate_grade.jsp" method="post">
<h3>Enter Marks (Max 100 per Subject):</h3>
<label for="mark1">Subject 1:</label>
<input type="number" id="mark1" name="mark1"
min="0" max="100" required><br><br>
<label for="mark2">Subject 2:</label>
<input type="number" id="mark2" name="mark2"
min="0" max="100" required><br><br>
<label for="mark3">Subject 3:</label>
<input type="number" id="mark3" name="mark3"
min="0" max="100" required><br><br>
<label for="mark4">Subject 4:</label>
<input type="number" id="mark4" name="mark4"
min="0" max="100" required><br><br>
<label for="mark5">Subject 5:</label>
<input type="number" id="mark5" name="mark5"
min="0" max="100" required><br><br>
<button type="submit">Calculate Grade</button>
</form>
</body>
</html>

Output :

52
Enrollment No:23DIT0055 Advanced Java Programming

53

You might also like