Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
40 views

JAVA PROGRAMMING LAB MANUAl

Here are the key points about access specifiers in Java: - Access specifiers determine the accessibility (visibility) of classes, methods, and other members. - The four access specifiers are: public, private, protected, and the default access level (no specifier). - Public members are accessible from anywhere. Private members are only accessible within the same class. Protected is accessible within the same package and subclasses. Default is accessible only within the same package. - Inheritance respects access levels - protected and public members of the parent class can be accessed in child classes, private cannot. - A program demonstrates the access specifiers by defining members with different access levels (private field, public field, default

Uploaded by

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

JAVA PROGRAMMING LAB MANUAl

Here are the key points about access specifiers in Java: - Access specifiers determine the accessibility (visibility) of classes, methods, and other members. - The four access specifiers are: public, private, protected, and the default access level (no specifier). - Public members are accessible from anywhere. Private members are only accessible within the same class. Protected is accessible within the same package and subclasses. Default is accessible only within the same package. - Inheritance respects access levels - protected and public members of the parent class can be accessed in child classes, private cannot. - A program demonstrates the access specifiers by defining members with different access levels (private field, public field, default

Uploaded by

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

G. B.

PANT INSTITUTE OF ENGINEERING & TECHNOLOGY

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

LAB MANUAL

SUBJECT NAME : JAVA PROGRAMMING LAB


SUBJECT CODE : PCS-353
YEAR/SEM : 3rd/Vth
BRANCH : CSE
SESSION : 2022-23

1
PCS-353 JAVA PROGRAMMING LAB L T P
Total Contact Hours - 20 0 0 2
Prerequisite –Fundamentals of Computing and Programming, Object
OrientedProgramming Using C++
Lab Manual Designed by – Dept. of Computer Science and Engineering.
OBJECTIVES
The main objective of this lab manual is to develop Core Java Programming Concepts.
COURSE OUTCOMES (COs)
CO1 Develop programs using object oriented concepts using arrays and string classes.

CO2 Demonstrate features such as Inheritance, Interfaces with access specifiers and
exception handling

CO3 Demonstrate multithreading programming concepts to solve real world problems


CO4 Design and implement GUI based applications.
CO5 Develop web application using JDBC and Servlets .

MAPPING BETWEEN COURSE OUTCOMES & PROGRAM


OUTCOMES (3/2/1 INDICATES STRENGTH OF CORRELATION) 3-
High, 2- Medium, 1-Low
COs PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12 PSO1 PSO2
CO1 3 1 3 2 3 - - - - - 2 3 3 2
CO2 3 1 3 2 3 - - - - - 2 3 3 2
CO3 3 1 3 2 3 - - - - - 2 3 3 2
CO4 3 1 3 2 3 - - - - - 2 3 3 2
CO5 3 1 3 2 3 - - - - - 2 3 3 2

2
LIST OF EXPERIMENTS
1. Write a program to implement matrix multiplication using multi-dimensional arrays.
2. Write a program to implement all String class functionalities.
3. Write a program to demonstrate the working of access specifiers in Inheritance.
4. Develop a program for banking application with exception handling. Handle the exceptions in following
cases:
a) Account balance <1000
b) Withdrawal amount is greater than balance amount
c) Transaction count exceeds 3
d) One day transaction exceeds 1 lakh.
5. Write a program to implement Thread class and runnable interface.
6. Write a program to implement producer-consumer problem using Inter threaded communication
7. Write a program to demonstrate the usage of event handling.
8. Write a program to depict all the cases of layout manager.
9. Create a Student database and store the details of the students in a table. Perform the SELECT, INSERT,
UPDATE and DELETE operations using JDBC connectivity.
10. Write an RMI application to fetch the stored procedure from the remote server side.
11. Design a login page using servlets and validate the username and password by comparing the details
stored in the database.

3
1-Write a program to implement matrix multiplication using multi-dimensional
arrays.
Ans –
Code
import java.util.Scanner;

class MatixMulti
{
public static void main(String args[])
{
int n;
Scanner input = new Scanner(System.in);
System.out.println("Enter the number of rows and columns of the matrices.");
n = input.nextInt();
int[][] a = new int[n][n];
int[][] b = new int[n][n];
int[][] c = new int[n][n];
System.out.println("Enter the numbers of the first matrix. Numbers will be added row wise \n");
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
a[i][j] = input.nextInt();
}
}
System.out.println("Enter the numbers of the 2nd matrix. Numbers will be added row wise. \n");
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
4
{
b[i][j] = input.nextInt();
}
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
for (int k = 0; k < n; k++)
{
c[i][j] = c[i][j] + a[i][k] * b[k][j];
}
}
}
System.out.println("The product of the matrices is shown as below");
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
System.out.print(c[i][j] + " ");
}
System.out.println();
}
}
}

OUTPUT

5
6
2. Write a program to implement all String class functionalities.
Ans – String is a sequence of characters, for e.g. “Hello” is a string of 5 characters. In java, string is an
immutable object which means it is constant and can cannot be changed once it has been created.
import java.io.*;
import java.util.*;
class Test
{
public static void main (String[] args)
{
String s= "GBPIET";
// or String s= new String ("GBPIET");

// Returns the number of characters in the String.


System.out.println("String length = " + s.length());

// Returns the character at ith index.


System.out.println("Character at 3rd position = "
+ s.charAt(3));

// Return the substring from the ith index character


// to end of string
System.out.println("Substring " + s.substring(3));

// Returns the substring from i to j-1 index.


System.out.println("Substring = " + s.substring(1,4));

// Concatenates string2 to the end of string1.


String s1 = "Pauri";
String s2 = "Garhwal";
System.out.println("Concatenated string = " +
s1.concat(s2));

// Returns the index within the string


// of the first occurrence of the specified string.
String s4 = "Learn Share Learn";
System.out.println("Index of Share " +
s4.indexOf("Share"));

// Returns the index within the string of the


// first occurrence of the specified string,
// starting at the specified index.
System.out.println("Index of a = " +
s4.indexOf('a',3));

// Checking equality of Strings


Boolean out = "GBPIET".equals("gbpiet");
7
System.out.println("Checking Equality " + out);
out = "GBPIET".equals("GBPIET");
System.out.println("Checking Equality " + out);

out = "GBpiet".equalsIgnoreCase("gbPIet");
System.out.println("Checking Equality " + out);

//If ASCII difference is zero then the two strings are similar
int out1 = s1.compareTo(s2);
System.out.println("the difference between ASCII value is="+out1);
// Converting cases
String word1 = "SacHin";
System.out.println("Changing to lower Case " +
word1.toLowerCase());

// Converting cases
String word2 = "gbpiet";
System.out.println("Changing to UPPER Case " +
word2.toUpperCase());

// Trimming the word


String word4 = " Learn Share Learn ";
System.out.println("Trim the word " + word4.trim());

// Replacing characters
String str1 = "Heppo";
System.out.println("Original String " + str1);
String str2 = "feeksforfeeks".replace('p' ,'l') ;
System.out.println("Replaced p with l -> " + str2);
}
}

Output-
String length = 6
Character at 3rd position = I
Substring IET
Substring = BPI
Concatenated string = PauriGarhwal
Index of Share 6
Index of a = 8
Checking Equality false
Checking Equality true
Checking Equality true
the difference between ASCII value is=9
Changing to lower Case sachin
Changing to UPPER Case GBPIET
Trim the word Learn Share Learn
Original String Heppo
8
Replaced p with l -> hello

9
3- Write a program to demonstrate the working of access specifiers in Inheritance.
Ans –
The keywords that define the access scope is known as access specifier.
Access specifier or modifier is the access type of the method.
It specifies the visibility of the method. Java provides four types of access specifier:
o Public: The method is accessible by all classes when we use public specifier in our application.
o Private: When we use a private access specifier, the method is accessible only in the classes in which
it is defined.
o Protected: When we use protected access specifier, the method is accessible within the same package
or subclasses in a different package.
o Default: When we do not use any access specifier in the method declaration, Java uses default access
specifier by default. It is visible only from the same package only.

import java.io.*;
import java.util.*;
public class Test{

void display(){ //default method


System.out.println("hi");
}

private int sum; //Private Access Specifier

public String name = "JAVA"; //Public Access Specifier

protected void sum(int x,int y){ //Protected Access specifier


s=x+y;
System.out.println(s);
}
}

public class Class2 extends Test{


public static void main(String[] args){
Test t1=new Class2();
t1.display();
t1.sum(10,10);
System.out.println(t1.name);

10
}
}

OUTPUT
hi
20
JAVA

11
4. Develop a program for banking application with exception handling. Handle the exceptions in following
cases:
a) Account balance <1000

Code
Bank.java

public class Bank {


public static void main(String [] args) {
CheckingAccount c = new CheckingAccount(101);

try {
System.out.println("Depositing 200...");
c.deposit(200.00);
}catch(InsufficientBalanceException e) {
System.out.println("Your Acoount has low balance, it is short by "+e.getAmount());
e.printStackTrace();
}
}}

CheckingAccount.java

import java.io.*;
public class CheckingAccount {
private double balance;
private int number;
public CheckingAccount(int number) {
this.number = number;
}
12
public void deposit(double amount) throws InsufficientBalanceException{
balance += amount;
if(balance<1000.00)
throw new InsufficientBalanceException(1000.00-balance);
}
public double getBalance() {
return balance;
}
public int getNumber() {
return number;
}
}

InsufficientBalanceException.java
import java.io.*;
public class InsufficientBalanceException extends Exception {
private double amount;

public InsufficientBalanceException(double amount) {


this.amount=amount;
}
public double getAmount() {
return amount;
}
}

OUTPUT

13
b) Withdrawal amount is greater than balance amount

Code
Bank.java

public class Bank {


public static void main(String [] args) {
CheckingAccount c = new CheckingAccount(101);
System.out.println("Depositing 2000...");
c.deposit(2000.00);
try {
System.out.println("\nWithdrawing 500...");
c.withdraw(500.00);
System.out.println("\nWithdrawing 600...");
c.withdraw(600.00);
System.out.println("\nWithdrawing 1000...");
c.withdraw(1000.00);
}catch(InsufficientFundsException e) {
System.out.println("Sorry, but you are short money by "+e.getAmount());
e.printStackTrace();
}
}}

CheckingAccount.java

import java.io.*;
public class CheckingAccount {
private double balance;
private int number;
public CheckingAccount(int number) {
14
this.number = number;
}

public void deposit(double amount) {


balance += amount;
}

public void withdraw(double amount) throws InsufficientFundsException


{
if(amount <= balance)
{
balance -= amount;
}else
{
double needs = amount - balance;
throw new InsufficientFundsException(needs);
}}

public double getBalance() {


return balance;
}

public int getNumber() {


return number;
}
}

InsufficientFundsException.java

import java.io.*;

15
public class InsufficientFundsException extends Exception {
private double amount;

public InsufficientFundsException (double amount) {


this.amount=amount;
}

public double getAmount() {


return amount;
}
}

OUTPUT

c) Transaction count exceeds 3

Code
Bank.java
public class Bank {

16
public static void main(String [] args) {
CheckingAccount c = new CheckingAccount(101);
System.out.println("Depositing 4000...");
c.deposit(4000.00);
try {
System.out.println("\nWithdrawing 500...");
c.withdraw(500.00);
System.out.println("\nWithdrawing 500...");
c.withdraw(500.00);
System.out.println("\nWithdrawing 500...");
c.withdraw(500.00);
System.out.println("\nWithdrawing 500...");
c.withdraw(500.00);
}catch(TransactioncountException e) {
System.out.println("Your Transactions limit exeded ");
e.printStackTrace();
}
}}

CheckingAccount.java
import java.io.*;
public class CheckingAccount {
private double balance;
private int number;
int count=0;
public CheckingAccount(int number) {
this.number = number;
}

17
public void deposit(double amount) {
count++;
balance += amount;
}

public void withdraw(double amount) throws TransactioncountException {


count++;
if(count>3) {
throw new TransactioncountException();
}
}

public double getBalance() {


return balance;
}
public int getNumber() {
return number;
}
}

TransactioncountException.java

import java.io.*;
public class TransactioncountException extends Exception {
private double amount;

public TransactioncountException () {
}

public double getAmount() {


18
return amount;
}
}

OUTPUT

d) One day transaction exceeds 1 lakh.


Code
Bank.java
public class Bank {
public static void main(String [] args) {
CheckingAccount c = new CheckingAccount(101);
System.out.println("Depositing 200000...");
c.deposit(200000.00);
try {
System.out.println("\nWithdrawing 50000...");
c.withdraw(50000.00);
System.out.println("\nWithdrawing 50000...");
c.withdraw(50000.00);

19
System.out.println("\nWithdrawing 5000...");
c.withdraw(5000.00);
System.out.println("\nWithdrawing 500...");
c.withdraw(500.00);
}catch(OneDayTransactionException e) {
System.out.println("Your One Day Transactions exeded ");
e.printStackTrace();
}
}}

CheckingAccount.java
import java.io.*;
public class CheckingAccount {
private double balance;
private int number;
double transaction=0.0;
public CheckingAccount(int number) {
this.number = number;
}

public void deposit(double amount) {


balance += amount;
}

public void withdraw(double amount) throws OneDayTransactionException {


transaction=transaction+amount;
if(transaction>100000) {
throw new OneDayTransactionException();
}
}

public double getBalance() {


return balance;
20
}

public int getNumber() {


return number;
}
}

OneDayTransactionException.java

import java.io.*;
public class OneDayTransactionException extends Exception {
private double amount;

public OneDayTransactionException() {
}

public double getAmount() {


return amount;
}
}

OUTPUT

21
5. Write a program to implement Thread class and runnable interface.
Ans –
1) Java Thread Example by extending Thread class:
class Multi extends Thread{
public void run(){
System.out.println("thread is running...");
}
public static void main(String args[]){
Multi t1=new Multi();
t1.start(); SS
}
}
Output: thread is running..

2) Java Thread Example by implementing Runnable interface


class Multi3 implements Runnable{
public void run(){
System.out.println("thread is running...");
}
public static void main(String args[]){
Multi3 m1=new Multi3();
Thread t1 =new Thread(m1);
t1.start();
}
}
Output: thread is running...

22
6. Write a program to implement producer-consumer problem using Inter threaded
communication
CODE

//Producer and consumer problem


class Program
{
public static void main(String ar[])
{
Q q= new Q();
new Producer(q);
new Consumer(q);
}
}
class Producer implements Runnable
{
Q q;
Producer(Q q)
{
this.q =q;
new Thread(this," producer").start();
}
public void run()
{
int i= 0;
while(true)
{
q.put(i++);
if(i== 5)
System.exit(0);
}
}
23
}
class Consumer implements Runnable
{
Q q;
Consumer(Q q)
{
this.q= q;
new Thread(this, "consumer").start();
}
public void run()
{
while(true)
q.get();
}
}

class Q
{
int n;
boolean valueset= false;
synchronized int get()
{
while(!valueset)
{
try
{
wait();
}
catch(Exception e)
{
}
}
System.out.println("GET " +n);
24
valueset= false;
notify();
return n;
}
synchronized void put(int n)
{
while(valueset)
{
try
{
wait();
}
catch(Exception e)
{
}
}
this.n= n;
valueset =true;
System.out.println("PUT " +n);
notify();
}
}

OUTPUT

25
7. Write a program to demonstrate the usage of event handling.
Ans –
Changing the state of an object is known as an event. For example, click on button, dragging mouse etc.
The java.awt.event package provides many event classes and Listener interfaces for event handling.
CODE

import java.awt.*;
import java.awt.event.*;
class AEvent extends Frame implements ActionListener{
TextField tf;
AEvent(){

//create components
tf=new TextField();
tf.setBounds(60,50,170,20);
Button b=new Button("click me");
b.setBounds(100,120,80,30);

//register listener
b.addActionListener(this);//passing current instance

//add components and set size, layout and visibility


add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e){
tf.setText("Welcome");
26
}
public static void main(String args[]){
new AEvent();
}
}
OUTPUT

27
8. Write a program to depict all the cases of layout manager.
Ans-
A layout manager is an object that controls the size and position of the components in the container. Every container
object has a layout manager object that controls its layout.

Actually, layout managers are used to arrange the components in a specific manner. It is an interface that is
implemented by all the classes of layout managers. There are some classes that represent the layout managers.

There are the following classes that represent the layout managers:
1. java.awt.BorderLayout
2. java.awt.FlowLayout
3. java.awt.GridLayout

Border Layout Manager


In the Border Layout Manager, the components are positioned in five different areas (regions).
In other words, North, South, East, West and Center. Each region may contain only one component.
If you enlarge the window, you will notice that the center area gets as much of the newly available space, as
possible. The other area will expand, only as much as necessary, to keep the available space filled.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Border extends JFrame
implements ActionListener {
private JButton b[];
private String names[] = {
"Hide North Border",
"Hide South Border",
"Hide East Border",
"Hide West Border",
"Hide Center Border"
};
private BorderLayout layout;
public Border() {
28
super("BorderLayout");
layout = new BorderLayout(5, 5);
Container c = getContentPane();
c.setLayout(layout);
b = new JButton[names.length];
for (int i = 0; i < names.length; i++) {
b[i] = new JButton(names[i]);
b[i].addActionListener(this);
}
c.add(b[0], BorderLayout.NORTH);
c.add(b[1], BorderLayout.SOUTH);
c.add(b[2], BorderLayout.EAST);
c.add(b[3], BorderLayout.WEST);
c.add(b[4], BorderLayout.CENTER);
setSize(400, 300);
show();
}
public void actionPerformed(ActionEvent e) {
for (int i = 0; i < b.length; i++)
if (e.getSource() == b[i])
b[i].setVisible(false);
else
b[i].setVisible(true);
layout.layoutContainer(getContentPane());
}
public static void main(String args[]) {
Border bord = new Border();
bord.addWindowListener(new WindowAdapter() {

29
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
}

OUTPUT

Grid Layout Manager

Grid Layout is used to place the components in a grid of cells (rectangular). Each component takes the
available space within its cell. Each cell, has exactly the same size and displays only one component. If the
Grid Layout window is expanded, the Grid Layout changes the cell size, so that the cells are as large as
possible.
In other words, the layout manager divides the container into a grid, so that components can be placed in
rows and columns. Each component will have the same width and height. The components are added to
the grid starting at the top-left cell and proceeding left-to-right, until the row is full. Then go to the next
row. This type of layout is known as, the Grid Layout Manager.

import java.awt.*;

30
import java.awt.event.*;
import javax.swing.*;
public class Grid extends JFrame implements ActionListener {
private JButton b[];
private String names[] = {
"Contacts",
"Message",
"Call Log",
"Games",
"Settings",
"Applications",
"Music",
"Gallery",
"Organiser"
};
private boolean toggle = true;
private Container c;
private GridLayout grid1, grid2, grid3;
public Grid() {
super("GridLayout");
grid1 = new GridLayout(2, 3, 5, 5);
grid2 = new GridLayout(3, 2);
grid3 = new GridLayout(3, 5);
c = getContentPane();
c.setLayout(grid3);
b = new JButton[names.length];
for (int i = 0; i < names.length; i++) {
b[i] = new JButton(names[i]);
b[i].addActionListener(this);
c.add(b[i]);
}
setSize(400, 400);
show();
}
public void actionPerformed(ActionEvent e) {
if (toggle)
c.setLayout(grid3);
else if (toggle)
c.setLayout(grid2);
else
c.setLayout(grid1);
toggle = !toggle;
c.validate();
}
public static void main(String args[]) {
Grid G = new Grid();
G.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
31
}
});
}
}

OUTPUT

Flow Layout manager

The flow layout, is the most basic layout manager in which components are placed from left to right, as
they were added. When the horizontal row is too small, to put all the components in one row, then it uses
multiple rows. You can align the components left, right, or center (default).
import java.awt.*;
import javax.swing.*;
public class Flow {
Frame f;
public Flow() {
f = new Frame();
Button b1 = new Button("Red");
JButton b2 = new JButton("Green");
JButton b3 = new JButton("Yellow");
JButton b4 = new JButton("Purple");
JButton b5 = new JButton("Blue");
JButton b6 = new JButton("Pink");
JButton b7 = new JButton("Brown");
f.add(b1);
f.add(b2);
32
f.add(b3);
f.add(b4);
f.add(b5);
f.add(b6);
f.add(b7);
f.setLayout(new FlowLayout(FlowLayout.LEFT));
f.setSize(400, 200);
f.setVisible(true);
}
public static void main(String[] args) {
new Flow();
}
}

OUTPUT:-

33
9-Create a Student database and store the details of the students in a table. Perform
the SELECT, INSERT, UPDATE and DELETE operations using JDBC connectivity.
Ans-

import java.sql.*;
class StudentRecord
{
public static final String DBURL = "jdbc:oracle:thin:@localhost:1521:XE";
public static final String DBUSER = "local";
public static final String DBPASS = "test";
public static void main(String args[])
{
try
{
//Loading the driver
Class.forName("oracle.jdbc.driver.OracleDriver");
//Cretae the connection object
Connection con = DriverManager.getConnection(DBURL, DBUSER, DBPASS);
//Insert the record
String sql = "INSERT INTO emp (student_id, studentname, email, city) VALUES
(?, ?, ?, ?)";
PreparedStatement statement = con.prepareStatement(sql);
statement.setInt(1, 100);
statement.setString(2, "Prashant");
statement.setString(3, "prasant@saxena.com");
statement.setString(4, "Pune");

int rowsInserted = statement.executeUpdate();


if (rowsInserted > 0)
{
System.out.println("A new Student was inserted successfully!\n");
}
// Display the record
String sql1 = "SELECT * FROM Student";
Statement stmt = con.createStatement();
ResultSet result = stmt.executeQuery(sql1);

while (result.next())
{
System.out.println (result.getInt(1)+" "+
result.getString(2)+" "+
result.getString(3)+" "+
result.getString(4));
}

//Update the record

34
String sql2 = "Update Student set email = ? where studentname = ?";
PreparedStatement pstmt = con.prepareStatement(sql2);
pstmt.setString(1, "Jaya@gmail.com");
pstmt.setString(2, "Jaya");
int rowUpdate = pstmt.executeUpdate();
if (rowUpdate > 0)
{
System.out.println("\nRecord updated successfully!!\n");
}

//Delete the record


String sql3 = "DELETE FROM Student WHERE studentname=?";
PreparedStatement statement1 = con.prepareStatement(sql3);
statement1.setString(1, "Prashant");

int rowsDeleted = statement1.executeUpdate();


if (rowsDeleted > 0)
{
System.out.println("A Student was deleted successfully!\n");
}
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
}

35
10. Write an RMI application to fetch the stored procedure from the remote server
side.
Ans –

The RMI (Remote Method Invocation) is an API that provides a mechanism to create distributed
application in java. The RMI allows an object to invoke methods on an object running in another JVM.The
RMI provides remote communication between the applications using two objects stub and skeleton.

PROGRAMS: -

1)REMOTE INTERFACE: -

import java.rmi.Remote;
import java.rmi.RemoteException;

// Creating Remote interface for our application


public interface Hello extends Remote {
void printMsg() throws RemoteException;
}

2)REMOTE OBJECT: -

// Implementing the remote interface


public class ImplExample implements Hello {

// Implementing the interface method


public void printMsg() {
System.out.println("This is an example RMI program");
}
}

3) SERVER PROGRAM: -

import java.rmi.registry.Registry;
import java.rmi.registry.LocateRegistry;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;

public class Server extends ImplExample {


public Server() {}
public static void main(String args[]) {
try {
// Instantiating the implementation class
ImplExample obj = new ImplExample();

// Exporting the object of implementation class


// (here we are exporting the remote object to the stub)
Hello stub = (Hello) UnicastRemoteObject.exportObject(obj, 0);

// Binding the remote object (stub) in the registry


Registry registry = LocateRegistry.getRegistry();

36
registry.bind("Hello", stub);
System.err.println("Server ready");
} catch (Exception e) {
System.err.println("Server exception: " + e.toString());
e.printStackTrace();
}
}
}

4)CLIENT PROGRAM: -

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

public class Client {


private Client() {}
public static void main(String[] args) {
try {
// Getting the registry
Registry registry = LocateRegistry.getRegistry(null);

// Looking up the registry for the remote object


Hello stub = (Hello) registry.lookup("Hello");

// Calling the remote method using the obtained object


stub.printMsg();

// System.out.println("Remote method invoked");


} catch (Exception e) {
System.err.println("Client exception: " + e.toString());
e.printStackTrace();
}
}
}

STEP1: -START THE rmiregistry: -

37
STEP2: -START THE SERVER: -

STEP3: -START THE CLIENT: -

38
11. Design a login page using servlets and validate the username and password by
comparing the details stored in the database.
Ans –
JAVA CODE

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {

private static final long serialVersionUID = 1L;

public LoginServlet() {
super();
// TODO Auto-generated constructor stub
}

// From login.jsp, as a post method only the credentials are passed


// Hence the parameters should match both in jsp and servlet and
// then only values are retrieved properly
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// We can able to get the form data by means of the below ways.
// Form arguments should be matched and then only they are recognised
// login.jsp component names should match and then only
// by using request.getParameter, it is matched
String emailId = request.getParameter("emailId");
String password = request.getParameter("password");
// To verify whether entered data is printing correctly or not
System.out.println("emailId.." + emailId);
System.out.println("password.." + password);
// Here the business validations goes. As a sample,
// we can check against a hardcoded value or pass
// the values into a database which can be available in local/remote db
// For easier way, let us check against a hardcoded value
if (emailId != null && emailId.equalsIgnoreCase("admin@gmail.com") &&
password != null && password.equalsIgnoreCase("admin")) {
// We can redirect the page to a welcome page
39
// Need to pass the values in session in order
// to carry forward that one to next pages
HttpSession httpSession = request.getSession();
// By setting the variable in session, it can be forwarded
httpSession.setAttribute("emailId", emailId);
request.getRequestDispatcher("welcome.jsp").forward(request, response);
}
}
}

HTML CODE

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


pageEncoding="ISO-8859-1"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Login Application</title>
<meta name="viewport" content="width=device-width, initial-scale=1">

<!-- css related code which we can have either in


same jsp or separately also in a css file -->
<style>
body {font-family: Arial, Helvetica, sans-serif;}
form {border: 3px solid #f1f1f1;}

input[type=text], input[type=password] {
width: 100%;
padding: 12px 20px;
margin: 8px 0;
display: inline-block;
border: 1px solid #ccc;
box-sizing: border-box;
}

button {
background-color: #04AA6D;
color: white;
padding: 14px 20px;
margin: 8px 0;
border: none;
cursor: pointer;
width: 100%;
}

button:hover {

40
opacity: 0.8;
}

.cancelbutton {
width: auto;
padding: 10px 18px;
background-color: #f44336;
}

.container {
padding: 16px;
}

span.psw {
float: right;
padding-top: 16px;
}

/* Change styles for span and cancel button


on extra small screens */
@media screen and (max-width: 300px) {
span.psw {
display: block;
float: none;
}
.cancelbutton {
width: 100%;
}
}
</style>

<!-- End of css related code which we can have either in


same jsp or separately also in a css file -->

<!-- Client side validations that need to be handled in javascript,


it can be handled in separate file or in same jsp -->
<script type="text/javascript">
function ValidateEmail(emailId)
{
var mailformat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if(emailId.value.match(mailformat))
{
document.getElementById('password').focus();
return true;
}
else
{
41
alert("You have entered an invalid email address!");
document.getElementById('emailId').focus();
return false;
}
}
</script>

<!-- End of client side validations that need to be handled


in javascript, it can be handled in separate file or in same jsp -->
</head>
<body>

<!-- We should have a servlet in order to process the form in


server side and proceed further -->
<form action="loginServlet" method="post"
onclick="ValidateEmail(document.getElementById('emailId'))">
<div class="container">
<label for="username"><b>Email</b></label>
<input type="text" placeholder="Please enter your email" name="emailId" id =
"emailId" required>

<label for="password"><b>Password</b></label>
<input type="password" placeholder="Please enter Password" name="password"
id="password" required>

<button type="submit">Login</button>
<label>
<input type="checkbox" checked="checked" name="rememberme"> Remember me
</label>
</div>

<div class="container" style="background-color:#f1f1f1">


<button type="button" class="cancelbutton">Cancel</button>
<span class="psw">Forgot <a
href="<%=request.getContextPath()%>/forgotpassword.jsp">password?</ a></span>
</div>
</form>
</body>
</html>

42
OUTPUT

43

You might also like