5CS4_24 Advance Java Lab
5CS4_24 Advance Java Lab
Lab Manual
Semester: V
Session 2021-22
Faculty:
Kajal Mathur
(Assistant Professor-II)
Department of Computer Science and Engineering
Swami Keshvanand Institute of Technology Management & Gramothan,
Ramnagaria, Jaipur-302017
1
Lab Manual
Advance Java LAB
5CS4-24
SESSION 2020-21
NAME Kajal Mathur Dr. Rajat Goel Prof (Dr.) Mukesh Gupta
SIGNATURE
2
INDEX
3
LAB ETHICS
Responsibilities of Users
Users are expected to follow some fairly obvious rules of conduct:
Always:
4
Do not remove printers and machines from the network without being explicitly told to do so by lab
staff.
Don't monopolize equipment. If you're going to be away from your machine for more than 10 or 15
minutes, log out before leaving. This is both for the security of your account, and to ensure that others
are able to use the lab resources while you are not.
Don’t use internet, internet chat of any kind in your regular lab schedule.
Do not download or upload of MP3, JPG or MPEG files.
No games are allowed in the lab sessions.
No hardware including USB drives can be connected or disconnected in the labs without prior
permission of the lab in-charge.
No food or drink is allowed in the lab or near any of the equipment. Aside from the fact that it leaves a
mess and attracts pests, spilling anything on a keyboard or other piece of computer equipment could
cause permanent, irreparable, and costly damage. (and in fact has) If you need to eat or drink, take a
break and do so in the canteen.
Don’t bring any external material in the lab, except your lab record, copy and books.
Don’t bring the mobile phones in the lab. If necessary then keep them in silence mode.
Please be considerate of those around you, especially in terms of noise level. While labs are a natural
place for conversations of all types, kindly keep the volume turned down.
Note: If you are having problems or questions, please go to either the faculty, lab in-charge or the lab
supporting staff. They will help you. We need your full support and cooperation for smooth functioning of
the lab.
5
INSTRUCTIONS
All the students are supposed to prepare the theory regarding the next experiment/ Program.
Students are supposed to bring their lab records as per their lab schedule.
Previous experiment/program should be written in the lab record.
If applicable trace paper/graph paper must be pasted in lab record with proper labeling.
All the students must follow the instructions, failing which he/she may not be allowed in the lab.
6
Marking/Assessment System
7
Rajasthan Technical University, Kota
Syllabus
8
LAB PLAN
Total number of experiment 10
Exp. 1 1 Day 1
Exp. 2 1 Day 2
Exp. 3 1 Day 3
Exp. 4 1 Day 4
Exp. 5 1 Day 5
Exp. 6 1 Day 6
Exp. 7 1 Day 7
Exp. 8 1 Day 8
Exp. 9 1 Day 9
Exp. 10 1 Day 10
9
Lab Objective & Requirements
Java Programming is intended for software engineers, systems analysts, program managers and user support
personnel who wish to learn the Python programming language.
Prerequisites
Experience with a high level language (C/C++) is suggested. Prior knowledge of a concepts of core java
programming and Object-Oriented concepts are mandatory.
Learning Objectives
a. Software Requirement:
Operating systems: Windows 7 or later OR Linux
Ecllipse IDE with Server setting
b. Hardware Requirement:
Processors: or Intel® Core™ i3 processor
4 GB RAM or Higher
Optical Mouse
Keyboard
10
Java Applets
Applet is a Java program that can be embedded into a web page. It runs inside the web browser and
works at client side. Applet is embedded in a HTML page using the APPLET or OBJECT tag and hosted
on a web server. Applets are used to make the web site more dynamic and entertaining. (A platform
dependent GUI toolkit)
Some important points :
1. All applets are sub-classes (either directly or indirectly) of java.applet.Applet class.
2. Applets are not stand-alone programs. Instead, they run within either a web browser or an applet
viewer. JDK provides a standard applet viewer tool called applet viewer.
3. In general, execution of an applet does not begin at main() method.
4. Output of an applet window is not performed by System.out.println(). Rather it is handled with
various AWT methods, such as drawString().
Java.lang.Object
Java.awt.Component
Java.awt.Container
Java.awt.Panel
Java.applet.Applet
It is important to understand the order in which the various methods shown in the above image are called.
When an applet begins, the following methods are called, in this sequence:
1. init( )
2. start( )
3. paint( )
When an applet is terminated, the following sequence of method calls takes place:
1. stop( )
2. destroy( )
2. start( ) : The start( ) method is called after init( ). It is also called to restart an applet after it has
been stopped. Note that init( ) is called once i.e. when the first time an applet is loaded
whereas start( ) is called each time an applet’s HTML document is displayed onscreen. So, if a user
leaves a web page and comes back, the applet resumes execution at start( ).
3. paint( ) : The paint( ) method is called each time an AWT-based applet’s output must be redrawn.
This situation can occur for several reasons. For example, the window in which the applet is running
may be overwritten by another window and then uncovered. Or the applet window may be
minimized and then restored.
paint( ) is also called when the applet begins execution. Whatever the cause, whenever the applet
must redraw its output, paint( ) is called.
The paint( ) method has one parameter of type Graphics. This parameter will contain the graphics
context, which describes the graphics environment in which the applet is running. This context is
used whenever output to the applet is required.
4. stop( ) : The stop( ) method is called when a web browser leaves the HTML document containing
the applet—when it goes to another page, for example. When stop( ) is called, the applet is probably
running. You should use stop( ) to suspend threads that don’t need to run when the applet is not
visible. You can restart them when start( ) is called if the user returns to the page.
5. destroy( ) : The destroy( ) method is called when the environment determines that your applet
needs to be removed completely from memory. At this point, you should free up any resources the
applet may be using. The stop( ) method is always called before destroy( ).
12
Experiment 1 – Write a Program to create a Hello World applet.
Let’s begin with the HelloWorld applet :
// A Hello World Applet
// Save file as HelloWorld.java
import java.applet.Applet;
import java.awt.Graphics;
13
Experiment 2 – Write a Program to Set the color of the applet and draws a fill oval
import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
/*
<applet code = "FillOval" width = 200 height = 200></applet>
*/
public class FillOval extends Applet {
public void paint(Graphics g) {
g.setcolor(Color.red);
g.fillOval(20,20,60,60);
}
}
14
Java Swing
Java Swing is a lightweight Graphical User Interface (GUI) toolkit that includes a rich set of widgets. It
includes package lets you make GUI components for your Java applications, and It is platform
independent.
The Swing library is built on top of the Java Abstract Widget Toolkit (AWT), an older, platform
dependent GUI toolkit. You can use the Java GUI components like button, textbox, etc. from the library
and do not have to create the components from scratch.
Component-based framework: The components are derived from the javax.swing. JComponent class.
Swing components compliant with the Java Beans Component Architecture specifications. Swing objects
asynchronously fire events, have bound properties, and respond to a documented set of methods specific
to the component.
Configurable: Swing can respond to fundamental changes in its settings at run time.
Lightweight User Interface: Swing's high level of flexibility is reflected in its inherent ability to override
the native host operating system (OS)'s GUI controls for displaying itself. A Swing component does not
have a corresponding native OS GUI component, and is free to render itself in any way that is possible
with the underlying graphics GUIs.
Loosely coupled and Model/View/Controller (MVC): The Swing library makes heavy use of
the software design pattern, which conceptually decouples the data being viewed from the user interface
controls through which it is viewed. Therefore, Swing components have associated models that are
specified in terms of Java interfaces and the programmers can use various default implementations or
provide their own.
15
All components in swing are JComponent which can be added to container classes.
1. Panel: It is a pure container and is not a window in itself. The sole purpose of a Panel is to
organize the components on to a window.
2. Frame: It is a fully functioning window with its title and icons.
3. Dialog: It can be thought of like a pop-up window that pops out when a message has to be
displayed. It is not a fully functioning window like the Frame.
16
Experiment 3 – Write a Program to design GUI in Java
import javax.swing.*;
4. class gui{
5. public static void main(String args[]){
6. JFrame frame = new JFrame("My First GUI");
7. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
8. frame.setSize(300,300);
9. JButton button = new JButton("Press");
10. frame.getContentPane().add(button); // Adds Button to content pane of frame
11. frame.setVisible(true);
12. }
13. }
Step 3) Now let's Add a Button to our frame. Copy following code into an editor
JavaBorderLayout
A BorderLayout places components in up to five areas: top, bottom, left, right, and center. It is the default
layout manager for every java JFrame.
17
Java FlowLayout
FlowLayout is the default layout manager for every JPanel. It simply lays out components in a single row
one after the other.
Java GridBagLayout
It is the more sophisticated of all layouts. It aligns components by placing them within a grid of cells,
allowing components to span more than one cell.
18
Experiment 4 : WAP to make a calculator using Java Swing.
package calculator;
public class form1 extends javax.swing.JFrame {
int a;
int count=0;
public form1() {
initComponents();
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
jTextField1.setText(jTextField1.getText()+"1");
}
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
jTextField1.setText(jTextField1.getText()+"2");
}
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
jTextField1.setText(jTextField1.getText()+"3");
}
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
jTextField1.setText(jTextField1.getText()+"4");
}
private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {
jTextField1.setText(jTextField1.getText()+"5");
}
private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {
jTextField1.setText(jTextField1.getText()+"6");
}
private void jButton7ActionPerformed(java.awt.event.ActionEvent evt) {
jTextField1.setText(jTextField1.getText()+"7");
}
19
private void jButton8ActionPerformed(java.awt.event.ActionEvent evt) {
jTextField1.setText(jTextField1.getText()+"8");
}
private void jButton9ActionPerformed(java.awt.event.ActionEvent evt) {
jTextField1.setText(jTextField1.getText()+"9");
}
private void jButton18ActionPerformed(java.awt.event.ActionEvent evt) {
jTextField1.setText(jTextField1.getText()+"0");
}
private void jButton10ActionPerformed(java.awt.event.ActionEvent evt) {
a=Integer.parseInt(jTextField1.getText());
jTextField1.setText("");
count=1;
}
private void jButton11ActionPerformed(java.awt.event.ActionEvent evt) {
a=Integer.parseInt(jTextField1.getText());
jTextField1.setText("");
count=2;
}
private void jButton12ActionPerformed(java.awt.event.ActionEvent evt) {
a=Integer.parseInt(jTextField1.getText());
jTextField1.setText("");
count=3;
}
private void jButton13ActionPerformed(java.awt.event.ActionEvent evt) {
a=Integer.parseInt(jTextField1.getText());
jTextField1.setText("");
count=4;
}
private void jButton14ActionPerformed(java.awt.event.ActionEvent evt) {
20
a=Integer.parseInt(jTextField1.getText());
jTextField1.setText("");
count=5;
}
private void jButton15ActionPerformed(java.awt.event.ActionEvent evt) {
a=Integer.parseInt(jTextField1.getText());
jTextField1.setText("");
count=6;
}
private void jButton17ActionPerformed(java.awt.event.ActionEvent evt) {
int b=Integer.parseInt(jTextField1.getText());
int c=0;
if(count==1)
c=a+b;
else if(count==2)
c=a-b;
else if(count==3)
c=a*b;
else if(count==4)
c=a/b;
else if(count==5)
c=a%b;
else if(count==6)
c=a*b;
jTextField1.setText(Integer.toString(c));
}
private void jButton16ActionPerformed(java.awt.event.ActionEvent evt) {
jTextField1.setText("");
}
21
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new form1().setVisible(true); }
});
} }
OUTPUT
22
Java Database Programming
Objectives
To understand the concept of database and database management systems
To understand the relational data model: relational data structures constraints, and languages
To use SQL to create and drop tables, and to retrieve and modify data
To learn how to load a driver, connect to a database, execute statements, and process result sets using
JDBC
To use prepared statements to execute precompiled SQL statements
To use callable statements to execute stored SQL procedures and functions
To explore database metadata using the DatabaseMetaData and ResultSetMetaData interfaces
First, Java is platform independent. You can develop platform-independent database applications using
SQL and Java for any relational database systems.
Second, the support for accessing database systems from Java is built into Java API, so you can create
database applications using all Java code with a common interface.
Third, Java is taught in almost every university either as the first programming language or as the second
programming language.
23
The execute, executeQuery, and executeUpdate Methods
The methods for executing SQL statements are execute, executeQuery, and executeUpdate, each of which
accepts a string containing a SQL statement as an argument. This string is passed to the database for
execution. The execute method should be used if the execution produces multiple result sets, multiple
update counts, or a combination of result sets and update counts. The executeQuery method should be
used if the execution produces a single result set, such as the SQL select statement. The executeUpdate
method should be used if the statement results in a single update count or no update count, such as a SQL
INSERT, DELETE, UPDATE, or DDL statement.
JDBC Drivers
Java Database Connectivity (JDBC) is an application programming interface (API) for the
programming language Java, which defines how a client may access any kind of tabular data, especially
relational database. It is part of Java Standard Edition platform, from Oracle Corporation. It acts as a
middle layer interface between java applications and database.
The JDBC classes are contained in the Java Package java.sql and javax.sql.
JDBC helps you to write Java applications that manage these three programming activities:
1. Connect to a data source, like a database.
2. Send queries and update statements to the database
3. Retrieve and process the results received from the database in answer to your query
24
JDBC drivers are client-side adapters (installed on the client machine, not on the server) that convert
requests from Java programs to a protocol that the DBMS can understand. There are 4 types of JDBC
drivers:
Socket Programming
Sockets provide the communication mechanism between two computers using TCP. A client program
creates a socket on its end of the communication and attempts to connect that socket to a server. When the
connection is made, the server creates a socket object on its end of the communication. The client and the
server can now communicate by writing to and reading from the socket.
The java.net.Socket class represents a socket, and the java.net.ServerSocket class provides a mechanism
for the server program to listen for clients and establish connections with them. The following steps occur
when establishing a TCP connection between two computers using sockets −
The server instantiates a ServerSocket object, denoting which port number communication is to
occur on.
The server invokes the accept() method of the ServerSocket class. This method waits until a client
connects to the server on the given port.
After the server is waiting, a client instantiates a Socket object, specifying the server name and the
port number to connect to.
The constructor of the Socket class attempts to connect the client to the specified server and the
port number. If communication is established, the client now has a Socket object capable of
communicating with the server.
On the server side, the accept() method returns a reference to a new socket on the server that is
connected to the client's socket.
After the connections are established, communication can occur using I/O streams. Each socket has both
an OutputStream and an InputStream. The client's OutputStream is connected to the server's InputStream,
and the client's InputStream is connected to the server's OutputStream.
TCP is a two-way communication protocol, hence data can be sent across both streams at the same time.
Following are the useful classes providing complete set of methods to implement sockets.
25
The java.net.ServerSocket class is used by server applications to obtain a port and listen for client
requests. The ServerSocket class has four constructors −
public ServerSocket(int port) throws IOExceptionAttempts to create a server socket bound the
specified port. An exception occurs if the port is already bound by another application.
Similar to the previous constructor, the backlog parameter specifies how many incoming clients to store
in a wait queue.
Similar to the previous constructor, the InetAddress parameter specifies the local IP address to bind to.
The InetAddress is used for servers that may have multiple IP addresses, allowing the server to specify
which of its IP addresses to accept client requests on.
Creates an unbound server socket. When using this constructor, use the bind() method when you
ready to bind the server socket.
If the ServerSocket constructor does not throw an exception, it means that your application has
successfully bound to the specified port and is ready for client requests.
Returns the port that the server socket is listening on. This method is useful if you passed in 0 as the port
number in a constructor and let the server find a port for you.
Waits for an incoming client. This method blocks until either a client connects to the server on the
specified port or the socket times out, assuming that the time-out value has been set using the
setSoTimeout() method. Otherwise, this method blocks indefinitely.
26
public void setSoTimeout(int timeout)
Sets the time-out value for how long the server socket waits for a client during the accept().
Binds the socket to the specified server and port in the SocketAddress object. Use this method if you have
instantiated the ServerSocket using the no-argument constructor.
When the ServerSocket invokes accept(), the method does not return until a client connects. After a client
does connect, the ServerSocket creates a new Socket on an unspecified port and returns a reference to this
new Socket. A TCP connection now exists between the client and the server, and communication can
begin.
The java.net.Socket class represents the socket that both the client and the server use to communicate
with each other. The client obtains a Socket object by instantiating one, whereas the server obtains a
Socket object from the return value of the accept() method.
The Socket class has five constructors that a client uses to connect to a server −
This method attempts to connect to the specified server at the specified port. If this constructor does not
throw an exception, the connection is successful and the client is connected to the server.
This method is identical to the previous constructor, except that the host is denoted by an InetAddress
object.
public Socket(String host, int port, InetAddress localAddress, int localPort) throws IOException.
Connects to the specified host and port, creating a socket on the local host at the specified address and
port.
public Socket(InetAddress host, int port, InetAddress localAddress, int localPort) throws
IOException.
27
This method is identical to the previous constructor, except that the host is denoted by an InetAddress
object instead of a String.
public Socket()
Creates an unconnected socket. Use the connect() method to connect this socket to a server.
When the Socket constructor returns, it does not simply instantiate a Socket object but it actually attempts
to connect to the specified server and port.
Some methods of interest in the Socket class are listed here. Notice that both the client and the server have
a Socket object, so these methods can be invoked by both the client and the server.
This method connects the socket to the specified host. This method is needed only when you instantiate the
Socket using the no-argument constructor.
This method returns the address of the other computer that this socket is connected to.
Returns the input stream of the socket. The input stream is connected to the output stream of the remote socket.
Returns the output stream of the socket. The output stream is connected to the input stream of the remote
28
socket.
Closes the socket, which makes this Socket object no longer capable of connecting again to any server.
This class represents an Internet Protocol (IP) address. Here are following usefull methods which you
would need while doing socket programming −
String getHostAddress()
String getHostName()
String toString()
29
Experiment 5 – Write a Program to implement the SQL –login ID commands using JDBC
package javaapplication5;
import java.sql.*;
import java.awt.*;
import javax.swing.*;
public class NewJFrame extends javax.swing.JFrame {
public NewJFrame() {
initComponents();
}
private void initComponents() {
jTextField1 = new javax.swing.JTextField();
jTextField2 = new javax.swing.JTextField();
jButton1 = new javax.swing.JButton();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jButton1.setText("Login");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try
{
// Connection conn;
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url = "Jdbc:Odbc:g2";
Connection conn = DriverManager.getConnection(url);
ResultSet rs;
Statement stmt=conn.createStatement();
rs=stmt.executeQuery("select * from mytab");
while(rs.next())
{
if(((jTextField1.getText()).equals(rs.getString(1)))&& ((jTextField2.getText()).equals(rs.getString(2)))){
JOptionPane.showMessageDialog(this, "login successfull");
System.exit(0);
30
}}
JOptionPane.showMessageDialog(this, "login unsuccessfull");
System.exit(0);
conn.close();
}
catch (Exception e) {
System.err.println("Got an exception! ");
System.err.println(e.getMessage());
}
}
}
OUTPUT:
31
Experiment 6 – Write a Program to implement the SQL commands using JDBC.
package opertiondemo;
import java.sql.*;
import javax.swing.*;
public class operationdemo1 extends javax.swing.JFrame {
ResultSet rs1;
/** Creates new form operationdemo1 */
public operationdemo1() {
initComponents();
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url = "Jdbc:Odbc:g4";
Connection conn = DriverManager.getConnection(url);
Statement
stmt=conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE
);
}
catch (Exception e) {
System.err.println("Got an exception! ");
System.err.println(e.getMessage());
}
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try
{System.out.println("Outside rs1");
if(rs1.next()){
System.out.println("Inside rs1");
String r1=rs1.getString(1);
String n1=rs1.getString(2);
String a1=rs1.getString(3);
32
jTextField1.setText(r1);
jTextField2.setText(n1);
jTextField3.setText(a1);
}
else
{
JOptionPane.showMessageDialog(this, "eND OF THE RECORD");
}
}catch(Exception e)
{}
}
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url = "Jdbc:Odbc:g4";
Connection conn = DriverManager.getConnection(url);
ResultSet rs;
Statement stmt=conn.createStatement();
String qry=("Insert into student
values('"+jTextField1.getText()+"','"+jTextField2.getText()+"','"+jTextField3.getText()+"')");
stmt.executeUpdate(qry);
JOptionPane.showMessageDialog(this, "Record inserted");
conn.close();
}
catch (Exception e) {
System.err.println("Got an exception! ");
System.err.println(e.getMessage());
}
}
private void jButton7ActionPerformed(java.awt.event.ActionEvent evt) {
try
{System.out.println("Outside rs1");
if(rs1.previous()){
System.out.println("Inside rs1");
String r1=rs1.getString(1);
String n1=rs1.getString(2);
String a1=rs1.getString(3);
jTextField1.setText(r1);
33
jTextField2.setText(n1);
jTextField3.setText(a1);
}
}catch(Exception e)
{}
}
private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
try
{
// Connection conn;
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url = "Jdbc:Odbc:g4";
Connection conn = DriverManager.getConnection(url);
ResultSet rs;
Statement
stmt=conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE
);
rs=stmt.executeQuery("select * from student");
rs.first();
String r=rs.getString(1);
String n=rs.getString(2);
String a=rs.getString(3);
jTextField1.setText(r);
jTextField2.setText(n);
jTextField3.setText(a);
conn.close();
}
catch (Exception e) {
System.err.println("Got an exception! ");
System.err.println(e.getMessage());
}
}
private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
try
{
// Connection conn;
34
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url = "Jdbc:Odbc:g4";
Connection conn = DriverManager.getConnection(url);
ResultSet rs;
Statement
stmt=conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE
);
rs=stmt.executeQuery("select * from student");
rs.last();
String r=rs.getString(1);
String n=rs.getString(2);
String a=rs.getString(3);
jTextField1.setText(r);
jTextField2.setText(n);
jTextField3.setText(a);
conn.close();
}
catch (Exception e) {
System.err.println("Got an exception! ");
System.err.println(e.getMessage());
}
try
{
// Connection conn;
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url = "Jdbc:Odbc:g4";
Connection conn = DriverManager.getConnection(url);
ResultSet rs;
35
String qry="update student set rollnum="+jTextField1.getText()+",age="+jTextField3.getText()+"
where name='"+jTextField2.getText()+"'";
Statement stmt=conn.createStatement();
stmt.executeUpdate(qry);
JOptionPane.showMessageDialog(this, "Record Updated");
conn.close();
}
catch (Exception e) {
System.err.println("Got an exception! ");
System.err.println(e.getMessage());
}
try
{
// Connection conn;
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url = "Jdbc:Odbc:g4";
Connection conn = DriverManager.getConnection(url);
Statement stmt=conn.createStatement();
stmt.executeUpdate("delete * from student where rollnum="+jTextField1.getText()+"");
JOptionPane.showMessageDialog(this, "Record deleted");
jTextField1.setText(" ");
jTextField2.setText(" ");
jTextField3.setText(" ");
conn.close();
}
catch (Exception e) {
System.err.println("Got an exception! ");
System.err.println(e.getMessage());
}
}
36
private void jButton8ActionPerformed(java.awt.event.ActionEvent evt) {
System.exit(0);
// TODO add your handling code here:
}
try
{
// Connection conn;
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url = "Jdbc:Odbc:g4";
Connection conn = DriverManager.getConnection(url);
ResultSet rs;
Statement stmt=conn.createStatement();
rs=stmt.executeQuery("Select * from student");
while(rs.next()){
String r=rs.getString(1);
String n=rs.getString(2);
String a=rs.getString(3);
jTextField1.setText(r);
jTextField2.setText(n);
jTextField3.setText(a);
}
conn.close();
}
catch (Exception e) {
System.err.println("Got an exception! ");
System.err.println(e.getMessage());
37
}}}
OUTPUT:
38
Java RMI
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.
RMI uses stub and skeleton object for communication with the remote object. A remote object is an
object whose method can be invoked from another JVM. Let's understand the stub and skeleton
objects:
Stub
The stub is an object, acts as a gateway for the client side. All the outgoing requests are routed
through it. It resides at the client side and represents the remote object. When the caller invokes
method on the stub object, it does the following tasks:
1. It initiates a connection with remote Virtual Machine (JVM),
2. It writes and transmits (marshals) the parameters to the remote Virtual Machine (JVM),
3. It waits for the result
4. It reads (unmarshals) the return value or exception, and
5. It finally, returns the value to the caller.
Skeleton
The skeleton is an object, acts as a gateway for the server side object. All the incoming requests are
routed through it. When the skeleton receives the incoming request, it does the following tasks:
1. It reads the parameter for the remote method
2. It invokes the method on the actual remote object, and
3. It writes and transmits (marshals) the result to the caller.
In the Java 2 SDK, an stub protocol was introduced that eliminates the need for skeletons.
39
Understanding requirements for the distributed applications
If any application performs these tasks, it can be distributed application.
The application need to locate the remote method
1. It need to provide the communication with the remote objects, and
2. The application need to load the class definitions for the objects.
The RMI application have all these features, so it is called the distributed application.
RMI Example
In this example, we have followed all the 6 steps to create and run the rmi application. The client
application need only two files, remote interface and client application. In the rmi application, both
client and server interacts with the remote interface. The client application invokes methods on the
proxy object, RMI sends the request to the remote JVM. The return value is sent back to the proxy
object and then to the client application.
40
1. create the remote interface
For creating the remote interface, extend the Remote interface and declare the RemoteException
with all the methods of the remote interface. Here, we are creating a remote interface that extends
the Remote interface. There is only one method named add() and it declares RemoteException.
1. import java.rmi.*;
2. public interface Adder extends Remote{
3. public int add(int x,int y)throws RemoteException;
4. }
Now provide the implementation of the remote interface. For providing the implementation of the
Remote interface, we need to
Either extend the UnicastRemoteObject class,
or use the exportObject() method of the UnicastRemoteObject class
In case, you extend the UnicastRemoteObject class, you must define a constructor that declares
RemoteException.
1. import java.rmi.*;
2. import java.rmi.server.*;
3. public class AdderRemote extends UnicastRemoteObject implements Adder{
4. AdderRemote()throws RemoteException{
5. super();
6. }
7. public int add(int x,int y){return x+y;}
8. }
41
3) create the stub and skeleton objects using the rmic tool.
Next step is to create stub and skeleton objects using the rmi compiler. The rmic tool invokes the
RMI compiler and creates stub and skeleton objects.
rmic AdderRemote
Now start the registry service by using the rmiregistry tool. If you don't specify the port number, it
uses a default port number. In this example, we are using the port number 5000.
rmiregistry 5000
In this example, we are binding the remote object by the name sonoo.
1. import java.rmi.*;
2. import java.rmi.registry.*;
3. public class MyServer{
4. public static void main(String args[]){
5. try{
6. Adder stub=new AdderRemote();
7. Naming.rebind("rmi://localhost:5000/sonoo",stub);
8. }catch(Exception e){System.out.println(e);}
9. }
10. }
At the client we are getting the stub object by the lookup() method of the Naming class and
invoking the method on this object. In this example, we are running the server and client
applications, in the same machine so we are using localhost. If you want to access the remote object
from another machine, change the localhost to the host name (or IP address) where the remote
object is located.
javac *.java
rmic AdderRemote
java MyServer
java MyClient
43
44
Experiment 7 – Write a Program to implement the Remote Method Invocation.
INTERFACE:
import java.rmi.*;
interface Bank extends Remote
{
double getAmount(double p,double t) throws RemoteException;
}
BANK SEVER:
import java.rmi.*;
import java.rmi.server;
public class BankImpl extends UnicastRemoteObject implements Bank
{
public BankImpl throws RemoteException
{
}
double getAmount(double p,double t) throws RemoteException
{
return p*Math.pow(1.41,t);
}
}
RMI REGISTRY:
import java.rmi.*;
import javax.naming.*;
public class BankServer
{
public static void main(String args[])
{
BankImpl centralbank=new BankImpl();
Naming.rebind("uti",centralbank);
}
}
BANKCLIENT:
45
import java.rmi.*;
import javax.naming.*;
public class Bankclient
{
public static void main(String args[]) throws RemoteException
{
String url="rmi://localHost//uti";
Bank b=(Bank) Naming.lookup(url);
System.out.println(b.getAmount(4000,3));
}
}
46
JSP
JSP technology is used to create web application just like Servlet technology. It can be thought of as
an extension to Servlet because it provides more functionality than servlet such as expression
language, JSTL, etc. A JSP page consists of HTML tags and JSP tags. The JSP pages are easier to
maintain than Servlet because we can separate designing and development. It provides some
additional features such as Expression Language, Custom Tags, etc.
JSP can be easily managed because we can easily separate our business logic with presentation
logic. In Servlet technology, we mix our business logic with the presentation logic.
If JSP page is modified, we don't need to recompile and redeploy the project. The Servlet code
needs to be updated and recompiled if we have to change the look and feel of the application.
In JSP, we can use many tags such as action tags, JSTL, custom tags, etc. that reduces the code.
Moreover, we can use EL, implicit objects, etc.
47
Experiment 8 – Write a Program to demonstrate Basic Servlet.
Program
Import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class hello extends HttpServlet {
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
PrintWriter out=response.getWriter(); java.util.Date today=new
java.util.Date(); out.println("<html>"+"<body>"+"<h1
align=center>welcome to
exciting world of servlet</h1>"+"<br>"+today+"</body>"+"</html>");
}
}
48
Output:
49
Experiment 9 – Write a Basic JSP program
Pr ogr am :
<%@ page language="java" contentType="text/html; charset=ISO88591"
pageEncoding="ISO88591"%>
Output:
51
Experiment 10 – Write a Program for Database Operation in jsp
Create a database: First create a database named 'student' in mysql and table named
"stu_info" in same database by sql query given below:
Create database student
create table stu_info (
ID int not null auto_increment,
Name varchar(20),
City varchar(20),
Phone varchar(15),
primary key(ID)
);
Create a new directory named "user" in the tomcat6.0.16/
webapps and
WEBINF
directory in same directory. Before running this java code you
need to paste a .jar file named mysql connector.jar in the Tomcat6.0.16/
webapps/user/WEBINF/
lib.
prepared_statement_query.jsp
Save this code as a .jsp file named "prepared_statement_query.jsp" in the
directory Tomcat6.0.16/
webapps/user/ and you can run this jsp page with
url http://localhost:8080/user/prepared_statement_query.jsp in address
bar of the browser
53
<%
String name = request.getParameter ("name");
String city = request.getParameter ("city");
String phone = request.getParameter ("phone");
String connectionURL = "jdbc: mysql:
Connection connection = null;
PreparedStatement pstatement = null;
Class.forName("com.mysql.jdbc.Driver").newInstance();
int updateQuery = 0;
if(name! =null && city!=null && phone!=null){
if(name!="" && city!="" && phone!="") {
try {
connection = DriverManager.getConnection
(connectionURL, "root", "root");
String queryString = "INSERT INTO stu_info(Name,
Address, Phone) VALUES (?, ?, ?)";
pstatement = connection.prepareStatement(queryString);
pstatement.setString(1, name);
pstatement.setString(2, city);
pstatement.setString(3, phone);
updateQuery = pstatement.executeUpdate();
if(updateQuery != 0) { %>
<br>
<TABLE style="backgroundcolor:
#E3E4FA;"
WIDTH="30%" border="1">
<tr><th>Data is inserted successfully
in database.</th></tr>
</table>
<%
54
}
}
catch (Exception ex) {
out.println("Unable to connect to database.");
}
finally {
.
pstatement.close();
connection.close();
}
}
}
%>
</FORM>
</body>
</html>
Output:
Fill all the fields and click on submit button, that shows a response message. If any field is blank or only
blank spaces are there page will remain same after clicking on submit button.
Update Data:
55
This example shows how to update the existing record of mysql table using jdbc connectivity in the jsp
page. In this example we have created two jsp pages update.jsp and updatingDatabase.jsp. In the
update.jsp page, we are using a Text box where user can give his/her name and submit the page.
After submitting the page, updatingDatabase.jsp will be called and the sql query ("update servlet set
name = ? where id = ?") is executed which will modify the table record.
<%@page language=”java” session=”true”
contentType=”text/html;charset= %>
<font color”blue” Please Enter Your Name </font><br><br>
<form name="frm" method="post" action="updatingDatabase.jsp">
<table border = "0">
<tr align="left" valign="top">
<td>Name:</td>
<td><input type="text" name ="name" /></td>
</tr>
<tr align="left" valign="top">
<td></td>
<td><input type="submit" name="submit" value="submit"/></td>
</tr>
</table>
</form>
Type the url: http://localhost:8080/ServletExample/jsp/update.jsp on your browser. Following output
will be displayed:
56
updatingDatabase.jsp
<%@ page language = "java" contentType =
"text/html; charset = ISO88591"
import = "java.io.*"
import = "java.sql.*"
import = "java.util.*"
import = "javax.sql.*"
import = "java.sql.ResultSet"
import = "java.sql.Statement"
import = "java.sql.Connection"
import = "java.sql.DriverManager"
import = "java.sql.SQLException"
%>
<%
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
Statement stmt = null;
57
String name = request.getParameter("name");
Integer id = 5;
%>
<html>
<head>
<title>Updating Database</title>
</head>
<body>
<%
try {
Class.forName("com.mysql.jdbc.Driver");
con =DriverManager.getConnection
("jdbc:mysql://192.168.10.59:3306/example",
"root", "root");
ps = con.prepareStatement("update servlet set
name = ? where id = ?");
ps.setInt(2, id);
ps.setString(1, name);
ps.executeUpdate();
%>
Database successfully Updated!<br>
<%
if(ps.executeUpdate()>=1){
28
stmt=con.createStatement();
rs = stmt.executeQuery("SELECT * FROM servlet");
while(rs.next()){
%>
<%=rs.getObject(1).toString()%>
<%=("\t\t\t")%>
58
<%=rs.getObject(2).toString()%>
<%=("<br>")%>
<%
}
}
} catch (IOException e) {
throw new IOException("Can not display records.", e);
} catch (ClassNotFoundException e) {
throw new SQLException("JDBC Driver not found.", e);
} finally {
try {
if(stmt != null){
stmt.close();
stmt = null;
}
if(ps != null) {
ps.close();
ps = null;
}
if(con != null) {
con.close();
con = null;
}
} catch (SQLException e) {}
}
%>
</body>
</html>
After submitting the name, it will be updated in the database and the records
will be displayed on your browser.
59
Save this code as a .jsp file named "prepared_statement_query.jsp" in the directory
Tomcat6.0.16/webapps/user/ and you can run this jsp page with url
http://localhost:8080/user/prepared_statement_query.jsp in address bar of the browser.
Conclusion:
Hence we studied how to perform different database operation in jsp.
60
Multiple Choice Questions
1) What technique is used for the authentication mechanism in the servlet specification?
a. Role Based Authentication
c. Both A & B
2) Which attribute specifies a JSP page that should process any exceptions thrown but not caught in the
current page?
a. The ErrorPage Attribute
c. Both A & B
3) Which Error Handling in Java handles runtime errors with exceptions, If an exception is not caught in
your JSP or Servlet, Resin will use a special error page to send results back to the browser, Resin uses a
default error page unless you explicitly provide an error page yourself?
a. Client Request Time Processing Errors
4) The ASP and JSP technologies are quite similar in the way they support the creation of Dynamic pages,
using HTML templates, scripting code and components for business logic.
a. True
b. False
61
5) Which can generate HTML dynamically on the client but can hardly interact with the web server to
perform complex tasks like database access and image processing etc. in JSP?
a. vs.Static HTML
b. vs.Server-Side Includes
c. vs.Pure Servlets
d. vs.JavaScript
6) In JSP Action tags which tags are used for bean development?
a. jsp:useBean
b. jsp:setPoperty
c. jsp:getProperty
b. HttpJspPage
c. JspWriter
d. PageContext
e. Both A & B
8) Which of the following is an advantage of the statement – Separation of business logic from JSP ?
a. Custom Tags in JSP
62
d. None of the above
9) JSPs eventually are compiled into Java servlets, you can do as much with JSPs as you can do with Java
servlets.
a. True
b. False
10) How many jsp implicit objects are there and these objects are created by the web container that are
available to all the jsp pages?
a. 8
b. 9
c. 10
d. 7
11) JavaServer Pages often serve the same purpose as programs implemented using the Common Gateway Interface
(CGI)
a. True
b. False
12) Which action tags are used in JSP for developing web application with Java Bean?
a. jsp:useBean
b. jsp:setProperty
c. jsp:getProperty
d. Both B & C
13) Which technology do we mix our business logic with the presentation logic?
a. Servlet
63
b. JSP
c. Both A & B
14) Which is the Microsoft solution for providing dynamic Web content?
a. ASP
b. JSP
c. Both A & B
15) A bean encapsulates many objects into one object, so we can access this object from multiple places.
a. True
b. False
b. Scriptlet tag
c. Expression tag
17) Which JSP Action tags is used to include the content of another resource, it may be jsp, html or servlet?
a. jsp:include
b. jsp:forward
c. jsp:plugin
d. jsp:papam
64
18) In JSP how many ways are there to perform exception handling?
a. 3
b. 2
c. 4
d. 5
19) In JSP page directive which attribute defines the MIME(Multipurpose Internet Mail Extension) type of the HTTP
response?
a. import
b. Content Type
c. Extends
d. Info
b. JSP tags
c. Both A & B
b. java.servlet
c. javax.servlet.jsp.tagext
d. Both A & C
65
22) JSP’s provide better facilities for separation of page code and template data by mean of Java beans, EJBs and
custom tag libraries
a. True
b. False
66
Practical Exam Sample Paper
Set-A
Q1. Write a program to calculate difference of two numbers using Remote Method Invocation.
Set-B
67
Viva Voce (Interview based)
69
What is the difference between a Scrollbar and a ScrollPane?
A Scrollbar is a Component, but not a Container. A ScrollPane is a Container.
A ScrollPane handles its own events and performs its own scrolling.
What is the difference between a public and a non-public class?
A public class may be accessed outside of its package.
A non-public class may not be accessed outside of its package.
To what value is a variable of the boolean type automatically initialized?
The default value of the boolean type is false.
Can try statements be nested?
Try statements may be tested.
What is the difference between the prefix and postfix forms of the ++ operator?
The prefix form performs the increment operation and returns the value of the increment operation.
The postfix form returns the current value all of the expression and then performs the increment
operation on that value.
What is the purpose of a statement block?
A statement block is used to organize a sequence of statements as a single statement group.
Reference Books
1. Java The Complete Reference, Herbert Schildt
2. Programming with Java, E. Balagurusamy
70