Java Programming Lab Manual
Java Programming Lab Manual
technology
[JAVA LAB
DOCUMENT]
Information technology
INDEX
TITLE
PAGE
1:
BASIC PROGRAMS
1-5
2:
6-20
3:
21-39
4:
PACKAGES
40-42
5:
POLYMORPHISM
43-44
6:
THREADS
45-49
7:
INNER CLASSES
50-53
8:
BEANS
54-70
9:
71-74
10: SERVLETS
75-87
11: JDBC
88-104
12: NETWORKING
105-113
Information technology
Note :
After installing the java software we must set path and classpath variables .
Always ensure that the path variable points to bin directory of jdk1.6.0 and
classpath variable points to lib folder of jdk and current directory
How to set PATH, CLASSPATH?
Click on MyComputer-properties- advanced tab and environment
variables
In that press new button in the user-variables dont edit system variables
it may cause problems in your system response
Add like this
Variable name:path
Variable value: %path%;C:\Program Files\Java\jdk1.6.0\bin;
-here it is assumed that javadeveloper kit is installed in C drive
Program-1:(MyClass.java)
Information technology
Source:
import java.io.*;
public class MyClass
{
public static void main(String pars[])
{
BufferedReader console = new BufferedReader(new
InputStreamReader(System.in));
String input="" ;
System.out.println("Enter Your Name::");
try
{
input=console.readLine();
}
catch(Exception e)
{
System.out.println("Exception caught::"+e.getMessage());
}
System.out.println("Hello "+input+" Welcome to Java!");
}
}
OUTPUT:
//to compile: javac <filename>.java
// To Execute: java <file-name>
Applet:
Information technology
We can view these applets by creating web document (.html) file or using the java tool
appletviewer.
FRAME:
Frame is a window that is not contained inside another window. Frame is the
basis to contain other user interface components in Java GUI applications.
The Frame class can be used to create windows.
PROGRAM-2: (AppletTest.java)
Write an Applet that handles mouse events and key events using adapter classes?
Source:
// <applet code="AppletTest.class" width=300 height=300> </applet>
import java.awt.*;
import java.awt.event.*;
public class AppletTest extends java.applet.Applet
{
int len;
public void init( )
{
this.addMouseListener( new MyMouseAdapter( ) );
this.addKeyListener( new MyKeyAdapter( ) );
}
public void start( )
{
len = 0;
}
public void paint( Graphics g )
{
g.setColor( Color.red );
g.fillRect( 10, 10, len, 5 );
6
Information technology
Information technology
PROGRAM-3: (BoxDraw.java)
Information technology
Source:
// <applet code="BoxDraw.class" width=600 height=600> </applet>
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class BoxDraw extends Applet implements MouseListener, MouseMotionListener
{
/* declare graphics object and integers for size of rect
*/
// private Graphics g;
int firstX=0, firstY=0, lastX, lastY, width=0,height=0;
public void init( )
{
System.out.println("init");
}
public BoxDraw()
{
/* make the applet a listener to mouse events
*/
addMouseListener(this);
addMouseMotionListener(this);
System.out.println("boxdraw");
}
public void paint(Graphics g)
{
/* draw the rectangle with the graphics object
*/
g.drawRect(firstX,firstY,width,height);
}
public void mousePressed(MouseEvent evt)
{
firstX = evt.getX(); // initial width and height
firstY = evt.getY();
}
public void mouseDragged(MouseEvent evt)
{
lastX=evt.getX();
width=lastX-firstX; // set the width
lastY=evt.getY();
height=lastY-firstY; // set the height
repaint();
}
9
Information technology
/* these empty methods are here because all the methods in the listener interfaces must be
implemented
*/
public void mouseMoved(MouseEvent evt)
{
}
public void mouseEntered(MouseEvent evt)
{
}
public void mouseExited(MouseEvent evt)
{
}
public void mouseClicked(MouseEvent evt)
{
}
public void mouseReleased(MouseEvent evt)
{
}
}
OUTPUT:
PROGRAM-4: (Card.java)
Write an applet that demonstrates cardlayout ?
10
Information technology
Source:
// <applet code="Card.class" width=300 height=300> </applet>
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class Card extends Applet implements ActionListener
{ CardLayout cl;
Panel p;
static String[] names =
{ "This", "is", "a", "layout", "tester" };
public void init( )
{ p = new Panel( );
cl = new CardLayout( );
p.setLayout( cl );
for ( int i = 0; i < names.length; ++i )
{ Button b = new Button( names[i] );
p.add( b, names[i] );
b.addActionListener( this );
}
add( p );
}
public void actionPerformed( ActionEvent evt )
{ cl.next( p );
}
}
OUTPUT:
PROGRAM-5: (ChoiceMu.java)-choice menu
Write an applet that demonstrates choice class and itemevent?
11
Information technology
Source:
//<applet code="ChoiceMu.class" width=300 height=300> </applet>
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class ChoiceMu extends Applet implements ItemListener
{
String shape = "Circle";
public void init ( )
{ Choice c = new Choice( );
c.addItem( "Circle" );
c.addItem( "Square" );
c.addItem( "Oval" );
c.addItem( "Rectangle" );
add( c );
c.addItemListener( this );
}
public void itemStateChanged( ItemEvent evt )
{ shape = (String) evt.getItem( );
repaint( );
}
public void paint( Graphics g )
{ g.setColor( Color.blue );
if ( "Circle".equals( shape ) )
g.fillOval( 50,50,40,40 );
if ( "Oval".equals( shape ) )
g.fillOval( 50,50,40,60 );
if ( "Square".equals( shape ) )
g.fillRect( 50,50,40,40 );
if ( "Rectangle".equals( shape ) )
g.fillRect( 50,50,40,60 );
}
}
OUTPUT:
PROGRAM-6: (CkBoxTst.java)-enabling
Write an applet that demonstrates checkboxes and itemevent?
12
Information technology
PROGRAM-7: (DialogTst.java)-enabling
Write an application program that demonstrates dialog box?
Source:
13
Information technology
Information technology
Source:
// <applet code="Gridbag.class" width=500 height=500> </applet>
15
Information technology
import java.awt.*;
public class Gridbag extends java.applet.Applet
{
void post ( String name,
GridBagLayout gb,
GridBagConstraints gbc )
{
Button b = new Button( name );
gb.setConstraints( b, gbc );
add( b );
}
public void init( )
{
GridBagLayout gb = new GridBagLayout( );
GridBagConstraints gbc = new GridBagConstraints( );
setLayout( gb );
gbc.anchor = GridBagConstraints.SOUTH;
gbc.fill = GridBagConstraints.BOTH;
/* Row One - One button */
gbc.gridwidth = GridBagConstraints.REMAINDER;
post( "One", gb, gbc );
/* Row Two - Two buttons */
gbc.gridwidth = GridBagConstraints.RELATIVE;
post( "Two", gb, gbc );
gbc.gridwidth = GridBagConstraints.REMAINDER;
post( "Three", gb, gbc );
/* Row Three - Three buttons */
gbc.weightx = 1.0;
gbc.gridwidth = 1;
post( "Four", gb, gbc );
gbc.gridwidth = GridBagConstraints.RELATIVE;
post( "Five12345", gb, gbc );
gbc.gridwidth = GridBagConstraints.REMAINDER;
post( "S", gb, gbc );
gbc.weightx = 0.0;
/* Row Four - One Three High, Three One High */
gbc.gridwidth = 1;
gbc.gridheight = 3;
16
Information technology
PROGRAM-9: (ListTest.java)
Write an applet that demonstrates the list class and itemevents?
Source:
// <applet code="ListTest.class" width=600 height=600> </applet>
import java.awt.*;
17
Information technology
PROGRAM-10: (MenuTest.java)
Write an application program that demonstrates MenuBar class?
Source:
import java.awt.*;
import java.awt.event.*;
18
Information technology
Information technology
OUTPUT:
Information technology
Source:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class HelloJava4
{
public static void main( String[] args ) {
JFrame frame = new JFrame( "HelloJava4" );
frame.add( new HelloComponent4("Hello, Java!") );
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.setSize( 300, 300 );
frame.setVisible( true );
}
}
class HelloComponent4 extends JComponent
implements MouseMotionListener, ActionListener, Runnable
{
String theMessage;
int messageX = 125, messageY = 95; // Coordinates of the message
JButton theButton;
int colorIndex; // Current index into someColors.
static Color[] someColors = {
Color.black, Color.red, Color.green, Color.blue, Color.magenta };
boolean blinkState;
public HelloComponent4( String message ) {
theMessage = message;
theButton = new JButton("Change Color");
setLayout( new FlowLayout( ) );
add( theButton );
theButton.addActionListener( this );
addMouseMotionListener( this );
Thread t = new Thread( this );
t.start( );
}
public void paintComponent( Graphics g ) {
g.setColor(blinkState ? getBackground( ) : currentColor( ));
g.drawString(theMessage, messageX, messageY);
}
public void mouseDragged(MouseEvent e) {
messageX = e.getX( );
21
Information technology
pROGRAM-12: (TempConvertor.java)
and
Source:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
22
Information technology
Fahrenheit-centigrade
Information technology
Information technology
PROGRAM-13: (Jtabp1.java)-jtabbedpane
Write an application program that demonstrates JTabbedpane?
Source:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class jtabp1 extends JFrame implements MouseListener
{
//private JPopupMenu popupMenu = new LaFPopupMenu(this);
25
Information technology
public jtabp1()
{
super("JTabbedPane 1");
JPanel p = new JPanel();
p.add("North", Box.createRigidArea(new Dimension(1, 5)));
JLabel l = new JLabel("Appointment Schedule", JLabel.CENTER);
l.setFont(new Font("Roman", Font.BOLD, 18));
p.add("Center", l);
p.add("South", Box.createRigidArea(new Dimension(1, 5)));
getContentPane().add("North", p);
String[] tab = {
"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
};
String[] tabLabel = {
"January", "February", "March",
"April", "May", "June",
"July", "August", "September",
"October", "November", "December"
};
Color[] color = {Color.lightGray, Color.pink, Color.white};
JTabbedPane tp = new JTabbedPane();
for (int i = 0; i < tab.length; ++i) {
tp.addTab(tab[i], createPane(tabLabel[i]));
tp.setBackgroundAt(i, color[i % 3]);
}
tp.setSelectedIndex(3);
getContentPane().add("Center", tp);
// popup menu for controlling L&F
addMouseListener( this );
// listeners, etc.
//addWindowListener(new DetectWindowClose());
setSize(300, 200);
show();
}
static public void main(String[] args)
{
new jtabp1();
}
private JPanel createPane(String text)
{
JPanel p = new JPanel();
p.add("North", new JLabel("--- " + text + " ---"));
return p;
}
// MouseListener methods
26
Information technology
PROGRAM-14: (Jtable1.java)-jtable
Write an application program that demonstrates JTable and JScrollpane?
Source:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class jtable1 extends JFrame implements MouseListener
{
// private JPopupMenu popupMenu = new LaFPopupMenu(this);
private String[] colHeading = {
"Last Name", "First Name", "City", "State"
27
Information technology
Information technology
PROGRAM-15: (JLsitSimpleExample.java)-jlist
Write an application program that demonstrates simple JList?
Source:
import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.border.*;
public class JListSimpleExample extends JFrame {
public static void main(String[] args) {
new JListSimpleExample();
}
private JList sampleJList;
private JTextField valueField;
29
Information technology
public JListSimpleExample() {
super("Creating a Simple JList");
setDefaultCloseOperation(DISPOSE_ON_CLOSE );
Container content = getContentPane();
// Create the JList, set the number of visible rows, add a
// listener, and put it in a JScrollPane.
String[] entries = { "Entry 1", "Entry 2", "Entry 3",
"Entry 4", "Entry 5", "Entry 6" };
sampleJList = new JList(entries);
sampleJList.setVisibleRowCount(4);
Font displayFont = new Font("Serif", Font.BOLD, 18);
sampleJList.setFont(displayFont);
sampleJList.addListSelectionListener(new ValueReporter());
JScrollPane listPane = new JScrollPane(sampleJList);
JPanel listPanel = new JPanel();
listPanel.setBackground(Color.white);
Border listPanelBorder =
BorderFactory.createTitledBorder("Sample JList");
listPanel.setBorder(listPanelBorder);
listPanel.add(listPane);
content.add(listPanel, BorderLayout.CENTER);
JLabel valueLabel = new JLabel("Last Selection:");
valueLabel.setFont(displayFont);
valueField = new JTextField("None", 7);
valueField.setFont(displayFont);
JPanel valuePanel = new JPanel();
valuePanel.setBackground(Color.white);
Border valuePanelBorder =
BorderFactory.createTitledBorder("JList Selection");
valuePanel.setBorder(valuePanelBorder);
valuePanel.add(valueLabel);
valuePanel.add(valueField);
content.add(valuePanel, BorderLayout.SOUTH);
pack();
setVisible(true);
}
private class ValueReporter implements ListSelectionListener {
public void valueChanged(ListSelectionEvent event) {
if (!event.getValueIsAdjusting())
valueField.setText(sampleJList.getSelectedValue().toString());
}
}
}
30
Information technology
Source:
import javax.swing.*;
import javax.swing.tree.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
class jtree1 extends JFrame implements TreeSelectionListener
, TreeExpansionListener
, MouseListener
{
//private JPopupMenu popupMenu = new LaFPopupMenu(this);
private JFrame frame = new JFrame("Listener Information");
31
Information technology
Information technology
Information technology
Information technology
Information technology
Information technology
OUTPUT:
37
Information technology
PROGRAM-17:( DynamicTree.java)
Write an application program that demonstrates dynamic tree ?
Source:
import java.awt.*;
import javax.swing.*;
public class DynamicTree extends JFrame {
public static void main(String[] args) {
int n = 5; // Number of children to give each node
if (args.length > 0)
try {
n = Integer.parseInt(args[0]);
} catch(NumberFormatException nfe) {
System.out.println("Can't parse number; using default of " + n);
}
new DynamicTree(n);
}
public DynamicTree(int n) {
super("Creating a Dynamic JTree");
38
Information technology
Packages:
A concept similar to class libraries
reusability in java, is to use packages.
Creating a package:
Declare a package at the beginning of the file using the form
package <package-name>.
Define the class that isto be put in the package and declare it public.
Create a subdirectory under the directory where the main source files are stored.
Store the listing as the <classname>.java file in the subdirectory created.
Compile the file.This creates .class file in the directory
We can compile with creating subdirectories by
javac -d <filename.java>
Java also supports package hierarchy. This is done by specifying them separated by
dots(.)
ex:- package firstpackage.secondpackage;
Accessing a package:
import package1 [.package2] [.package3].classname;
import packagename.*;
ex: import firstpackage.secondpackage.MyClass;
39
Information technology
Source:
Package02: :--creating package00 at Combined.java.p2 directory
package Combined.Java.p2;
public class Package02
{
public Package02()
{
System.out.println("Constructing Package02 object in folder p2");
}
}
Compilation:
--
Information technology
Compilation:
-- compile the program with javac d package01.java
Package00(main):-invoking packages
package Combined.Java;
import Combined.Java.p1.*;
import Combined.Java.p2.*;
class Package00{
public static void main(String s[]){
System.out.println("Starting Package00");
System.out.println("Instantiate obj of public " +
"classes in different packages");
new Package01();
new Package02();
System.out.println("Back in main of Package00");
}
}
OUTPUT:
C:\java Package00
C:\java Package00
Starting Package00
Instantiate obj of public Classes in different packages
Constructing Package02 object in folder p2
Constructing Package01 object in folder p1
Back in main of Package00
41
Information technology
PolyMorphism:
PROGRAM-19: (Poly03.java)
Write an application program that demonstrates polymorphism using classes?
Source:
class A extends Object{
public void m(){
System.out.println("m in class A");
}
}
class B extends A{
public void m(){
System.out.println("m in class B");
}
}
public class Poly03{
public static void main(String[] args){
Object var = new B();
B bref=new B();
//bref.m();
42
Information technology
PROGRAM-20: (Poly06.java)
Write an application program that demonstrates polymorphism using interfaces?
Source:
interface I1{
public void p();
}//end interface I1
//===================================//
interface I2 extends I1{
public void q();
}//end interface I2
//===================================//
class A extends Object{
public String toString(){
return "toString in A";
}//end toString()
//---------------------------------//
public String x(){
return "x in A";
}//end x()
//---------------------------------//
}//end class A
43
Information technology
Information technology
Threads:
Sharing a single CPU between multiple tasks (or "threads") in a way designed to
minimize the time required to switch tasks. This is accomplished by sharing as much as
possible of the program execution environment between the different tasks so that very little
state needs to be saved and restored when changing tasks.
45
Information technology
PROGRAM-21: (AddSync.java)
Write an application program that demonstrate Threads?
Source:
public class AddSync extends Thread {
static int value = 0;
public static void main(String arg[]) {
for(int i=0; i<50; i++) {
46
Information technology
PROGRAM-22: (producer.java,consumer.java)
Write an application program that demonstrates producer-consumer problem using
threads?
Source:
Producer:
47
Information technology
Information technology
49
Information technology
InnerClasses:
This feature lets you define a class as part of another class, just as fields and methods
are defined within classes.
Java defines four types of inner classes.
50
Information technology
A local class is an inner class defined within a block of Java code, such as within a
method or within the body of a loop. Local classes have local scope they can only be
used within the block in which they are defined. Local classes can refer to the
methods and variables of their enclosing classes. They are used mostly to implement
adapters, which are used to handle events.
An anonymous class is a local class whose definition and use are combined into a
single expression. Rather than defining the class in one statement and using it in
another, both operations are combined into a single expression. Anonymous classes
are intended for one-time use. Therefore, they do not contain constructors
When Java compiles a file containing a named inner class, it creates separate class files
for them with names that include the nesting class as a qualifier. For example, if you define
an inner class named Metric inside a top-level class named Converter, the compiler will
create a class file named Converter$Metric.class for the inner class. If you wanted to access
the inner class from some other class (besides Converter), you would use a qualified name:
Converter. Metric.
An anonymous class bytecode files are given names like ConverterFrame$1.class.
Eg1: Inner Classes Example Program
Eg2: Local Class
Eg3: Anonymous Class
PROGRAM-23: (ConverterUser.java)
Write an application program that converts meters to inches and kilograms to lbs and
display to console?
Source:
class Converter { private static final double INCH_PER_METER = 39.37;
private final double LBS_PER_KG = 2.2;
public static class Distance {
// Nested Top-level class
51
Information technology
PROGRAM-24: (ConverterUser.java)
Write an application program that converts meters to inches and kilograms to lbs and
display them using gui?
Source:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
52
Information technology
// Reference to app
public ConverterFrame() {
metersToInch = createJButton("Meters To Inches");
kgsToLbs = createJButton("Kilos To Pounds");
getContentPane().setLayout( new FlowLayout() );
getContentPane().add(inField);
getContentPane().add(outField);
getContentPane().add(metersToInch);
getContentPane().add(kgsToLbs);
} // ConverterFram()
private JButton createJButton(String s) { // A method to create a JButton
JButton jbutton = new JButton(s);
class ButtonListener implements ActionListener {
// Local class
public void actionPerformed(ActionEvent e) {
double inValue = Double.valueOf(inField.getText()).doubleValue();
JButton button = (JButton) e.getSource();
if (button.getText().equals("Meters To Inches"))
outField.setText(""+ new Converter.Distance().metersToInches(inValue));
else
outField.setText(""+ converter.new Weight().kgsToPounds(inValue));
} // actionPerformed()
} // ButtonListener class
ActionListener listener = new ButtonListener();
// Create a listener
jbutton.addActionListener(listener); // Register buttons with listener
return jbutton;
} // createJButton()
public static void main(String args[]) {
ConverterFrame frame = new ConverterFrame();
frame.setSize(200,200);
frame.setVisible(true);
} // main()
} // ConverterFrame class
OUTPUT:
53
Information technology
BEANS:
What exactly is or are JavaBeans? JavaBeans (the architecture) defines a set of rules;
Java beans are ordinary Java objects that play by these rules. That is, Java beans are Java
objects that conform to the JavaBeans API and design patterns. By doing so, they can be
recognized and manipulated within visual application builder environments, as well as by
hand coding. Beans live and work in the Java runtime system, as do all Java objects. They
communicate with their neighbors using events and other normal method invocations.
54
Information technology
-Here we are using the BEANBOX software which comes from sun.microsoft
How to open?
-Click on the run batch file which was placed in beansoftware/beanbox/
55
Information technology
Consists of:
1: tool box
2: Beanbox
3: properties
4: Jmethod traces
-the tool box loads the jar files placed in the beansoftware/jars folder or load the
jar file from file menu.
JAR (Java Archive) is a platform-independent file format that aggregates many files into
one. The JAR format also supports compression, which reduces the file size, further
improving the download time. In addition, the applet author can digitally sign individual
entries in a JAR file to authenticate their origin. It is fully extensible.
56
Information technology
Manifest Specification:
57
Information technology
:
:
:
:
:
:
:
:
:
PROGRAM-25(A): (NumericFiled.java,Textarea.java,Multiplier.java)
Write an application program that demonstrates user defined beans?
Source:
58
Information technology
59
Information technology
60
Information technology
-now place the myFile.jar in the beansoftware/jars folder or load the jar file from
file menu.
61
Information technology
Working:
Here we are dra the numeric fields named by placing TextLabels As val1 and val2,
result
And a multiplier is placed between these fields. We want that the values in numeric fields
val1, val2 is multiplied and displayed in result numericfiled using multiplier.
In the edit menu we have to bind properties values to a,b and the value of c is binded to the
result
And the appropriate roperties displayed in the properties box
PROGRAM-25(B): (MyNumericFiled.java,MyTextarea.java,MyMultiplier.java),and their infos
Write an application program that demonstrates user defined beans which extends
simplebeaninfo?
Source:
62
MyField.java
Information technology
63
Information technology
MyFieldBeanInfo.java
import java.beans.*;
public class MyFieldBeanInfo extends SimpleBeanInfo {
public PropertyDescriptor[] getPropertyDescriptors( ) {
try {
PropertyDescriptor pd1 = new
PropertyDescriptor("value", MyField.class);
pd1.setBound(true);
MYLABEL.JAVA
import javax.swing.JLabel;
public class MyLabel extends JLabel {
public void setText( String s ) {
super.setText(s);
if ( getParent( ) != null ) {
64
Information technology
invalidate( );
getParent().validate( );
}
}
}
MYLABELBEANINFO.JAVA
import java.beans.*;
public class MyLabelBeanInfo extends SimpleBeanInfo {
public PropertyDescriptor[] getPropertyDescriptors( ) {
try {
PropertyDescriptor pd1 = new
PropertyDescriptor("text", MyLabel.class);
pd1.setBound(true);
return new PropertyDescriptor [] { pd1 };
}
catch (IntrospectionException e) {
return null;
}
}
}
MYMULTIPLIER.JAVA
import java.beans.*;
public class MyMultiplier implements java.io.Serializable {
private double a, b, c;
synchronized public void setA( double val ) {
a = val;
multiply( );
}
65
Information technology
66
Information technology
import java.beans.*;
public class MyMultiplierBeanInfo extends SimpleBeanInfo {
public PropertyDescriptor[] getPropertyDescriptors( ) {
try {
PropertyDescriptor pd1 = new
PropertyDescriptor("a", MyMultiplier.class);
PropertyDescriptor pd2 = new
PropertyDescriptor("b", MyMultiplier.class);
PropertyDescriptor pd3 = new
PropertyDescriptor("c", MyMultiplier.class);
pd1.setBound(true);
pd2.setBound(true);
pd3.setBound(true);
Information technology
Manifest-Version: 1.0
Created-By: 1.2.2 (Sun Microsystems Inc.)
Name: MyField.class
Java-Bean: True
Name: MyLabel.class
Java-Bean: True
Name: MyMultiplier.class
Java-Bean: True
-now place the myFile.jar in the beansoftware/jars folder or load the jar file from
file menu.
68
Information technology
Working:
In this bean program we are implementing the beans which extends with simplebeaninfo
class.It results that in the previous illustrative example we can observe that we have the
properties of beans that are unnecessary and note that here we are observing with our defined
methods only
And the remaining continue from previous program.
69
Information technology
serialver
Steps:
Compile the java files and also rmi-implementation file must.
Next we can add the remote class by compiling the implementing class file
rmic <rmi-implementationfile>(class) - create a stub.class file.
Then start the rmi-registry service by command start rmiregistry
A new window opened indicates registry service started.
---Now run sever file first and dont close.
---And then run client file with sufficient port address along with arguments..
70
Information technology
Source:
Addserver.java
import java.net.*;
import java.rmi.*;
public class AddServer {
public static void main(String args[]) {
try {
AddServerImpl addServerImpl = new AddServerImpl();
Naming.rebind("AddServer", addServerImpl);
}
catch(Exception e) {
System.out.println("Exception: " + e);
}
}
}
AddServerIntf.java
import java.rmi.*;
public interface AddServerIntf extends Remote {
//public static final double pi=3.1456;
double add(double d1, double d2) throws RemoteException;
double mul(double d1, double d2) throws RemoteException;
public double div(double d1, double d2) throws RemoteException ;
public double sub(double d1, double d2) throws RemoteException ;
}
AddServerImpl.java
import java.rmi.*;
import java.rmi.server.*;
public class AddServerImpl extends UnicastRemoteObject
implements AddServerIntf {
public AddServerImpl() throws RemoteException {}
public double add(double d1, double d2) throws RemoteException {
return d1 + d2;
}
public double mul(double d1, double d2) throws RemoteException {
return d1 * d2;
}
71
Information technology
OUTPUT:
C:\java>javac AddServer.java
C:\java>javac AddServerIntf.java
C:\java>javac AddServerImpl.java
C:\java>javac AddClient.java
Now create a stub file using AddServerImpl.class
C:\java>rmic AddServerImpl
Now Start the registry service
C:\java>start rmiregistry
72
Information technology
73
Information technology
Servlets:
What is a Servlet?
Servlets are Java programs that can be run dynamically from a Web Server
A servlet is an intermediating layer between an HTTP request of a client and the Web
server
Look up other information about request in the HTTP request (e.g., headers, cookies,
etc.)
Generate the results (may do this by talking to a database, file system, etc.)
Set the appropriate HTTP response parameters (e.g., cookies, content-type, etc.)
74
Information technology
Supporting ServletsThe Web server must support servlets (since it must run the
servlets):
Apache Tomcat
Allaire Jrun an engine that can be added to IIS, PWS, old Apache Web
servers etc
Compiling
Servlet Package
Need to
import javax.servlet.*;
The Servlet interface defines methods that manage servlets and their communication
with clients
When a connection is formed, the servlet receives two objects that implement:
ServletRequest
ServletResponse
Information technology
And then edit the web.xml file (dont delete any matter in it just append your servlet tags as
mentioned below and save it.
<servlet>
<servlet-name> firstservlet</servlet-name>
<servlet-class>HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>firstservlet</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
76
Information technology
press enter
from the above web.xml document by placing the request as hello which is for
accessing HelloSevlet.class placed in webserver
request:
http://localhost:8080/hello
press enter
If we did not modify the web.xml document then it gives error service
There is another way to fulfill your request that is
Remove the comments for invoker servlet and servlet-mapping at
C:\Program Files\Apache Software Foundation\Tomcat 6.0\conf
Or
create the invoker servlet by editing
Then restart the tomcat-service.
77
Information technology
PROGRAM-27: (HelloServlet.java)
Write a servlet program that demonstrate simple servlet ?
Source:
import javax.servlet.*;
import java.io.*;
public class HelloServlet implements Servlet
{
private ServletConfig sConfig;
public void init(ServletConfig sc){
sConfig=sc;
}
public void service(ServletRequest req, ServletResponse res)throws IOException{
PrintWriter pw = res.getWriter();
res.setContentType("text/html");
pw.println("<html><body bgcolor=red>Hello,World</body></html>");
}
public void destroy(){}
public ServletConfig getServletConfig(){
return sConfig;
}
public String getServletInfo(){
return "A Simple Servlet";
}
}
OUTPUT:
C:\java>javac HelloServlet.java
Palce the class file at C:\Program Files\Apache Software Foundation\Tomcat
6.0\webapps\ROOT\WEB-INF\classes
And edit the xml document as
<servlet>
78
Information technology
PROGRAM-28: (FormData.html)
79
Information technology
Source:
OUTPUT:
PROGRAM-29: (ShowParameter.java)
80
Information technology
Write a servlet program that demonstrates the html file to request to showparameters
of the servlet?
Source:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
public class ShowParameters extends HttpServlet {
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String docType =
"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD
HTML 4.0 " +
"Transitional//EN\">\n";
String title = "Reading All Request Parameters";
out.println(docType +
"<HTML>\n" +
"<HEAD><TITLE>"+title +
"</TITLE></HEAD>\n"+
"<BODY BGCOLOR=\"#FDF5E6\">\n"
+
"<H1 ALIGN=CENTER>" + title +
"</H1>\n" +
"<TABLE BORDER=1
ALIGN=CENTER>\n" +
"<TR BGCOLOR=\"#FFAD00\">\n" +
"<TH>Parameter Name<TH>Parameter
Value(s)");
Enumeration paramNames = request.getParameterNames();
while(paramNames.hasMoreElements()) {
String paramName = (String)paramNames.nextElement();
out.print("<TR><TD>" + paramName + "\n<TD>");
String[] paramValues =
request.getParameterValues(paramName);
if (paramValues.length == 1) {
String paramValue = paramValues[0];
if (paramValue.length() == 0)
out.println("<I>No Value</I>");
else
out.println(paramValue);
} else {
out.println("<UL>");
for(int i=0; i<paramValues.length; i++) {
81
Information technology
PROGRAM-30: (ShowRequestHeaders.java)
Write a servlet program that demonstrates the html file to show headers of servlet?
82
Information technology
83
Information technology
PROGRAM-31: (RequestParameters.java)
Write a servlet program that demonstrates the html file to request the parameters of a
servlet?
84
Information technology
Information technology
JDBC
86
Using Oracle
If a student whose login is Snoopy wants to work directly with Oracle:
sqlplus snoopy/[email protected]
87
Information technology
Note: we use the login for a password! (Dont change your password)
88
Information technology
-we have to give classpath to existing oracle class driver which were installed in
the pc.
Classpath:
C:\oracle\ora92\jdbc\lib;
-
89
Information technology
PROGRAM-32: (dboperations.java)
Write an application program that access the database using jtabbedpane ?
Source:
//oracle driver (type 2 hybrid java driver)
import java.sql.*;
import oracle.jdbc.driver.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class dbOperations extends JFrame{
Connection conn;
Statement stmt;
ResultSet rset;
JTabbedPane dbJTP;
JPanel browsePanel,insertPanel,deletePanel;
dbOperations(String title){
super(title);
dbInit();
dbJTP=new JTabbedPane();
add(dbJTP);
browsePanel=new BrowsePanel();
insertPanel=new InsertPanel();
deletePanel=new DeletePanel();
dbJTP.addTab("Browse",browsePanel);
dbJTP.addTab("Insert",insertPanel);
dbJTP.addTab("Delete",deletePanel);
setVisible(true);
setSize(200,200);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void dbInit() {
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
}catch (ClassNotFoundException ex){
System.out.println(ex.getMessage());
}
try{
conn = DriverManager.getConnection
("jdbc:odbc:empdata", "scott", "tiger");
stmt = conn.createStatement(
90
Information technology
Information technology
Information technology
PROGRAM-33: (dbOracleType4.java)
93
Information technology
Write an application program that access the database operations using type 4 driver?
Source:
//oracle driver (type 4 pure java driver)
import java.sql.*;
import oracle.jdbc.driver.*;
class dbOracleType4 {
public static void main (String args []) throws SQLException
{
//DriverManager.registerDriver (new oracle.jdbc.driver.OracleDriver());
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
}catch (ClassNotFoundException ex){
System.out.println(ex.getMessage());
}
Connection conn = DriverManager.getConnection
("jdbc:oracle:thin:@localhost:1521:sivaram", "scott", "tiger");
// @machineName:port:SID, userid, password
Statement stmt = conn.createStatement();
ResultSet rset = stmt.executeQuery("select * from emp");
while (rset.next())
System.out.println (rset.getString(1)+ " "+ rset.getString(2)+ "
"+rset.getString(3)); // Print col 1
stmt.close();
}
}
OUTPUT:
PROGRAM-34: (dbOracleType2.java)
94
Information technology
Source:
//oracle driver (type 2 hybrid java driver)
import java.sql.*;
import oracle.jdbc.driver.*;
class dbOracleType2 {
public static void main (String args []) throws SQLException
{
//DriverManager.registerDriver (new oracle.jdbc.driver.OracleDriver());
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
}catch (ClassNotFoundException ex){
System.out.println(ex.getMessage());
}
Connection conn = DriverManager.getConnection
("jdbc:oracle:oci:@sivaram", "scott", "tiger");
// @machineName:port:SID, userid, password
Statement stmt = conn.createStatement();
ResultSet rset = stmt.executeQuery("select * from emp");
while (rset.next())
System.out.println (rset.getString(1)+ " "+ rset.getString(2)+ "
"+rset.getString(3)); // Print col 1
stmt.close();
conn.close();
}
}
OUTPUT:
PROGRAM-33: (JdbcExample.java)
Write a program that demonstrate the database operations on java with type 1 driver?
95
Information technology
Information technology
navPanel.add(first=new JButton("|<"));
navPanel.add(prev=new JButton("<<"));
navPanel.add(next=new JButton(">>"));
navPanel.add(last=new JButton(">|"));
navPanel.add(insert=new JButton("Insert"));
navPanel.add(delete=new JButton("Delete"));
add(BorderLayout.CENTER,deptPanel);
add(BorderLayout.SOUTH,navPanel);
first.addActionListener(this);
next.addActionListener(this);
prev.addActionListener(this);
last.addActionListener(this);
insert.addActionListener(this);
delete.addActionListener(this);
}
public void actionPerformed(ActionEvent ae){
String qry,cmd=ae.getActionCommand();
int j=0;
if(cmd.equals(">>"))
fillDetail(0);
else if(cmd.equals("<<"))
fillDetail(1);
else if(cmd.equals(">|"))
fillDetail(3);
else if(cmd.equals("|<"))
fillDetail(2);
else if(cmd.equals("Insert"))
{
qry="INSERT INTO DEPT VALUES(?,?,?)";
try{
pstmt=con.prepareStatement(qry,ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONC
UR_UPDATABLE);
int
departmentno=Integer.parseInt(JOptionPane.showInputDialog("Enter DNO"));
97
Information technology
Information technology
Information technology
OUTPUT:
100
Information technology
PROGRAM-34: (JdbcExample2.java)
101
Information technology
Write an application program that demonstrates the database operations on java with
type 1 driver?
Source:
import java.sql.*;
public class JdbcExample2 {
public static void main(String args[]) {
Connection con = null;
ResultSet rs;
CallableStatement stmt;
String query,regno;
int total;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:studentdata", "scott", "tiger");
if (!con.isClosed())
System.out.println("Successfully connected to Oracle Server...");
query="{ call HiSal(?) }";
stmt = con.prepareCall(query);
stmt.registerOutParameter(1, Types.INTEGER);
stmt.execute();
/* rs = (ResultSet)stmt.getObject(1);
System.out.println("REGNO"+"
"+"TOTAL");
while(rs.next())
{
rowNumber=rs.getRow();
regno=rs.getString(1);
total=rs.getInt(2);
System.out.println(regno+"
"+total);
}*/
int i=stmt.getInt(1);
System.out.println("The max salary is ::"+i);
} catch(Exception e) {
System.err.println("Exception: " + e.getMessage());
} finally {
try {
if (con != null)
102
Information technology
103
Information technology
NETWORK PROGRAMMING:
PROGRAM-35: (Server.java,Client.java)
Write an applcation program that demonstrate the interconnection between server and
client using datagrampacket ?
Source:
Server.java
import java.net.*;
import java.io.*;
104
Information technology
int clientPort;
InetAddress address;
String str;
Information technology
Information technology
107
Information technology
// main
} // Class Client
OUTPUT:
108
Information technology
PROGRAM-36: (EchoServer.java,EchoClient.java)
Write a program that demonstrate the interconnection between server and client using
sockets ?
Source:
EchoServer.java
import java.net.Socket;
import java.net.ServerSocket;
import java.io.*;
109
Information technology
110
Information technology
while (true) {
String theLine = userIn.readLine();
if (theLine.equals("."))
break;
sockOut.println(theLine);
sockOut.flush();
System.out.println(sockIn.readLine());
}
userIn.close();
sockIn.close();
sockOut.close();
}
}
OUTPUT:
111
Information technology
112
Information technology