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

Java Manual

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 views36 pages

Java Manual

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
You are on page 1/ 36

LAB MANUAL

Subject: Advanced Java Programming

Class: TE E&TC Semester – 2

(Academic Year: 2021-22)

Prepared By:
Mr. Shrikrishna U. Kolhar
Assistant Professor
Department of Electronics and Telecommunication Engineering.

Vidya Pratishthan’s
Kamalnayan Bajaj Institute of Engineering and Technology,
Baramati
List of Experiments
1 Write a program to demonstrate status of key on an Applet window such as
KeyPressed, KeyReleased, KeyUp, KeyDown.
2 Write a program to create a frame using AWT. Implement mouseClicked,
mouseEntered() and mouseExited() events. Frame should become visible when
the mouse enters it.
3 Develop a GUI which accepts the information regarding the marks for all the
subjects of a student in the examination. Display the result for a student in a
separate window.
4 Write a program to insert and retrieve the data from the database using JDBC.
5 Develop an RMI application which accepts a string or a number and checks that
string or number is palindrome or not.
6 Write a program to demonstrate the use of InetAddress class and its factory
methods.
7 Write program with suitable example to develop your remote interface, implement
your RMI server, implement application that create your server, also develop
security policy file.
8 Write a database application that uses any JDBC driver.
9 Create a simple calculator application using servlet.
10 Create a registration servlet in Java using JDBC. Accept the details such as
Username, Password, Email, and Country from the user using HTML Form and
store the registration details in the database
Program No: 1
Program Statement: Write a program to demonstrate status of key on an Applet window such
as KeyPressed, KeyReleased, KeyUp, KeyDown.

Theory: Write in 4-5 lines


What is Applet in Java?
What is event handling? Write an example

Program:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="SimpleKey" width=300 height=100>
</applet>
*/
public class SimpleKey extends Applet implements KeyListener
{
String msg = "";
int X = 10, Y = 20; // output coordinates

public void init()


{
addKeyListener(this);
}
public void keyPressed(KeyEvent k)
{
showStatus("Key Down");
int key = k.getKeyCode();

switch(key)
{
case KeyEvent.VK_F1:
msg = msg + "F1";
break;
case KeyEvent.VK_F2:
msg = msg + "F2";
break;
case KeyEvent.VK_F3:
msg = msg + "F3";
break;
case KeyEvent.VK_F4:
msg = msg + "F4 ";
break;
case KeyEvent.VK_RIGHT:
msg = msg + "RIGHT ";
break;
case KeyEvent.VK_LEFT:
msg = msg + "LEFT ";
break;
case KeyEvent.VK_UP:
msg = msg + "UP ";
break;
case KeyEvent.VK_DOWN:
msg = msg + "DOWN ";
break;

}
repaint();
}
public void keyReleased(KeyEvent ke)
{
showStatus("Key Up");
}
public void keyTyped(KeyEvent ke)
{
msg += ke.getKeyChar();
repaint();
}
// Display keystrokes.
public void paint(Graphics g)
{
g.drawString(msg, X, Y);
}
}

Post-lab questions:
1. Identify the name of listener interface used in above program
2. Which command is used for registering listener in the above program?
3. Identify the name of event class
4. Name the methods used for handling event in above program
Program No: 2
Program Statement: Write a program to create a frame using AWT. Implement
mouseClicked, mouseEntered() and mouseExited() events. Frame should become visible
when the mouse enters it.

Theory: Write in 4-5 lines


What is GUI in Java?
Explain use of Frame class with its constructors.

Program:
/**** Mouse_Exp2.java ****/
// Program we want to check events like Mouse click, mouse entered and
mouse exited
import java.awt.*;
import java.awt.event.*;

public class Mouse_Exp2 extends Frame implements MouseListener {


Label l;
Mouse_Exp2() {
super("AWT Frame");
l = new Label();
l.setBounds(25, 60, 250, 30);
l.setAlignment(Label.CENTER);
this.add(l);
this.setSize(300, 300);
this.setLayout(null);
this.setVisible(true);
this.addMouseListener(this);

this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
dispose();
}
});
}
public static void main(String[] args) {
new Mouse_Exp2();
}
@Override
public void mouseClicked(MouseEvent e) {
l.setText("Mouse Clicked");
}
@Override
public void mousePressed(MouseEvent e) {
}
@Override
public void mouseReleased(MouseEvent e) {
}
@Override
public void mouseEntered(MouseEvent e) {
l.setText("Mouse Entered");
}

@Override
public void mouseExited(MouseEvent e) {
l.setText("Mouse Exited");
}
}

Post-lab questions:
1. How to identify that above program is a GUI program?
2. Identify the name of listener interface used in above program
3. Which command is used for registering listener in the above program?
4. Identify the name of event class
5. Name the methods used for handling event in above program
Program No: 3
Program Statement: Develop a GUI which accepts the information regarding the marks for
all the subjects of a student in the examination. Display the result for a student in a separate
window.

Theory:
If you want to accept marks for 3 subjects of a student and after clicking on submit a
new window will pop-up to display overall result
Which component classes are required for creating above GUI?
Draw GUI here.
Program:
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class ReportCard extends JFrame{


JPanel jp = new JPanel();
JLabel lname = new JLabel();
JButton bsubmit = new JButton("Submit");
JTextField tname = new JTextField(20);
JLabel lMath = new JLabel();
JTextField tMath = new JTextField(20);
JLabel lScience = new JLabel();
JTextField tScience = new JTextField(20);
JLabel lEnglish = new JLabel();
JTextField tEnglish = new JTextField(20);

public ReportCard()
{
lname.setText("Enter Name");
jp.add(lname);
jp.add(tname);
lMath.setText("Enter Math Marks");
jp.add(lMath);
jp.add(tMath);
lScience.setText("Enter Science Marks");
jp.add(lScience);
jp.add(tScience);
lEnglish.setText("Enter English Marks");
jp.add(lEnglish);
jp.add(tEnglish);
jp.add(bsubmit);
add(jp);
bsubmit.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
String val = tname.getText();
JLabel l1 = new JLabel("Welcome "+val);
int sub1 = Integer.parseInt(tMath.getText());
int sub2 = Integer.parseInt(tScience.getText());
int sub3 = Integer.parseInt(tEnglish.getText());
int sum = sub1+sub2+sub3;
float average = sum/3;
JLabel l2 = new JLabel("Average "+ average);
JPanel jip = new JPanel();
jip.add(l1);
jip.add(l2);
JFrame inf = new JFrame();
inf.setVisible(true);
inf.add(jip);
inf.setSize(300, 100);
}

});

public static void main(String[] args) {


ReportCard rc = new ReportCard();
rc.setSize(300, 200);
rc.setVisible(true);
}
}

Post-lab Questions:
1. Identify component classes used in above program.
2. Which event and listener used in the program?
3. What is the use of integer.parseInt() method?
Program No: 4
Program Statement: Write a program to insert and retrieve the data from the database using
JDBC.

Theory:
What is JDBC and what is the use of it? (https://www.javatpoint.com/java-jdbc)
Write 5 steps for JDBC connectivity (https://www.javatpoint.com/steps-to-connect-to-the-
database-in-java)

VLAB Link: http://vlabs.iitb.ac.in/vlabs-


dev/vlab_bootcamp/bootcamp/bots_with_dots/labs/exp1/index.html

Program:
1. Program to display the contents of the table
import java.sql.*;
// User class
public class SQLStatementSelect{

public static void main(String args[]){


try{
Class.forName("com.mysql.jdbc.Driver"); // register the driver class
Connection con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/xyz?characterEncoding=latin1","root","root");

Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from pqr");
while(rs.next())
//System.out.println("Success");
System.out.println(rs.getString(1)+" "+rs.getString(2)+"
"+rs.getString(3));
con.close();
}catch(Exception e){
System.out.println(e);}
}
}
2. Program to insert new record into the table
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;

public class SQLPreparedStatementInsert{

public static void main(String[] args) {


try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection(

"jdbc:mysql://localhost:3306/xyz?characterEncoding=latin1","root","root");

PreparedStatement stmt = con.prepareStatement("insert into pqr


values (?,?,?)");
stmt.setString(1,"user3");
stmt.setString(2,"[email protected]");
stmt.setString(3,"Baramati");
//stmt.setString(4, "India");
//stmt.setString(4,"India");
int i = stmt.executeUpdate();
System.out.println(i + "Records inserted..");
con.close();
}
catch(Exception e){
System.out.println(e);
}

3. Program to delete record from the table


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;

public class SQLPreparedStatementDelete{

public static void main(String[] args) {


try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection(

"jdbc:mysql://localhost:3306/xyz?characterEncoding=latin1","root","root");

PreparedStatement stmt = con.prepareStatement("delete from pqr


where city=?");
stmt.setString(1,"Baramati");

int i = stmt.executeUpdate();
System.out.println(i + "Records deleted");
con.close();
}
catch(Exception e){
System.out.println(e);
}

4. Program to update any field of the record


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;

public class SQLPreparedStatementUpdate{

public static void main(String[] args) {


try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection(

"jdbc:mysql://localhost:3306/xyz?characterEncoding=latin1","root","root");

PreparedStatement stmt = con.prepareStatement("update pqr set


email=? where name=?");
stmt.setString(1,"[email protected]");
stmt.setString(2,"Ganesh");

int i = stmt.executeUpdate();
System.out.println(i + "Records updated");
con.close();
}
catch(Exception e){
System.out.println(e);
}

}
Post-lab Questions:
1. List the SQL queries for 1) displaying all the data from the table 2) inserting new record
3) deleting particular record 4) updating any field of the record
2. List and explain the commands for JDBC connectivity steps
Program No: 5
Program Statement: Develop an RMI application which accepts a string or a number and
checks that string or number is palindrome or not.

Theory:
What is RMI? Architecture of RMI application, Working of RMI application, RMI registry,
https://www.tutorialspoint.com/java_rmi/java_rmi_introduction.htm
list steps for RMI application development

Program:
1. Following is an example of a remote interface. Here we have defined an interface
with the name Hello and it has a method called printMsg().

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

// Creating Remote interface for our application


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

2. Following is an implementation class. Here, we have created a class named


ImplExample and implemented the interface Hello created in the previous step
and provided body for this method which prints a message.

// 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. Following is an example of an RMI 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();

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

4. Following is an example of an RMI 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();
}
}
}

Post-lab Questions:
1. List steps to write RMI program
(https://www.tutorialspoint.com/java_rmi/java_rmi_application.htm)
2. Write example code for creating remote interface
Program No: 6
Program Statement: Write a program to demonstrate the use of InetAddress class and its
factory methods.

Theory:
Write use of InetAddress class, two versions of IP address and TCP/IP communication
protocol.
https://www.javatpoint.com/InetAddress-class

Program:
import java.io.*;
import java.net.*;
public class InetDemo{
public static void main(String[] args){
try{
InetAddress ip=InetAddress.getByName("www.javatpoint.com");

System.out.println("Host Name: "+ip.getHostName());


System.out.println("IP Address: "+ip.getHostAddress());
}catch(Exception e){System.out.println(e);}
}
}

import java.net.Inet4Address;
import java.util.Arrays;
import java.net.InetAddress;
public class InetDemo2
{
public static void main(String[] arg) throws Exception
{
InetAddress ip = Inet4Address.getByName("www.javatpoint.com");
InetAddress ip1[] = InetAddress.getAllByName("www.javatpoint.com");
byte addr[]={72, 3, 2, 12};
System.out.println("ip : "+ip);
System.out.print("\nip1 : "+ip1);
InetAddress ip2 = InetAddress.getByAddress(addr);
System.out.print("\nip2 : "+ip2);
System.out.print("\nAddress : " +Arrays.toString(ip.getAddress()));
System.out.print("\nHost Address : " +ip.getHostAddress());
System.out.print("\nisAnyLocalAddress : " +ip.isAnyLocalAddress());
System.out.print("\nisLinkLocalAddress : " +ip.isLinkLocalAddress());
System.out.print("\nisLoopbackAddress : " +ip.isLoopbackAddress());
System.out.print("\nisMCGlobal : " +ip.isMCGlobal());
System.out.print("\nisMCLinkLocal : " +ip.isMCLinkLocal());
System.out.print("\nisMCNodeLocal : " +ip.isMCNodeLocal());
System.out.print("\nisMCOrgLocal : " +ip.isMCOrgLocal());
System.out.print("\nisMCSiteLocal : " +ip.isMCSiteLocal());
System.out.print("\nisMulticastAddress : " +ip.isMulticastAddress());
System.out.print("\nisSiteLocalAddress : " +ip.isSiteLocalAddress());
System.out.print("\nhashCode : " +ip.hashCode());
System.out.print("\n Is ip1 == ip2 : " +ip.equals(ip2));
}
}

Post-lab Questions:
List factory methods and instance methods of InetAddress class. Write use of each one.
Program No: 7
Program Statement: Write program with suitable example to develop your remote interface,
implement your RMI server, implement application that create your server, also develop
security policy file.

Theory and Program:


1. In the previous chapter, we created a sample RMI application. In this chapter, we will
explain how to create an RMI application where a client invokes a method which
displays a GUI window (JavaFX).
2. Defining the Remote Interface
3. Here, we are defining a remote interface named Hello with a method named
animation() in it.
import java.rmi.Remote;
import java.rmi.RemoteException;

// Creating Remote interface for our application


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

4. Developing the Implementation Class


5. In the Implementation class (Remote Object) of this application, we are trying to
create a window which displays GUI content, using JavaFX.

import javafx.animation.RotateTransition;
import javafx.application.Application;
import javafx.event.EventHandler;

import javafx.scene.Group;
import javafx.scene.PerspectiveCamera;
import javafx.scene.Scene;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyEvent;
import javafx.scene.paint.Color;
import javafx.scene.paint.PhongMaterial;
import javafx.scene.shape.Box;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
import javafx.scene.transform.Rotate;

import javafx.stage.Stage;
import javafx.util.Duration;

// Implementing the remote interface


public class FxSample extends Application implements Hello {
@Override
public void start(Stage stage) {
// Drawing a Box
Box box = new Box();

// Setting the properties of the Box


box.setWidth(150.0);
box.setHeight(150.0);
box.setDepth(100.0);

// Setting the position of the box


box.setTranslateX(350);
box.setTranslateY(150);
box.setTranslateZ(50);

// Setting the text


Text text = new Text(
"Type any letter to rotate the box, and click on the box to stop the rotation");

// Setting the font of the text


text.setFont(Font.font(null, FontWeight.BOLD, 15));

// Setting the color of the text


text.setFill(Color.CRIMSON);

// Setting the position of the text


text.setX(20);
text.setY(50);

// Setting the material of the box


PhongMaterial material = new PhongMaterial();
material.setDiffuseColor(Color.DARKSLATEBLUE);

// Setting the diffuse color material to box


box.setMaterial(material);

// Setting the rotation animation to the box


RotateTransition rotateTransition = new RotateTransition();

// Setting the duration for the transition


rotateTransition.setDuration(Duration.millis(1000));

// Setting the node for the transition


rotateTransition.setNode(box);

// Setting the axis of the rotation


rotateTransition.setAxis(Rotate.Y_AXIS);

// Setting the angle of the rotation


rotateTransition.setByAngle(360);

// Setting the cycle count for the transition


rotateTransition.setCycleCount(50);

// Setting auto reverse value to false


rotateTransition.setAutoReverse(false);

// Creating a text filed


TextField textField = new TextField();

// Setting the position of the text field


textField.setLayoutX(50);
textField.setLayoutY(100);

// Handling the key typed event


EventHandler<KeyEvent> eventHandlerTextField = new EventHandler<KeyEvent>() {
@Override
public void handle(KeyEvent event) {
// Playing the animation
rotateTransition.play();
}
};

// Adding an event handler to the text feld


textField.addEventHandler(KeyEvent.KEY_TYPED, eventHandlerTextField);

// Handling the mouse clicked event(on box)


EventHandler<javafx.scene.input.MouseEvent> eventHandlerBox =
new EventHandler<javafx.scene.input.MouseEvent>() {
@Override
public void handle(javafx.scene.input.MouseEvent e) {
rotateTransition.stop();
}
};
// Adding the event handler to the box
box.addEventHandler(javafx.scene.input.MouseEvent.MOUSE_CLICKED,
eventHandlerBox);

// Creating a Group object


Group root = new Group(box, textField, text);

// Creating a scene object


Scene scene = new Scene(root, 600, 300);

// Setting camera
PerspectiveCamera camera = new PerspectiveCamera(false);
camera.setTranslateX(0);
camera.setTranslateY(0);
camera.setTranslateZ(0);
scene.setCamera(camera);

// Setting title to the Stage


stage.setTitle("Event Handlers Example");

// Adding scene to the stage


stage.setScene(scene);

// Displaying the contents of the stage


stage.show();
}

// Implementing the interface method


public void animation() {
launch();
}
}
6. Server Program: An RMI server program should implement the remote interface or
extend the implementation class. Here, we should create a remote object and bind it
to the RMIregistry.
7. Following is the server program of this application. Here, we will extend the above
created class, create a remote object, and registered it to the RMI registry with the
bind name hello.

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

public class Server extends FxSample {


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

// 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();

registry.bind("Hello", stub);
System.err.println("Server ready");
} catch (Exception e) {
System.err.println("Server exception: " + e.toString());
e.printStackTrace();
}
}
}
8. Client Program: Following is the client program of this application. Here, we are
fetching the remote object and invoking its method named animation().

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.animation();

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


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

Post-lab questions:
1. List steps to run the program
Program No: 8
Program Statement: Write a database application that uses any JDBC driver.
Theory and Program:

1. We will take an example to see how a client program can retrieve the records of
a table in MySQL database residing on the server.
2. Assume we have a table named student_data in the database details as shown
below.
+----+--------+--------+------------+---------------------+
| ID | NAME | BRANCH | PERCENTAGE | EMAIL |
+----+--------+--------+------------+---------------------+
| 1 | Ram | IT | 85 | [email protected] |
| 2 | Rahim | EEE | 95 | [email protected] |
| 3 | Robert | ECE | 90 | [email protected] |
+----+--------+--------+------------+---------------------+
3. Assume the name of the user is myuser and its password is password.
4. Creating a Student Class: Create a Student class with setter and getter methods as shown
below.

public class Student implements java.io.Serializable {


private int id, percent;
private String name, branch, email;

public int getId() {


return id;
}
public String getName() {
return name;
}
public String getBranch() {
return branch;
}
public int getPercent() {
return percent;
}
public String getEmail() {
return email;
}
public void setID(int id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setBranch(String branch) {
this.branch = branch;
}
public void setPercent(int percent) {
this.percent = percent;
}
public void setEmail(String email) {
this.email = email;
}
}
5. Defining the Remote Interface: Define the remote interface. Here, we are defining a
remote interface named Hello with a method named getStudents () in it. This method
returns a list which contains the object of the class Student.

import java.rmi.Remote;
import java.rmi.RemoteException;
import java.util.*;

// Creating Remote interface for our application


public interface Hello extends Remote {
public List<Student> getStudents() throws Exception;
}

6. Developing the Implementation Class: Create a class and implement the above created
interface.
7. Here we are implementing the getStudents() method of the Remote interface. When you
invoke this method, it retrieves the records of a table named student_data. Sets these
values to the Student class using its setter methods, adds it to a list object and returns
that list.

import java.sql.*;
import java.util.*;

// Implementing the remote interface


public class ImplExample implements Hello {

// Implementing the interface method


public List<Student> getStudents() throws Exception {
List<Student> list = new ArrayList<Student>();

// JDBC driver name and database URL


String JDBC_DRIVER = "com.mysql.jdbc.Driver";
String DB_URL = "jdbc:mysql://localhost:3306/details";

// Database credentials
String USER = "myuser";
String PASS = "password";

Connection conn = null;


Statement stmt = null;

//Register JDBC driver


Class.forName("com.mysql.jdbc.Driver");

//Open a connection
System.out.println("Connecting to a selected database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println("Connected database successfully...");
//Execute a query
System.out.println("Creating statement...");

stmt = conn.createStatement();
String sql = "SELECT * FROM student_data";
ResultSet rs = stmt.executeQuery(sql);

//Extract data from result set


while(rs.next()) {
// Retrieve by column name
int id = rs.getInt("id");

String name = rs.getString("name");


String branch = rs.getString("branch");

int percent = rs.getInt("percentage");


String email = rs.getString("email");

// Setting the values


Student student = new Student();
student.setID(id);
student.setName(name);
student.setBranch(branch);
student.setPercent(percent);
student.setEmail(email);
list.add(student);
}
rs.close();
return list;
}
}
8. Server Program: An RMI server program should implement the remote interface or extend
the implementation class. Here, we should create a remote object and bind it to the RMI
registry.
9. Following is the server program of this application. Here, we will extend the above created
class, create a remote object and register it to the RMI registry with the bind name hello.

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();

registry.bind("Hello", stub);
System.err.println("Server ready");
} catch (Exception e) {
System.err.println("Server exception: " + e.toString());
e.printStackTrace();
}
}
}
10. Client Program: Following is the client program of this application. Here, we are fetching
the remote object and invoking the method named getStudents(). It retrieves the records
of the table from the list object and displays them.
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.util.*;
public class Client {
private Client() {}
public static void main(String[] args)throws Exception {
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


List<Student> list = (List)stub.getStudents();
for (Student s:list)v {

// System.out.println("bc "+s.getBranch());
System.out.println("ID: " + s.getId());
System.out.println("name: " + s.getName());
System.out.println("branch: " + s.getBranch());
System.out.println("percent: " + s.getPercent());
System.out.println("email: " + s.getEmail());
}
// System.out.println(list);
} catch (Exception e) {
System.err.println("Client exception: " + e.toString());
e.printStackTrace();
}
}
}
Program No: 9
Program Statement: Create a simple calculator application using servlet.

Program:
index.html
<html><head>
<title>Calculator App</title></head><body>
<form action="CalculatorServlet" >
Enter First Number <input type="text" name="txtN1"><br>
Enter Second Number <input type="text" name="txtN2" ><br>
Select an Operation<input type="radio" name="opr" value="+">
ADDTION <input type="radio" name="opr" value="-">
SUBSTRACTION <input type="radio" name="opr" value="*">
MULTIPLY <input type="radio" name="opr" value="/">
DIVIDE <br><input type="reset">
<input type="submit" value="Calculate" >
</form></body></html>
CalculatorServlet.java
packagemypack;
import java.io.*;
importjavax.servlet.*;
importjavax.servlet.http.*;
public class CalculatorServlet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throwsServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("<html><head><title>Servlet
CalculatorServlet</title></head><body>");
double n1 = Double.parseDouble(request.getParameter("txtN1"));
double n2 = Double.parseDouble(request.getParameter("txtN2"));
double result =0;
String opr=request.getParameter("opr");
if(opr.equals("+"))
result=n1+n2;
if(opr.equals("*"))
result=n1*n2;
out.println("<h1> Result = "+result);
if(opr.equals("-"))
result=n1-n2;
if(opr.equals("/"))
result=n1/n2;
out.println("</body></html>");
}}
Experiment No: 10
Program Statement: Create a registration servlet in Java using JDBC. Accept the details
such as Username, Password, Email, and Country from the user using HTML Form and store
the registration details in the database

Program:
index.html
<html><head><title>Login Form</title></head>
<form action="LoginServlet" >
Enter User ID<input type="text" name="txtId"><br>
Enter Password<input type="password" name="txtPass"><br>
<input type="reset">
<input type="submit" value=" Click to Login "></form></html>
LoginServlet.java
packagemypack;
import java.io.*;
importjavax.servlet.ServletException;
importjavax.servlet.http.*;
public class LoginServlet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throwsServletException, IOException
{
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("<html><head><title>Servlet LoginServlet</title></head>");
String uname = request.getParameter("txtId");
String upass = request.getParameter("txtPass");
if(uname.equals("admin") &&upass.equals("12345"))
{
out.println("<body bgcolor=blue >");
out.println("<h1> Welcome !!! "+uname+"</h1>");
}
else
{
out.println("<body bgcolor=red >");
out.println("<h1> Login Fail !!! </h1>");

You might also like