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

Advanced Java Practical

The document outlines a series of practical exercises demonstrating various Java AWT and Swing components, including buttons, dialogs, menus, lists, checkboxes, and database operations using JDBC. Each practical includes the aim, Java code examples, and expected outputs for implementing GUI elements and database interactions. The exercises cover a range of topics from basic GUI creation to advanced features like RMI and database record manipulation.

Uploaded by

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

Advanced Java Practical

The document outlines a series of practical exercises demonstrating various Java AWT and Swing components, including buttons, dialogs, menus, lists, checkboxes, and database operations using JDBC. Each practical includes the aim, Java code examples, and expected outputs for implementing GUI elements and database interactions. The exercises cover a range of topics from basic GUI creation to advanced features like RMI and database record manipulation.

Uploaded by

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

Practical No 1

Aim: Implements and create five button and put on different direction and centre by using
border layout manager.

AWTBorderLayoutExample.java
import java.awt.*;

public class AWTBorderLayoutExample {


public static void main(String[] args) {
Frame frame = new Frame("AWT BorderLayout Example");

Button northButton = new Button("North");


Button southButton = new Button("South");
Button eastButton = new Button("East");
Button westButton = new Button("West");
Button centerButton = new Button("Center");

frame.setLayout(new BorderLayout());

frame.add(northButton, BorderLayout.NORTH);
frame.add(southButton, BorderLayout.SOUTH);
frame.add(eastButton, BorderLayout.EAST);
frame.add(westButton, BorderLayout.WEST);
frame.add(centerButton, BorderLayout.CENTER);

frame.setSize(400, 300);
frame.setVisible(true);
}
}
Output:
Practical No 02
Aim: Implementation of awt to create a dialog box
DialogExample.java
import java.awt.*;

public class DialogExample {


private Frame mainFrame;
private Button showButton;
private Dialog dialog;

public DialogExample() {
prepareGUI();
showFileDialog();
}

private void prepareGUI() {


mainFrame = new Frame("Dialog Example");
mainFrame.setSize(400, 400);
mainFrame.setLayout(new FlowLayout());

showButton = new Button("Show Dialog");


mainFrame.add(showButton);
mainFrame.setVisible(true);
}

private void showFileDialog() {


dialog = new Dialog(mainFrame, "Dialog", true);
dialog.setSize(300, 200);
dialog.setLayout(new FlowLayout());

Label label = new Label("This is a dialog box.");


dialog.add(label);
Button closeButton = new Button("Close");
dialog.add(closeButton);
dialog.setVisible(true);
}

public static void main(String[] args) {


new DialogExample();
}
}

Output
Practical No 03
Aim: Implementation of AWT to create menubar.

MenuBarExample.java
import java.awt.*;

public class MenuBarExample {


private Frame mainFrame;
private MenuBar menuBar;
private Menu fileMenu;
private MenuItem openMenuItem;
private MenuItem saveMenuItem;
private MenuItem exitMenuItem;

public MenuBarExample() {
prepareGUI();
createMenuBar();
}

private void prepareGUI() {


mainFrame = new Frame("Menu Bar Example");
mainFrame.setSize(400, 400);
mainFrame.setLayout(new FlowLayout());
mainFrame.setVisible(true);
}

private void createMenuBar() {


menuBar = new MenuBar();
fileMenu = new Menu("File");

openMenuItem = new MenuItem("Open");


saveMenuItem = new MenuItem("Save");
exitMenuItem = new MenuItem("Exit");

fileMenu.add(openMenuItem);
fileMenu.add(saveMenuItem);
fileMenu.addSeparator();
fileMenu.add(exitMenuItem);

menuBar.add(fileMenu);

mainFrame.setMenuBar(menuBar);
}

public static void main(String[] args) {


new MenuBarExample();
}
}
Output:
Practical No 04
Aim: Implementation of AWT to create list

ListExample.java
import java.awt.*;
import java.awt.event.*;

public class ListExample {


private Frame mainFrame;
private List list;

public ListExample() {
prepareGUI();
createList();
}

private void prepareGUI() {


mainFrame = new Frame("List Example");
mainFrame.setSize(400, 400);
mainFrame.setLayout(new FlowLayout());

mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent) {
System.exit(0);
}
});

mainFrame.setVisible(true);
}

private void createList() {


list = new List(4, true); // Parameters: visible rows, multiple selection allowed
list.add("Item 1");
list.add("Item 2");
list.add("Item 3");
list.add("Item 4");
list.add("Item 5");

mainFrame.add(list);
}

public static void main(String[] args) {


new ListExample();
}
}

Output:
Practical No 05
Aim: Implementation of AWT to create choice
ChoiceExample.java
import java.awt.*;
import java.awt.event.*;

public class ChoiceExample {


private Frame mainFrame;
private Choice choice;

public ChoiceExample() {
prepareGUI();
createChoice();
}

private void prepareGUI() {


mainFrame = new Frame("Choice Example");
mainFrame.setSize(400, 400);
mainFrame.setLayout(new FlowLayout());

mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent) {
System.exit(0);
}
});

mainFrame.setVisible(true);
}

private void createChoice() {


choice = new Choice();
choice.add("Option 1");
choice.add("Option 2");
choice.add("Option 3");
choice.add("Option 4");
choice.add("Option 5");

mainFrame.add(choice);
}

public static void main(String[] args) {


new ChoiceExample();
}
}

Output:
Practical No 06
Aim: Implementation of AWT to create checkbox

CheckboxExample.java

import java.awt.*;
import java.awt.event.*;

public class CheckboxExample {


private Frame mainFrame;
private Checkbox checkbox1, checkbox2, checkbox3;

public CheckboxExample() {
prepareGUI();
createCheckboxes();
}

private void prepareGUI() {


mainFrame = new Frame("Checkbox Example");
mainFrame.setSize(400, 400);
mainFrame.setLayout(new FlowLayout());

mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent) {
System.exit(0);
}
});

mainFrame.setVisible(true);
}

private void createCheckboxes() {


checkbox1 = new Checkbox("Checkbox 1");
checkbox2 = new Checkbox("Checkbox 2");
checkbox3 = new Checkbox("Checkbox 3");

mainFrame.add(checkbox1);
mainFrame.add(checkbox2);
mainFrame.add(checkbox3);
}

public static void main(String[] args) {


new CheckboxExample();
}
}
Output:
Practical No 07
Aim: Implementation of AWT to create scrollbar
ScrollbarExample.java
import java.awt.*;

public class ScrollbarExample {


private Frame mainFrame;
private Scrollbar scrollbar;

public ScrollbarExample() {
prepareGUI();
createScrollbar();
}

private void prepareGUI() {


mainFrame = new Frame("Scrollbar Example");
mainFrame.setSize(400, 400);
mainFrame.setLayout(new FlowLayout());
mainFrame.setVisible(true);
}

private void createScrollbar() {


scrollbar = new Scrollbar();
scrollbar.setOrientation(Scrollbar.VERTICAL);
scrollbar.setMinimum(0);
scrollbar.setMaximum(100);
scrollbar.setVisibleAmount(10);
scrollbar.setUnitIncrement(1);
scrollbar.setBlockIncrement(10);
mainFrame.add(scrollbar);
}
public static void main(String[] args) {
new ScrollbarExample();
}
}

Output:
Practical No 08
Aim: Implementation of swing to demonstrate of Radiobutton
import javax.swing.*;
import java.awt.*;

public class RadioButtonExample {


private JFrame mainFrame;
private JPanel panel;
private JRadioButton radioButton1, radioButton2, radioButton3;

public RadioButtonExample() {
prepareGUI();
createRadioButtons();
}

private void prepareGUI() {


mainFrame = new JFrame("RadioButton Example");
mainFrame.setSize(400, 400);
mainFrame.setLayout(new FlowLayout());
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

panel = new JPanel();


panel.setLayout(new GridLayout(3, 1));

mainFrame.add(panel);
mainFrame.setVisible(true);
}

private void createRadioButtons() {


radioButton1 = new JRadioButton("Option 1");
radioButton2 = new JRadioButton("Option 2");
radioButton3 = new JRadioButton("Option 3");
ButtonGroup group = new ButtonGroup();
group.add(radioButton1);
group.add(radioButton2);
group.add(radioButton3);

panel.add(radioButton1);
panel.add(radioButton2);
panel.add(radioButton3);
}

public static void main(String[] args) {


new RadioButtonExample();
}
}

Output:
Practical No 09
Aim: Implementation of swing to demonstrate of JToggleButton
JToggleButtonExample.java
import javax.swing.*;
import java.awt.*;

public class JToggleButtonExample {


private JFrame mainFrame;
private JPanel panel;
private JToggleButton toggleButton1, toggleButton2, toggleButton3;

public JToggleButtonExample() {
prepareGUI();
createToggleButtons();
}

private void prepareGUI() {


mainFrame = new JFrame("JToggleButton Example");
mainFrame.setSize(400, 400);
mainFrame.setLayout(new FlowLayout());
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

panel = new JPanel();


panel.setLayout(new GridLayout(3, 1));

mainFrame.add(panel);
mainFrame.setVisible(true);
}

private void createToggleButtons() {


toggleButton1 = new JToggleButton("Option 1");
toggleButton2 = new JToggleButton("Option 2");
toggleButton3 = new JToggleButton("Option 3");

panel.add(toggleButton1);
panel.add(toggleButton2);
panel.add(toggleButton3);
}

public static void main(String[] args) {


new JToggleButtonExample();
}
}
Output:
Practical No 10
Aim: Implementation of swing to demonstrate of Tabbed panes
TabbedPaneExample.java
import javax.swing.*;
import java.awt.*;

public class TabbedPaneExample {


private JFrame mainFrame;
private JTabbedPane tabbedPane;

public TabbedPaneExample() {
prepareGUI();
createTabbedPane();
}

private void prepareGUI() {


mainFrame = new JFrame("TabbedPane Example");
mainFrame.setSize(400, 400);
mainFrame.setLayout(new GridLayout(1, 1));
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

tabbedPane = new JTabbedPane();


mainFrame.add(tabbedPane);

mainFrame.setVisible(true);
}

private void createTabbedPane() {


JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
JPanel panel3 = new JPanel();
tabbedPane.addTab("Tab 1", panel1);
tabbedPane.addTab("Tab 2", panel2);
tabbedPane.addTab("Tab 3", panel3);
}

public static void main(String[] args) {


new TabbedPaneExample();
}
}
Output:
Practical No 11
Aim: Implementation of swing to demonstrate of tree.
TreeDemo.java
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;

public class TreeDemo {


public static void main(String[] args) {
JFrame frame = new JFrame("Tree Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root");


DefaultMutableTreeNode node1 = new DefaultMutableTreeNode("Node 1");
DefaultMutableTreeNode node2 = new DefaultMutableTreeNode("Node 2");
DefaultMutableTreeNode node3 = new DefaultMutableTreeNode("Node 3");

root.add(node1);
root.add(node2);
root.add(node3);

node1.add(new DefaultMutableTreeNode("Subnode 1"));


node1.add(new DefaultMutableTreeNode("Subnode 2"));

node2.add(new DefaultMutableTreeNode("Subnode 3"));

JTree tree = new JTree(root);


JScrollPane treeScrollPane = new JScrollPane(tree);

frame.add(treeScrollPane);

frame.setSize(300, 300);
frame.setVisible(true);
}
}

Output:
Practical No 12
Aim: Implementation of JDBC to insert record in database.
InsertRecordExample.java

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class InsertRecordExample {


private static final String JDBC_URL = "jdbc:mysql://localhost:3306/mydatabase";
private static final String USERNAME = "root";
private static final String PASSWORD = "tiger";

public static void main(String[] args) {


try {

Connection connection = DriverManager.getConnection(JDBC_URL, USERNAME,


PASSWORD);

String sql = "INSERT INTO my_table (id, name) VALUES (?, ?)";

PreparedStatement preparedStatement = connection.prepareStatement(sql);

preparedStatement.setInt(1, 1); // Assuming id is an integer column and you want to insert 1


preparedStatement.setString(2, "John"); // Assuming name is a string column and you want to
insert "John"

int rowsInserted = preparedStatement.executeUpdate();


if (rowsInserted > 0) {
System.out.println("A new record was inserted successfully!");
} else {
System.out.println("Failed to insert the record!");
}

preparedStatement.close();
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Output:

A new record was inserted successfully!

Process finished with exit code 0


Practical No 13
Aim: Implementation of JDBC to update record of database.
UpdateRecordExample.java

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class UpdateRecordExample {

private static final String JDBC_URL = "jdbc:mysql://localhost:3306/mydatabase";


private static final String USERNAME = "your_username";
private static final String PASSWORD = "your_password";

public static void main(String[] args) {


try {

Connection connection = DriverManager.getConnection(JDBC_URL, USERNAME,


PASSWORD);

String sql = "UPDATE my_table SET name = ? WHERE id = ?";

PreparedStatement preparedStatement = connection.prepareStatement(sql);

preparedStatement.setString(1, "Sagar"); // Assuming you want to update the name to "New


Name"
preparedStatement.setInt(2, 1); // Assuming id is an integer column and you want to update the
record with id 1

int rowsUpdated = preparedStatement.executeUpdate();


if (rowsUpdated > 0) {
System.out.println("Record updated successfully!");
} else {
System.out.println("No records were updated!");
}

preparedStatement.close();
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Output:
Record updated successfully!

Process finished with exit code 0


Practical No 14
Aim: Implementation of JDBC to select record from table and display it.
SelectRecordExample.java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class SelectRecordExample {


private static final String JDBC_URL = "jdbc:mysql://localhost:3306/mydatabase";
private static final String USERNAME = "root";
private static final String PASSWORD = "tiger";

public static void main(String[] args) {


try {

Connection connection = DriverManager.getConnection(JDBC_URL, USERNAME,


PASSWORD);

String sql = "SELECT id, name FROM mytable";

PreparedStatement preparedStatement = connection.prepareStatement(sql);

ResultSet resultSet = preparedStatement.executeQuery();

while (resultSet.next()) {
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
System.out.println("ID: " + id + ", Name: " + name);
}

resultSet.close();
preparedStatement.close();
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Output:
ID: 1, Name: Sagar
ID: 2, Name: Isha

Process finished with exit code 0


Practical No 15
Aim: Implementation of RMI application
Hello.java
import java.rmi.Remote;
import java.rmi.RemoteException;

public interface Hello extends Remote {


String sayHello() throws RemoteException;
}
HelloImpl.java
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;

public class HelloImpl extends UnicastRemoteObject implements Hello {


public HelloImpl() throws RemoteException {
super();
}

public String sayHello() throws RemoteException {


return "Hello, world!";
}
}

Server.java
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;

public class Server {


public static void main(String[] args) {
try {
HelloImpl obj = new HelloImpl();
Registry registry = LocateRegistry.createRegistry(1099);
registry.bind("Hello", obj);

System.out.println("Server is running...");
} catch (Exception e) {
System.err.println("Server exception: " + e.toString());
e.printStackTrace();
}
}
}
Client.java
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;

public class Client {


public static void main(String[] args) {
try {
Registry registry = LocateRegistry.getRegistry("localhost", 1099);
Hello stub = (Hello) registry.lookup("Hello");
String response = stub.sayHello();
System.out.println("Response from server: " + response);
} catch (Exception e) {
System.err.println("Client exception: " + e.toString());
e.printStackTrace();
}
}
}
Output:
Server is running...
Response from server: Hello, world!
Practical No 16
Aim: Design a Program to Implement a Socket programming where client will send the request
and server will then respond.
Server.java
import java.io.*;
import java.net.*;

public class Server {


public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(12345);
System.out.println("Server is running. Waiting for client...");
Socket clientSocket = serverSocket.accept();
System.out.println("Client connected.");
BufferedReader in = new BufferedReader(new
InputStreamReader(clientSocket.getInputStream()));
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
String request = in.readLine();
System.out.println("Client request: " + request);
out.println("Hello, client! This is the server responding to your request: " + request);
in.close();
out.close();
clientSocket.close();
serverSocket.close();
} catch (IOException e) {
System.err.println("Error: " + e.getMessage());
}
}
}
Client.java
import java.io.*;
import java.net.*;

public class Client {


public static void main(String[] args) {
try {
Socket socket = new Socket("localhost", 12345);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out.println("Hello, server! How are you?");
String response = in.readLine();
System.out.println("Server response: " + response);
out.close();
in.close();
socket.close();
} catch (IOException e) {
System.err.println("Error: " + e.getMessage());
}
}
}

Client side output:


Server response: Hello, client! This is the server responding to your request: Hello, server! How are
you?
Server side output:
Server is running. Waiting for client...
Client connected.
Client request: Hello, server! How are you?
Practical No 17
Aim: Implementation of servlets for Hello World

HelloWorldServlet.java
package myPackage;

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

@WebServlet("/hello")
public class HelloWorldServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<h1>Hello, World! </h1>");
}
}

Output:
Practical No 18
Aim: Implementation of servlets for doGet method

Index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h2>Enter Your Name</h2>
<form action="welcome" method="get">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>
<button type="submit">Submit</button>
</form>
</body>
</html>

WelcomeServelt.java:
package myPackage;

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

@WebServlet("/welcome")
public class WelcomeServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

public WelcomeServlet() {
super();

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws


ServletException, IOException {

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

// Retrieve the 'name' parameter from the request


String name = request.getParameter("name");
if (name == null || name.trim().isEmpty()) {
name = "Guest"; // Default if no name is provided
}

out.println("<html><head><title>Welcome</title></head><body>");
out.println("<h1>Welcome, " + name + "!</h1>");
out.println("</body></html>");
}

Output:
Index.html:

WelcomeServlet.java
Practical No. 19
Aim: Implementation of servlets for doPost method

Dob.html:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h2>Enter Your Date of Birth</h2>
<form action="calculateAge" method="post">
<label for="dob">Date of Birth:</label>
<input type="datetime-local" id="dob" name="dob" required>
<button type="submit">Calculate Age</button>
</form>
</body>
</html>

AgeCalculatorServlet.java:
package myPackage;

import java.io.IOException;
import java.io.PrintWriter;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

@WebServlet("/calculateAge")
public class AgeCalculatorServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();

try {
// Get DOB from request
String dobInput = request.getParameter("dob");
if (dobInput == null || dobInput.isEmpty()) {
out.println("<h1>Error: Please provide a valid date of birth.</h1>");
return;
}

// Parse input into LocalDateTime


DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm");
LocalDateTime dob = LocalDateTime.parse(dobInput, formatter);

// Get current time


LocalDateTime now = LocalDateTime.now(ZoneId.systemDefault());

// Calculate differences
Duration duration = Duration.between(dob, now);
long totalSeconds = duration.getSeconds();
long years = totalSeconds / (365 * 24 * 3600);
long remainingSeconds = totalSeconds % (365 * 24 * 3600);
long months = remainingSeconds / (30 * 24 * 3600);
remainingSeconds %= (30 * 24 * 3600);
long days = remainingSeconds / (24 * 3600);
remainingSeconds %= (24 * 3600);
long hours = remainingSeconds / 3600;
remainingSeconds %= 3600;
long minutes = remainingSeconds / 60;
long seconds = remainingSeconds % 60;
long microseconds = duration.toNanos() / 1000; // Convert nanoseconds to microseconds

// Display result
out.println("<html><head><title>Age Result</title></head><body>");
out.println("<h1>Age Calculation Result</h1>");
out.println("<p><strong>Total Years:</strong> " + years + "</p>");
out.println("<p><strong>Total Months:</strong> " + months + "</p>");
out.println("<p><strong>Total Days:</strong> " + days + "</p>");
out.println("<p><strong>Total Hours:</strong> " + hours + "</p>");
out.println("<p><strong>Total Minutes:</strong> " + minutes + "</p>");
out.println("<p><strong>Total Seconds:</strong> " + seconds + "</p>");
out.println("<p><strong>Total Microseconds:</strong> " + microseconds + "</p>");
out.println("</body></html>");

} catch (Exception e) {
out.println("<h1>Error processing request: " + e.getMessage() + "</h1>");
}
}
}
Output:
Dob.html:

AgeCalculatorServlet.java:
Practical No. 20
Aim: Implementation of JSP to create User ID and Password

index.jps:

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


pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h2>Create User ID & Password</h2>
<form action="success.jsp" method="post">
<label for="userId">User ID:</label>
<input type="text" id="userId" name="userId" required><br><br>

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

<button type="submit">Register</button>
</form>
</body>
</html>

success.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h2>Registration Successful!</h2>

<%

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


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

if (userId == null || password == null || userId.isEmpty() || password.isEmpty()) {


out.println("<p>Error: User ID and Password are required!</p>");
} else {

session.setAttribute("userId", userId);
session.setAttribute("password", password);

out.println("<p><strong>User ID:</strong> " + userId + "</p>");


out.println("<p>Your password is stored securely (not displayed here).</p>");
}
%>
</body>
</html>

Output:
Index.jsp

Success.jsp

You might also like