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

Final Assignment Java Akshad

The document contains details about Akshad Jaiswal including name and roll number. It then provides 7 code examples showing how to: 1) sort an array in ascending order using merge sort, 2) find the transpose of a matrix, 3) reverse a string, 4) check if a string is a palindrome, 5) create classes in a package, 6) implement an interface with classes, and 7) create an abstract class with derived classes. The last example shows how to test 5 standard exceptions.

Uploaded by

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

Final Assignment Java Akshad

The document contains details about Akshad Jaiswal including name and roll number. It then provides 7 code examples showing how to: 1) sort an array in ascending order using merge sort, 2) find the transpose of a matrix, 3) reverse a string, 4) check if a string is a palindrome, 5) create classes in a package, 6) implement an interface with classes, and 7) create an abstract class with derived classes. The last example shows how to test 5 standard exceptions.

Uploaded by

Akshad Jaiswal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 41

Name : Akshad Jaiswal

Roll no. MC-I-47

1. WAP to sort the elements of an array in ascending order.

public class qu_1_Sort {


static void merge(int a[], int l, int m, int r) {

// get sizes of the arrays to merge


int n1 = m - l + 1;
int n2 = r - m;

// creating temp array


int L[] = new int[n1];
int R[] = new int[n2];

// coping elements in temp array


for (int i = 0; i < n1; ++i) {
L[i] = a[l + i];
}
for (int j = 0; j < n2; ++j) {
R[j] = a[m + 1 + j];
}

// sorting and merging elements into main array

int i = 0, j = 0;

int k = l;

while (i < n1 && j < n2) {


if (L[i] <= R[j]) {
a[k] = L[i];
i++;
} else {
a[k] = R[j];
j++;
}
k++;
}

// adding rest of the elements


while (i < n1) {
a[k] = L[i];
i++;
k++;
}

while (j < n2) {


a[k] = R[j];
j++;
k++;
}
}

static void Mergesort(int[] a, int l, int r) {

if (l < r) {
int m = (l + (r - 1)) / 2;

Mergesort(a, l, m);
Mergesort(a, m + 1, r);

merge(a, l, m, r);
}

public static void main(String args[]) {


int a[] = { 100, 90, 80, 70, 60, 50, 44, 32, 21, 12 };

System.out.print("Elements before sorting => [");

for (int e : a) {
System.out.print(e + " ");
}
System.out.print("]\n");

Mergesort(a, 0, a.length - 1);

System.out.print("Elements after sorting => [");

for (int e : a) {
System.out.print(e + " ");
}
System.out.print("]\n");
}

Output :
Name : Akshad Jaiswal
Roll no. MC-I-47

2. WAP to find the transpose of a given matrix.


public class qu_2_Transpose {

static void print(int[][] a) {


for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
System.out.print(a[i][j] + " ");
}
System.out.println("");
}
}

public static void main(String args[]) {


int[][] a = { { 1, 4, 3 }, { 6, 9, 5 }, { 2, 8, 7} };

System.out.println("The matrix is: ");


print(a);

System.out.println("Transpose of the matrix is: ");


int[][] c = new int[3][3];
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
c[i][j] = a[j][i];
}
}
print(c);

}
}

Output :
Name : Akshad Jaiswal
Roll no. MC-I-47

3. How to reverse a given String? (Without using a pre-defined function)


public class qu_3_Reverse {

public static void main(String args[]) {


String s = "akshad";

String news = "";

for (int i = s.length() - 1; i >= 0; i--) {


news += s.charAt(i);
}

System.out.println("Brfore reversing = " + s);


System.out.println("After reversing = " + news);

Output :
Name : Akshad Jaiswal
Roll no. MC-I-47

4. WAP to How do you check if a given String is Palindrome or not


import java.util.Scanner;

public class qu_4_Palindrome {

public static void main(String args[]) {


Scanner S = new Scanner(System.in);

System.out.println("enter a string");
StringBuilder s = new StringBuilder();
s.append(S.next());

StringBuilder r = new StringBuilder();


r.append(s);
r.reverse();

System.out.println((s == r) ? "The String is palindrome" : "The string is not


palindrome");

Output :
Name : Akshad Jaiswal
Roll no. MC-I-47

5. Create a package mca1 which will have 2 classes as class Mathematics with a
method to add two numbers, add three float numbers and class Maximum with
a method to find maximum of three numbers.
// Mathematics.java class

package mca1;

public class Mathematics {

public int add(int a, int b) {


return a + b;
}

public double add(double a, double b, double c) {


return a + b + c;
}

public static void main(String args[]) {


new Mathematics();
}

// Maximum.java class

package mca1;

public class Maximum {

public void max(int a, int b, int c) {


if (a >= b && a >= c) {
System.out.println(a + " is the greatest number");
} else if (b >= a && b >= c) {
System.out.println(b + " is greatest among the three");
} else {
System.out.println(c + " is the greatest");
}
}

public static void main(String args[]) {


new Maximum();
}

}
// importing mca1 package ..

import mca1.*;

public class qu_5_Package {

public static void main(String args[]) {

Mathematics m = new Mathematics();

double c = m.add(12.1, 31.2, 22.3);

System.out.println("Addition of 15 and 43 is : " + m.add(15, 43));


System.out.println("Addition of 12.1 , 31.2 and 22.3 is : " + c);

Maximum M = new Maximum();

M.max(11, 27, 63);


}

Output :
Name : Akshad Jaiswal
Roll no. MC-I-47

6. Write a Java program to create Animal interface that contains run() and eat()
method. And implement methods in Dog and Cat class.
interface Animal {

void run();

void eat();
}

class Dog implements Animal {

public void eat() {


System.out.println("The dog is eating");
}

public void run() {


System.out.println("The dog is running");
}
}

class Cat implements Animal {

public void eat() {


System.out.println("The cat is eating");

public void run() {


System.out.println("The cat is running");
}
}
public class qu_6_Animal_interface {

public static void main(String args[]) {


Dog d = new Dog();
Cat c = new Cat();

d.eat();
d.run();

c.eat();
c.run();
}
}
Output:

Name : Akshad Jaiswal


Roll no. MC-I-47

7. Write a Java program to create an abstract class Animal that contains non
abstract run() and abstract eat() method.Derive two classes Dog and Cat from it.
abstract class Animal_1 {
void run() {
System.out.println("Animal ran");
};

abstract void eat();


}
class Dog_1 extends Animal_1 {

public void eat() {


System.out.println("The dog is eating");
}

public void run() {


System.out.println("The dog is running");
super.run();
}
}
class Cat_1 extends Animal_1 {
void eat() {
System.out.println("The cat is eating");
}

public void run() {


System.out.println("The cat is running");
super.run();
}
}
public class qu_7_Animal_abstract {

public static void main(String args[]) {


Dog_1 d = new Dog_1();
Cat_1 c = new Cat_1();

d.eat();
d.run();

c.eat();
c.run();
}
}

Output:
Name : Akshad Jaiswal
Roll no. MC-I-47

8 Write a Java program to test any five of standard exception.

import java.util.Scanner;

public class qu_8_Exception {

public static void main(String args[]) throws Exception {

Scanner S = new Scanner(System.in);

while (true) {
System.out.println(
"Choose a number between 1 to 5 : ");
int x = S.nextInt();
switch (x) {
case 1:
try {
int a[] = { 1, 2, 3, 4, 5 };
System.out.println(a[7]);
} catch (Exception e) {
System.out.println("\n" + e + "\n");
}
break;

case 2:
try {
int i = 10 / 0;
System.out.println(x);
} catch (Exception e) {
System.out.println("\n" + e + "\n");
}
break;

case 3:
try {
Class.forName("Test");
} catch (Exception e) {
System.out.println("\n" + e + "\n");
}
break;

case 4:
try {
String w = null;
System.out.println(w.charAt(0));
} catch (Exception e) {
System.out.println("\n" + e + "\n");
}
break;

case 5:
try {
String c = "harsh";
System.out.println(c.charAt(10));
} catch (Exception e) {
System.out.println("\n" + e + "\n");
}
break;

default:
System.out.println("Invalid choice...");

Output:

Name : Akshad Jaiswal


Roll no. MC-I-47

9 User-defined exception.
import java.util.Scanner;

class UDE extends Exception {

public class qu_9_UserDefindException {

public static void main(String args[]) throws UDE {

Scanner S = new Scanner(System.in);

System.out.println("Enter your age : ");


int a = S.nextInt();
try {
if (a < 18) {
throw new UDE();
} else {
System.out.println("Age above 18");
}

} catch (Exception e) {
System.out.println("Exception !! Age not above 18 ");
}
}

Output:

Name : Akshad Jaiswal


Roll no. MC-I-47

10 Write a Java program to create a Thread by extending the Thread class. And
print the name of currently executing thread.
public class qu_10_Thread {

public static void main(String args[]) {

new_Thread t1 = new new_Thread();

System.out.println(Thread.currentThread().getName());
t1.start();
System.out.println(Thread.currentThread().getName());

}
}

class new_Thread extends Thread {


public void run() {
System.out.println(Thread.currentThread().getName());

}
}

Output:
Name : Akshad Jaiswal
Roll no. MC-I-47

11 Write a Java program to create a Thread by Implementing the Runnable


Interface. And print the name of currently executing thread.
public class qu_11_Thread_runnable {

public static void main(String args[]) {

newThread t1 = new newThread();


Thread th = new Thread(t1);

System.out.println(Thread.currentThread().getName());
th.start();
System.out.println(Thread.currentThread().getName());

}
}

class newThread implements Runnable {


public void run() {
System.out.println(Thread.currentThread().getName());
}
}

Output:
Name : Akshad Jaiswal
Roll no. MC-I-47

12 Write a multithreaded program to print even and odd numbers. Create two
threads, one thread prints even number and second thread prints odd number.

public class qu_12_Thread_even_odd {

public static void main(String args[]) {


Even e1 = new Even();
Odd o1 = new Odd();

e1.start();
o1.start();
}
}

class Even extends Thread {


public void run() {
try {
for (int i = 0; i < 15; i++) {
if (i % 2 == 0) {
System.out.println(Thread.currentThread().getName() +":"+ i);
sleep(500);
}
}
} catch (Exception e) {
System.out.println(e);
}
}
}

class Odd extends Thread {


public void run() {
try {
for (int i = 0; i < 15; i++) {
if (i % 2 != 0) {
System.out.println(Thread.currentThread().getName() +":"+ i);
sleep(500);
}
}
} catch (Exception e) {
System.out.println(e);
}
}
}
Output:
Name : Akshad Jaiswal
Roll no. MC-I-47

13 Write a code to remove duplicates from Array List in Java.


import java.util.*;

public class qu_13_Array_list_duplicates {

public static void main(String args[]) {


ArrayList<Integer> a_list = new ArrayList<>();

a_list.add(1);
a_list.add(2);
a_list.add(3);
a_list.add(4);
a_list.add(1);
a_list.add(5);
a_list.add(2);
a_list.add(3);

System.out.println("Array list : " + a_list);

LinkedHashSet<Integer> set = new LinkedHashSet<>();

set.addAll(a_list);

a_list.clear();
a_list.addAll(set);

System.out.println("Array list after removing duplicates : " + a_list);


}
}
Output:
Name : Akshad Jaiswal
Roll no. MC-I-47

14 Write a code to sort a linked list and Reverse a linked list in java.
import java.util.*;

public class qu_14_Linked_list {

public static void main(String args[]) {

LinkedList<Integer> list = new LinkedList<>();


list.add(1);
list.add(13);
list.add(12);
list.add(3);
list.add(5);
list.add(17);

System.out.println("Unordered linked list => " + list);

TreeSet<Integer> tree = new TreeSet<>();

tree.addAll(list);
list.clear();
list.addAll(tree);

System.out.println("Sorted Linked List => " + list);

System.out.print("Linked List in reverse => [");


for (int i = list.size() - 1; i >= 0; i--) {
System.out.print(+list.get(i) + ", ");
}
System.out.print("]");
}

}
Output:
Name : Akshad Jaiswal
Roll no. MC-I-47

15 Write a Java program to copy the contents of a file to another file.

import java.io.*;

import java.util.*;

public class qu_15_File_Handling {

public static void main(String args[]) throws Exception {

Scanner S = new Scanner(System.in);

System.out.println("Enter File to be Read: ");

String toBeRead = S.nextLine();

File r = new File(toBeRead);

System.out.println("Enter File to be Written: ");

String toBeWritten = S.nextLine();

File w = new File(toBeWritten);

FileInputStream Read = new FileInputStream("H:\\Codes\\java codes\\


homework\\src\\assignment\\"+r);

FileOutputStream Write = new FileOutputStream("H:\\Codes\\java codes\\


homework\\src\\assignment\\"+w);

try {

int n;

while ((n = Read.read()) != -1) {

Write.write(n);

System.out.println("File contents have been copied");

} finally {

S.close();
Read.close();

Write.close();

} } }

Output:
Source file…

Destination file before execution..

Execution ..

Destination file after execution..

Name : Akshad Jaiswal


Roll no. MC-I-47

16. Write Java AWT code to accept Student information and display Student
details on the Screen.
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class qu_16_Student_details extends JFrame {


private static final long serialVersionUID = 1L;
private JPanel contentPane;
private JTextField textField;
private JTextField textField_1;
private JTextField textField_2;
private JTextField textField_3;

// Launch the application.

public static void main(String[] args) {


EventQueue.invokeLater(new Runnable() {
public void run() {
try {
qu_16_Student_details frame = new
qu_16_Student_details();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}

// Create the frame.

public qu_16_Student_details() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 649, 484);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));

setContentPane(contentPane);
contentPane.setLayout(null);

textField = new JTextField();


textField.setBounds(178, 45, 226, 46);
contentPane.add(textField);
textField.setColumns(10);

textField_1 = new JTextField();


textField_1.setColumns(10);
textField_1.setBounds(178, 161, 226, 46);
contentPane.add(textField_1);

textField_2 = new JTextField();


textField_2.setColumns(10);
textField_2.setBounds(178, 104, 226, 46);
contentPane.add(textField_2);

textField_3 = new JTextField();


textField_3.setColumns(10);
textField_3.setBounds(178, 230, 226, 46);
contentPane.add(textField_3);

JLabel lblNewLabel = new JLabel("Student name");


lblNewLabel.setBounds(69, 58, 84, 21);
contentPane.add(lblNewLabel);

JLabel lblNewLabel_1 = new JLabel("Student Roll no.");


lblNewLabel_1.setBounds(69, 120, 84, 14);
contentPane.add(lblNewLabel_1);

JLabel lblNewLabel_2 = new JLabel("Contact");


lblNewLabel_2.setBounds(69, 177, 46, 14);
contentPane.add(lblNewLabel_2);

JLabel lblNewLabel_3 = new JLabel("Email");


lblNewLabel_3.setBounds(69, 246, 46, 14);
contentPane.add(lblNewLabel_3);

contentPane.setName("Student Information");

JButton btnNewButton = new JButton("Submit");


btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String name = textField.getText();
String rollno = textField_1.getText();
String contact = textField_2.getText();
String email = textField_3.getText();

JOptionPane.showMessageDialog(btnNewButton, "Name: "+name+"\nRollno:


"+rollno+"\nContact: "+contact+"\nEmail id: "+email);
}
});
btnNewButton.setBounds(248, 331, 89, 23);
contentPane.add(btnNewButton);
}
}
Output:
Name : Akshad Jaiswal
Roll no. MC-I-47

17 Write a JAVA program to design a screen using Swing to perform String


operations.
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class qu_17_String_operations extends JFrame {

private static final long serialVersionUID = 1L;


private JPanel contentPane;
private JTextField textField;
private JTextField textField_1;
private JTextField textField_2;
private JTextField textField_3;

/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
qu_17_String_operations frame = new qu_17_String_operations();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}

/**
* Create the frame.
*/
public qu_17_String_operations() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 639, 450);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));

setContentPane(contentPane);
contentPane.setLayout(null);

textField = new JTextField();


textField.setBounds(113, 63, 86, 20);
contentPane.add(textField);
textField.setColumns(10);

textField_1 = new JTextField();


textField_1.setBounds(324, 63, 86, 20);
contentPane.add(textField_1);
textField_1.setColumns(10);

textField_2 = new JTextField();


textField_2.setBounds(209, 144, 216, 20);
contentPane.add(textField_2);
textField_2.setColumns(10);

JLabel lblNewLabel = new JLabel("String 1");


lblNewLabel.setBounds(43, 66, 46, 14);
contentPane.add(lblNewLabel);

JLabel lblNewLabel_1 = new JLabel("String 2");


lblNewLabel_1.setBounds(268, 66, 46, 14);
contentPane.add(lblNewLabel_1);

JLabel lblNewLabel_2 = new JLabel("Result");


lblNewLabel_2.setBounds(153, 147, 46, 14);
contentPane.add(lblNewLabel_2);

JButton btnNewButton = new JButton("Concatenate");


btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String s1 = textField.getText();
String s2 = textField_1.getText();

String s3 = s1+s2;

textField_2.setText(s3);
}
});
btnNewButton.setBounds(96, 235, 106, 23);
contentPane.add(btnNewButton);

JButton btnNewButton_1 = new JButton("Sub String");


btnNewButton_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String s1 = textField.getText();
String s2 = textField_1.getText();
int i = Integer.parseInt(textField_3.getText());

textField_2.setText(s1.substring(0, i)+s2+s1.substring(i+1));
}
});
btnNewButton_1.setBounds(247, 235, 89, 23);
contentPane.add(btnNewButton_1);
JButton btnNewButton_1_2 = new JButton("Length");
btnNewButton_1_2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textField_2.setText(String.valueOf(textField.getText().length()));
}
});
btnNewButton_1_2.setBounds(393, 235, 89, 23);
contentPane.add(btnNewButton_1_2);

JButton btnNewButton_1_3 = new JButton("Equality");


btnNewButton_1_3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {

textField_2.setText(textField.getText().equals(textField_1.getText())?"The Given
strings are equal":"The given Strings are not equal");
}
});
btnNewButton_1_3.setBounds(324, 298, 89, 23);
contentPane.add(btnNewButton_1_3);

JButton btnNewButton_1_4 = new JButton("Reverse");


btnNewButton_1_4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
StringBuilder b = new StringBuilder(textField.getText());
b.reverse();
textField_2.setText(String.valueOf(b));
}
});
btnNewButton_1_4.setBounds(179, 298, 89, 23);
contentPane.add(btnNewButton_1_4);

textField_3 = new JTextField();


textField_3.setColumns(10);
textField_3.setBounds(492, 63, 86, 20);
contentPane.add(textField_3);

JLabel lblNewLabel_1_1 = new JLabel("Index");


lblNewLabel_1_1.setBounds(448, 66, 34, 14);
contentPane.add(lblNewLabel_1_1);
}

}
Output:

Concatenation :
Sub String :

Length :
Reverse :

Equality :
Name : Akshad Jaiswal
Roll no. MC-I-47

18 Write a Java code to Read, Insert, Update and Delete any record from the
database.(Employee table).
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Scanner;

public class qu_18_Database_employee {

public static void main(String args[]) {


try {
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/assignment", "root",
"Vardhan@13");
Scanner S = new Scanner(System.in);
while(true) {
System.out.println("1.Insert\n2.Read\n3.Update\n4.Delete\nEnter Your
Choice: ");
int x = S.nextInt();
switch(x) {
// Insert
case 1:
System.out.println("id = ");
int id = S.nextInt();
System.out.println("name = ");
String name = S.next();
System.out.println("salary = ");
int sal = S.nextInt();

String q = "INSERT INTO Employee values(?,?,?)";


PreparedStatement ps = con.prepareStatement(q);
ps.setInt(1, id);
ps.setString(2, name);
ps.setInt(3, sal);
int r = ps.executeUpdate();
System.out.println((r > 0) ? "Data Inserted successfully" :
"Something went wrong");
break;

// Read
case 2:
q = "select id,fname,salary from Employee";
ps = con.prepareStatement(q);
ResultSet rs = ps.executeQuery();
System.out.println("\n");
while (rs.next()) {
System.out.println("Id: " + rs.getInt(1) + " Name: " +
rs.getString(2) + " Salary: " + rs.getInt(3));
}
System.out.println("\n");
break;

// Update
case 3:
System.out.println("id to update = ");
int id1 = S.nextInt();
System.out.println("new salary = ");
int sal1 = S.nextInt();

q = "Update Employee set salary=? where id = ?";


ps = con.prepareStatement(q);
ps.setInt(1, sal1);
ps.setInt(2, id1);

r = ps.executeUpdate();
System.out.println((r > 0) ? "Update was successfully preformed
changing employee id "+id1+"'s salary to "+sal1: "No Such id was Found");
break;

// Delete
case 4:
System.out.println("id to delete = ");
int id2 = S.nextInt();

q = "Delete from Employee where id =?";


ps = con.prepareStatement(q);
ps.setInt(1, id2);
r = ps.executeUpdate();
System.out.println((r > 0) ? "Employee with id "+id2+" was
deleted." : "No Such id was Found");
break;

case 5: System.exit(0);

default: System.out.println("Enter a valid choice");

}
}
} catch (Exception e) {
System.out.println(e);
}
}
}
Output :
Database Schema :

Execution :
Name : Akshad Jaiswal
Roll no. MC-I-47

19 Write a Java Servlet Application for login page with proper validations.
Web.xml :
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="https://jakarta.ee/xml/ns/jakartaee"
xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee
https://jakarta.ee/xml/ns/jakartaee/web-app_5_0.xsd"
id="WebApp_ID" version="5.0">

<welcome-file-list>
<welcome-file>newLogin.html</welcome-file>
</welcome-file-list>

<servlet>
<servlet-name>Login</servlet-name>
<servlet-class>com.reserva.backend.newLoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Login</servlet-name>
<url-pattern>/userLogin</url-pattern>
</servlet-mapping>

</web-app>

Login.html :
<!DOCTYPE html>
<html>

<head>
<meta charset="UTF-8">
<title>Login page</title>
<style>
body {
display: flex;
justify-content: center;
align-items: center;
height: 97vh;
width: 100%;
}
#body {
display: flex;
flex-direction: column;
}

#submit,
#reset {
width: 100px;
align-self: center;
margin-bottom: 10px;
}
</style>
</head>

<body>
<form action="userLogin" method="post">
<div id="header">
<h1>Welcome To Login Page</h1>
</div>

<div id="body">

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


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

<input type="submit" id="submit"><input type="reset" id="reset">


</div>

</form>
</body>

</html>

Login Servlet :
import java.io.IOException;
import java.io.PrintWriter;
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("/userLogin")
public class newLoginServlet extends HttpServlet {

private static final long serialVersionUID = 1L;


final String umail ="xyz@gmail.com";
final String pwd= "1234";

protected void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {

PrintWriter out = response.getWriter();


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

out.print((umail.equals(email) && pwd.equals(pass))?"Welcome to the site


!":"Wrong email or password");

}
}
Output :

Validations :
Login Fail :

Successful Login :

Result :
Name : Akshad Jaiswal
Roll no. MC-I-47

20 Write a Java program to design Registration page using JSP


Register.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Register</title>
</head>
<body>
<form action=http://localhost:8080/Register/register.jsp>
<h2>REGISTERATION PAGE:</h2><br>
Email: <input type=email name=email required><br>
Password: <input type=password name=pass required><br>
<input type=submit value=LOGIN>
</form>

</body>
</html>
Register.jsp
<%@page import="java.util.*,java.text.*,java.sql.*"%>
<%

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


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

try{

Connection con;
Statement st;
ResultSet rs;

Class.forName("org.postgresql.Driver");
con=DriverManager.getConnection("jdbc:postgresql:te512","postgres","");

st=con.createStatement();

rs= st.executeQuery("select * from login where email='"+email+"'");

if(!rs.next()){ //if no such email is already present

st.executeUpdate("insert into login values('"+email+"','"+pass+"')");


out.println("Registeration Successfull! ");

}else{ //if there is already same email in dB


out.println("Registeration Failed! <br> The Email entered Already Exists!!");
}
out.println("<br><br>Email:"+email+"<br>Password:"+pass);
} catch(Exception e){
out.println("Some eXCEPTION Occured"+e);
}

%>

Output :

You might also like