0% found this document useful (0 votes)
5 views48 pages

Java Lab Work

Uploaded by

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

Java Lab Work

Uploaded by

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

Contents

1. Programming in Java ............................................................................................................................ 2


1.1. Class and object ............................................................................................................................ 2
1.2. Inheritance and interface ............................................................................................................. 6
1.3. Exception Handling ..................................................................................................................... 11
1.4. Multithreading ........................................................................................................................... 12
1.5. File IO .......................................................................................................................................... 16
1.5.1. Read Into & Write From File .............................................................................................. 16
1.5.2. Zip and UnZip File ............................................................................................................... 18
2. User Interface Components with swings ........................................................................................... 20
2.1. GUI tools (Buttons, Labels, Text fields, Dialog box, Tooltips, Menus, etc.) ............................. 20
2.2. Layout Managements ................................................................................................................. 25
2.2.1. Border Layout ..................................................................................................................... 25
2.2.2. Grid Layout ......................................................................................................................... 27
2.2.3. Flow Layout ........................................................................................................................ 29
3. Events Handling .................................................................................................................................. 32
4. Database Connectivity ....................................................................................................................... 34
5. Network Programming ....................................................................................................................... 34
5.1. Working with URLs ..................................................................................................................... 34
5.2. TCP sockets ................................................................................................................................. 35
6. Servlets ............................................................................................................................................... 37
6.1. HTTP Request and Response ...................................................................................................... 37
7. Java Server Pages ............................................................................................................................... 38
7.1. JSP Basic ...................................................................................................................................... 38
7.2. Creating and Processing Forms .................................................................................................. 39
7.3. Session Management ................................................................................................................. 42
8. RMI ...................................................................................................................................................... 47
8.1. Creating and Executing RMI Application ................................................................................... 47
1. Programming in Java
1.1. Class and object

Exercise 1
Implement the following classes and test its functions.

Solution:
public class Line {
private Point BEGIN=new Point();
private Point END=new Point();

public Line(int x1,int y1,int x2,int y2){


this.BEGIN.setX(x1);
this.BEGIN.setY(y1);
this.END.setX(x2);
this.END.setY(y2);
}
public Line(Point begin, Point end) {
this.BEGIN = begin;
this.END = end;
}
public Point getBEGIN() {
return BEGIN;
}
public void setBEGIN(Point begin) {
this.BEGIN = begin;
}
public Point getEND() {
return END;
}
public void setEND(Point end) {
this.END = end;
}
public int getBEGINX() {
return this.BEGIN.getX();
}
public int getBEGINY() {
return this.BEGIN.getY();
}
public void setBEGINX(int beginx) {
this.BEGIN.setX(beginx);
}
public void setBEGINY(int beginy) {
this.BEGIN.setX(beginy);
}
public void setBEGINXY(int beginx,int beginy) {
this.BEGIN.setX(beginx);
this.BEGIN.setY(beginy);
}
public int getENDX() {
return this.END.getX();
}

public int getENDY() {


return this.END.getY();
}

public void setENDX(int endx) {


this.END.setX(endx);
}

public void setENDY(int endy) {


this.END.setX(endy);
}

public void setENDXY(int endx,int endy) {


this.END.setX(endx);
this.END.setY(endy);
}

@Override
public String toString(){
return(" Begin @("+this.getBEGINX()+","+this.getBEGINY()+") &
END @("+this.getENDX()+","+this.getENDY()+")");
}
public double getLength(){
double xDiff = this.getBEGINX()-this.getENDX();
double yDiff = this.getBEGINY()-this.getENDY();
double result = Math.sqrt((xDiff*xDiff)+(yDiff*yDiff));
return(result);
}
}

public class Point {


private int X;
private int Y;

public Point(){

}
public Point(int x, int y) {
this.X = x;
this.Y = y;
}
public int getX() {
return X;
}

public void setX(int X) {


this.X = X;
}

public int getY() {


return Y;
}

public void setY(int Y) {


this.Y = Y;
}

@Override
public String toString(){
return("Point @ ("+this.getX()+","+this.getY()+")");
}

public class test {


public static void main(String[] args) {
Point P1 =new Point();
Point P2 =new Point(5,6);
Point P3 =new Point(7,8);
System.out.println("X:"+P1.getX()+",Y:"+P1.getY());
System.out.println("X:"+P2.getX()+",Y:"+P2.getY());
System.out.println(P1.toString());
System.out.println(P2.toString());

Line L1=new Line(1,2,3,4);


System.out.println("Begin (X:"+L1.getBEGINX()+",Y:"+L1.getBEGINY()+")");
System.out.println("END (X:"+L1.getENDX()+",Y:"+L1.getENDY()+")");
Line L2=new Line(P2,P3);
System.out.println("Begin (X:"+L2.getBEGINX()+",Y:"+L2.getBEGINY()+")");
System.out.println("END (X:"+L2.getENDX()+",Y:"+L2.getENDY()+")");
L2.setBEGINXY(9, 8);
System.out.println("Begin (X:"+L2.getBEGINX()+",Y:"+L2.getBEGINY()+")");
System.out.println("END (X:"+L2.getENDX()+",Y:"+L2.getENDY()+")");
System.out.println(L2.getBEGIN());
System.out.println(L2.getEND());
System.out.println("Line 1 "+L1.toString());
System.out.println("Line 2 "+L2.toString());
System.out.println("Distance1: "+L1.getLength());
System.out.println("Distance2: "+L2.getLength());
}

}
Outputs

1.2. Inheritance and interface

Exercise 2: (Inheritance & Interface)


Write a program to represent geometric shapes and some operations that can be performed on
them. The idea here is that shapes in higher dimensions inherit data from lower dimensional
shapes. For example a cube is a three dimensional square. A sphere is a three dimensional circle
and a glom is a four dimensional circle. A cylinder is another kind of three dimensional circle.
The circle, sphere, cylinder, and glom all share the attribute radius. The square and cube share
the attribute side length. There are various ways to use inheritance to relate these shapes but
please follow the inheritance described in the table below.
All shapes inherit getName() from the superclass Shape.
Specification:
Your program will consist of the following classes: Shape, Circle, Square, Cube, Sphere,

Cylinder, and Glome and two interfaces Area and Volume (Area.java and Volume.java are
given below).
Your classes may only have the class variable specified in the table below and the methods
defined in the two interfaces Area and Volume. You will implement the methods specified in
the Area and Volume interfaces and have them return the appropriate value for each shape.
Class Shape will have a single public method called getName that returns a string.

Class Class Variable Constructor Extends Implements


Shape String name Shape()
Circle double radius Circle( double r, String n ) Shape Area
Square double side Square( double s, String n ) Shape Area
Cylinder double height Cylinder(double h, double r, String n ) Circle Volume
Sphere None Sphere( double r, String n ) Circle Volume
Cube None Cube( double s, String n ) Square Volume
Glome None Glome( double r, String n ) Sphere Volume

Note: the volume of a glome is 0.5(π2)r4 where r is the radius


Solution:
Area.java
public interface Area {

public double getArea();


}
Volume.java
public interface Volume {

public double getVolume();

}
Circle.java
public class Circle extends Shape implements Area{
private double RADIUS;

public Circle(double r,String n){


super(n);
this.RADIUS=r;
}

public double getRADIUS() {


return RADIUS;
}

@Override
public double getArea() {
return(Math.PI*this.RADIUS*this.RADIUS);
}
}
Cube.java
public class Cube extends Square implements Volume {

public Cube(double s, String n) {


super(s, n);
}

@Override
public double getVolume() {
return(super.getSIDE()*super.getSIDE()*super.getSIDE());
}

}
Cylinder.java
public class Cylinder extends Circle implements Volume {
private double HEIGHT;

public Cylinder(double height, double r, String n) {


super(r, n);
this.HEIGHT = height;
}

public double getHEIGHT() {


return HEIGHT;
}

public double getVolume() {


return(super.getArea()*this.HEIGHT);
}
}
Glome.java
public class Glome extends Sphere implements Volume{

public Glome(double r, String n) {


super(r, n);
}

@Override
public double getVolume(){
return(0.5*super.getArea()*super.getArea());
}
}
Shape.java
public class Shape {
private String NAME;

public Shape(String s){


this.NAME=s;
}

public String getNAME() {


return NAME;
}
}
Sphere.java
public class Sphere extends Circle implements Volume {

public Sphere(double r, String n) {


super(r, n);
}

@Override
public double getVolume() {
return(4/3*super.getArea()*super.getRADIUS());
}
}
Square.java
public class Square extends Shape implements Area {
private double SIDE;

public Square(double side,String n) {


super(n);
this.SIDE = side;
}

public double getSIDE() {


return SIDE;
}

@Override
public double getArea() {
return(this.getSIDE()*this.getSIDE());
}

}
Test.java
public class test {
public static void main(String[] args) {
Circle C=new Circle(5,"Circle1");
Cube Cu=new Cube(3,"Cube1");
Cylinder Cy=new Cylinder(7,6,"Cylinder1");
Sphere S=new Sphere(8,"Sphere1");
Square Sq=new Square(6,"Square1");
Glome G=new Glome(9,"Glome1");

System.out.println(C.getNAME()+" has Radius:"+C.getRADIUS()+", Area:"+C.getArea());


System.out.println(Cu.getNAME()+" has Radius:"+Cu.getSIDE()+", Volume:"+Cu.getVolume());
System.out.println(Cy.getNAME()+" has Height:"+Cy.getHEIGHT()+",
Radius:"+Cy.getRADIUS()+", Volume:"+Cy.getVolume());
System.out.println(S.getNAME()+" has Radius:"+S.getRADIUS()+", Volume:"+S.getVolume());
System.out.println(Sq.getNAME()+" has Side:"+Sq.getSIDE()+", Area:"+Sq.getArea());
System.out.println(G.getNAME()+" has Radius:"+G.getRADIUS()+", Volume:"+G.getVolume());
}
}
Outputs

1.3. Exception Handling


ExceptionExample.java

import java.util.Random;

class ExceptionExample {

public static void main(String args[]) {

int a = 0, b = 0, c = 0;

Random r = new Random();

for (int i = 0; i < 10; i++) {

try {

b = r.nextInt();

c = r.nextInt();

a = 12345 / (b / c);
} catch (ArithmeticException e) {

System.out.println("Division by zero");
a = 0;

System.out.println("a: " + a);

Output

1.4. Multithreading
ExtendThread.java

public class ExtendThread extends Thread {

private int sleepTime;

public ExtendThread(String name) {

super(name);

sleepTime = (int) (Math.random() * 5000);


System.out.println("Thread Name: " + getName() + " "

+ ";Sleep Time :" + sleepTime);

}
public void run() {

try {

System.out.println(getName() + " is going to sleep");

Thread.sleep(sleepTime);

System.out.println();

} catch (Exception e)
{ System.out.println(e.toString());

System.out.println(getName()+" is done sleeping");

ImplementThread.java

public class ImplementThread implements Runnable {

private int sleepTime;

private String name;

public ImplementThread(String name) {

this.name = name;

sleepTime = (int) (Math.random() * 5000);


System.out.println("Thread Name: " + getName() + " "

+ ";Sleep Time :" + sleepTime);

@Override

public void run() {

Thread th = new Thread();

try {
System.out.println(getName() + " is going to sleep");

th.sleep(sleepTime);

} catch (Exception e)
{ System.out.println(e.toString());

System.out.println(getName() + " is done sleeping");

private String getName() {

return this.name;

MultithreadingDemo.java

public class MultiThreadingDemo {

public static void main(String[] args) {

ExtendThread Thread1, Thread2, Thread3, Thread4;

Thread1 = new ExtendThread("Thread1");

Thread2 = new ExtendThread("Thread2");

Thread3 = new ExtendThread("Thread3");

Thread4 = new ExtendThread("Thread4");

/ ImplementThread IThread1, IThread2, IThread3, IThread4;

/ IThread1 = new ImplementThread(" IThread1");

/ IThread2 = new ImplementThread(" IThread2");

/ IThread3 = new ImplementThread(" IThread3");

/ IThread4 = new ImplementThread(" IThread4");

/ Thread obj1 = new Thread(IThread1);

/ Thread obj2 = new Thread(IThread2);

/ Thread obj3 = new Thread(IThread3);


/ Thread obj4 = new Thread(IThread4);

System.out.println("Starting Threads");

Thread1.start();

Thread2.start();

Thread3.start();

Thread4.start();

/ obj1.start();

/ obj2.start();;

/ obj3.start();

/ obj4.start();

System.out.println("Thread has been started");

Output
1.5. File IO
1.5.1. Read Into & Write From File

ReadFromFile.java

import java.io.BufferedReader;

import java.io.FileNotFoundException;

import java.io.FileReader;

import java.io.IOException;

public class ReadFromFile {

String filelocation = "E:\\abc.docx";

FileReader fr = null;

BufferedReader br = null;

public ReadFromFile() {}

public void readDateFromFile() throws IOException


{ try {

fr = new FileReader(filelocation);

br = new BufferedReader(fr);

String line="";

while ((line = br.readLine()) != null) {

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

} catch (FileNotFoundException ex) {


System.out.println(ex.toString());

} finally {

if (fr != null) {

fr.close();

br.close();

}
}}}
WriteToFile.java

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

public class WriteToFile {

String filelocation = "E:\\new.txt";

String outputFile = "E:\\new(copy).txt";

FileInputStream in = null;

FileOutputStream out = null;

public WriteToFile() throws IOException {}

public void writeDataToFile() throws IOException {

try {

in = new FileInputStream(filelocation);

out = new FileOutputStream(outputFile);

int size;

while ((size = in.read()) != -1) {

out.write(size);

} catch (FileNotFoundException ex) {

System.out.println(ex.toString());

} finally {

in.close();

out.close();

}
FileIO.java

import java.io.IOException;

public class FileIO {

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


ReadFromFile rff = new ReadFromFile();

WriteToFile wrf = new WriteToFile();

try {

rff.readDateFromFile();

wrf.writeDataToFile();

} catch (IOException ex)


{ System.out.println(ex.toString()
);
}}}

1.5.2. Zip and UnZip File


Zip.java

import java.io.*;

import java.util.zip.DeflaterOutputStream;

public class Zip {

public static void main(String[] args) throws FileNotFoundException, IOException {

FileInputStream fis = new FileInputStream("E:\\abc.docx");

FileOutputStream fos = new FileOutputStream("E:\\zip");


DeflaterOutputStream dos = new DeflaterOutputStream(fos);
int data;

while((data = fis.read())!=-1){

dos.write(data);

}
dos.close();

fos.close();

fis.close();

}}
Unzip.java

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

import java.util.zip.InflaterInputStream;

public class Unzip {

public static void main(String[] args) throws FileNotFoundException, IOException {


FileInputStream fis = new FileInputStream("E:\\zip");

FileOutputStream fos = new FileOutputStream("E:\\Unzip.docx");

InflaterInputStream iis = new InflaterInputStream(fis); int data;

while ((data = iis.read()) != -1) {

fos.write(data);

iis.close();

fos.close();

fis.close();

}
2. User Interface Components with swings
2.1. GUI tools (Buttons, Labels, Text fields, Dialog box,
Tooltips, Menus, etc.)

GUIToolsDemo.java

import java.awt.Container;

import java.awt.GridLayout;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import javax.swing.ButtonGroup;

import javax.swing.ImageIcon;

import javax.swing.JButton;

import javax.swing.JComboBox;

import javax.swing.JFileChooser;

import javax.swing.JFrame;

import javax.swing.JLabel;

import javax.swing.JMenu;

import javax.swing.JMenuBar;

import javax.swing.JMenuItem;
import javax.swing.JPasswordField;

import javax.swing.JRadioButton;

import javax.swing.JTextArea;

import javax.swing.JTextField;

import javax.swing.TransferHandler;

import javax.swing.filechooser.FileNameExtensionFilter
;

public class GUIToolsDemo extends JFrame implements ActionListener {

private JButton btnSubmit,btnCancel;

private JTextField txtName;

public GUIToolsDemo() {

super("GUIToolsDemo");

Container con = getContentPane();

con.setLayout(new FlowLayout());

JLabel lblName= new JLabel();

lblName.setText("Name:");

con.add(lblName);

txtName = new JTextField("kkkk");

txtName.setText("Enter Name...");

txtName.setDragEnabled(true);

con.add(txtName);

JLabel lblPass= new JLabel("password");

con.add(lblPass);

JPasswordField txtPass= new JPasswordField();

txtPass.setText("*******");

con.add(txtPass);

JLabel lblgender = new JLabel("Gender");


con.add(lblgender);

JRadioButton rdMale = new JRadioButton("Male");

JRadioButton rdFemale = new JRadioButton("Female");

ButtonGroup genderGroup = new ButtonGroup();

genderGroup.add(rdMale);

genderGroup.add(rdFemale);

con.add(rdMale);

con.add(rdFemale);

JLabel lblCourse = new JLabel("Course");

con.add(lblCourse);

String[] courses = {"java Programming ", "PHP", "ROR",


"ASP.Net","Python"}; JComboBox cmbCourses = new JComboBox(courses);

con.add(cmbCourses);

JLabel lblComments= new JLabel("Comments");

con.add(lblComments);

JTextArea txtComments= new JTextArea("Comments


here..."); con.add(txtComments);

btnSubmit = new JButton("Submit");

btnSubmit.addActionListener(this);

btnCancel = new JButton("Cancel");

btnCancel.addActionListener(this);

con.add(btnSubmit);

btnCancel.setToolTipText("This button does nothing");

btnSubmit.setTransferHandler(new TransferHandler("text"));

con.add(btnCancel);

JMenuBar mainMenu = new JMenuBar();

JMenu fileMenu = new JMenu("FILE");


JMenuItem newProject = new JMenuItem(" New project");

fileMenu.add(newProject);

mainMenu.add(fileMenu);

final JFileChooser fc = new JFileChooser();

FileNameExtensionFilter filter = new FileNameExtensionFilter("All Files", "*.*");

fc.setFileFilter(filter);

fc.showOpenDialog(this);

JMenu editMenu = new JMenu("EDIT");

JMenuItem copy = new JMenuItem(" copy");

JMenuItem cut = new JMenuItem(" cut");

JMenuItem paste = new JMenuItem("paste");

fileMenu.add(newProject);

editMenu.add(cut);

cut.setIcon(new ImageIcon("C:\\Users\\Prashant Gautam\\Documents\\


NetBeansProjects\\GUIToolsDemo\\src\\icons/cut.png"));

editMenu.add(copy);

editMenu.add(paste);

mainMenu.add(editMenu);

setJMenuBar(mainMenu);

setSize(500, 600);

setVisible(true);

public static void main(String[] args) { GUIToolsDemo guiDemo


= new GUIToolsDemo();
guiDemo.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// TODO code application logic here

}
@Override

public void actionPerformed(ActionEvent e) {

if(e.getSource()==btnSubmit)

String s= this.txtName.getText();

System.out.println("Submit Button is pressed");

else if(e.getSource()== btnCancel)

String s="Dummy text";

this.txtName.setText(s);

/int a= Integer.parseInt(s);
System.out.println("Cancel button is pressed");

Outputs
2.2. Layout Managements
2.2.1. Border Layout
BorderLayoutDemo.java

import java.awt.BorderLayout;

import java.awt.Container;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import javax.swing.JButton;

import javax.swing.JFrame;

public class BorderLayoutDemo extends JFrame implements ActionListener


{ private JButton buttons[];

private String names[] = {"HIDE NORTH", "HIDE SOUTH", "HIDE EAST","HIDE WEST", "HIDE CENTER"};

private BorderLayout layout;

public BorderLayoutDemo() {

super("BorderLayout Demo");

layout = new BorderLayout();

Container con = getContentPane();

con.setLayout(layout);

buttons = new JButton[names.length];

for (int i = 0; i < names.length; i++) {

buttons[i] = new JButton(names[i]);

}
con.add(buttons[0], BorderLayout.NORTH);

buttons[0].addActionListener(this);

con.add(buttons[1], BorderLayout.SOUTH);

buttons[1].addActionListener(this);

con.add(buttons[2], BorderLayout.EAST);

buttons[2].addActionListener(this);

con.add(buttons[3], BorderLayout.WEST);

buttons[3].addActionListener(this);

con.add(buttons[4], BorderLayout.CENTER);

buttons[4].addActionListener(this);

setSize(400, 400);

setVisible(true);

public static void main(String[] args) { BorderLayoutDemo

app = new BorderLayoutDemo();

app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

@Override

public void actionPerformed(ActionEvent e) {

for (int i = 0; i <= 4; i++) {

if (e.getSource() == buttons[i]) {

buttons[i].setVisible(false);

}
Output

2.2.2. Grid Layout


GridLayoutDemo.java

import java.awt.Container;

import java.awt.GridLayout;

import javax.swing.JButton;

import javax.swing.JFrame;

public class GridLayoutDemo extends JFrame {

private JButton buttons[];

private String names[] = {"Button1", "Button2", "Button3",

"Button4", "Button5","Button6", "Button7",

"Button8", "Button9"};

private GridLayout layout;


public GridLayoutDemo() {

super("Grid Layout Demo");

layout = new GridLayout(3, 3);

Container con = getContentPane();

con.setLayout(layout);

for (int i = 0; i < names.length; i++) {

con.add(new JButton("MyButton" + (i + 1)));

setSize(400, 400);

setVisible(true);

public static void main(String[] args) { GridLayoutDemo app =

new GridLayoutDemo();

app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

Output
2.2.3. Flow Layout
FlowLayoutDemo.java

import java.awt.Container;

import java.awt.FlowLayout;

import java.awt.LayoutManager;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import javax.swing.JButton;

import javax.swing.JFrame;

public class Flowlayout extends JFrame{

private JButton btnLeft,btnRight,btnCenter;

FlowLayout layout;

public Flowlayout(){

super("Flow layout demo");


Container con = getContentPane();

layout = new FlowLayout();

con.setLayout(layout);

con.add(btnLeft = new JButton("LEFT"));

btnLeft.addActionListener(new ActionListener() {

@Override

public void actionPerformed(ActionEvent e) {

layout.setAlignment(FlowLayout.LEFT);

layout.layoutContainer(con);

});

con.add(btnRight = new JButton("Right"));


btnRight.addActionListener(new ActionListener()
{ @Override

public void actionPerformed(ActionEvent e) {

layout.setAlignment(FlowLayout.RIGHT);

layout.layoutContainer(con);

});

con.add(btnCenter = new JButton("Center"));


btnCenter.addActionListener(new ActionListener()
{ @Override

public void actionPerformed(ActionEvent e) {

layout.setAlignment(FlowLayout.CENTER);

layout.layoutContainer(con);
}

});

setSize(400,400);

setVisible(true);

public static void main(String[] args) { Flowlayout app =


new Flowlayout();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

Outputs
3. Events Handling
GUIEventHandling.java

public class GUIEventHandling extends JFrame implements ActionListener {

private String[] countyName = {"Nepal", "India", "USA", "Select Country"};

private JComboBox cmbCountry;

private JTextField txtCodeNumber;

private JTextField txtMobileNumber;

public GUIEventHandling() {

super("GUI EventHandling");

Container con = getContentPane();

con.setLayout(new FlowLayout());

con.add(new JLabel("Country"));

cmbCountry = new JComboBox(countyName);

cmbCountry.setToolTipText("Select Country");

cmbCountry.addActionListener(this);

con.add(cmbCountry);

con.add(new JLabel("Mobile NO:"));

con.add(txtCodeNumber = new JTextField("", 3));

con.add(new JLabel("-"));

con.add(txtMobileNumber = new JTextField("", 10));

setSize(500, 500);

setVisible(true);

public static void main(String[] args)


{ GUIEventHandling App = new
GUIEventHandling();
App.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

@Override

public void actionPerformed(ActionEvent e) {

if (e.getSource().equals(cmbCountry)) {

if (cmbCountry.getSelectedItem().toString() == "Nepal")
{ txtCodeNumber.setText("+977");

} else if (cmbCountry.getSelectedItem().toString() == "India") {


txtCodeNumber.setText("+91");

} else if (cmbCountry.getSelectedItem().toString() == "USA")


{ txtCodeNumber.setText("+1");

} else {

txtCodeNumber.setText("");

} Outputs
4.Database Connectivity

5.Network Programming
5.1. Working with URLs
ParseURL.java
import java.net.*;
import java.io.*;
public class ParseURL {
public static void main(String[] args) throws Exception {
URL aURL = new
URL("http://example.com:80/docs/books/tutorial"
+
"/index.html?
name=networking#DOWNLOADIN
G");

System.out.println("protocol = " +
aURL.getProtocol());
System.out.println("authority = " +
aURL.getAuthority());
System.out.println("filename = " +
aURL.getFile()); System.out.println("host
= " + aURL.getHost());
System.out.println("port = " +
aURL.getPort());
System.out.println("path
= " + aURL.getPath());
System.out.println("query = " +
aURL.getQuery());
System.out.println("ref
= " + aURL.getRef());

}
}
Output
protocol = http
authority = example.com:80
host = example.com
port = 80
path = /docs/books/tutorial/index.html
query = name=networking
filename = /docs/books/tutorial/index.html?
name=networking ref = DOWNLOADING

5.2. TCP sockets


Client.java

import java.io.DataOutputStream;

import java.io.IOException;

import java.io.OutputStream;

import java.net.*;

public class Client {

String message;

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


OutputStream ostream = null;

Socket sock = null;

DataOutputStream dos = null;

String message;

try {

sock = new Socket("127.0.0.1", 5001);

message = "Hello Server ";

ostream = sock.getOutputStream();

dos = new DataOutputStream(ostream);

dos.writeBytes(message);

} catch (IOException ex)


{ System.out.println(ex.toString()
);
} finally
{ dos.close(
);

ostream.close();

sock.close();

Server.java

import java.io.DataInputStream;

import java.io.IOException;

import java.io.InputStream;

import java.net.*;

public class Server {

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

ServerSocket serSock = null;

DataInputStream dis = null;

InputStream istream = null;

Socket cSock = null;

try {

serSock = new ServerSocket(5001);

System.out.println("Server started!");

cSock = serSock.accept();

istream = cSock.getInputStream();

dis = new DataInputStream(istream);

String msg = dis.readLine();

System.out.println("From client :" + msg);


} catch (IOException ex)
{ System.out.println(ex.toString()
);

} finally {

dis.close();

istream.close();

cSock.close();

serSock.close();

Outputs

6. Servlets
6.1. HTTP Request and Response

HelloServlet.java

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;
import javax.sql.rowset.serial.SerialException;

public class HelloServlet extends HttpServlet {

public HelloServlet(){}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException{

response.setContentType("text/html;charset= UTF-8");

PrintWriter write = response.getWriter();

write.println("HELLO WORLD!!");

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws


ServletException, IOException{

7. Java Server Pages


7.1. JSP Basic
Index.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>

<!DOCTYPE html>

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">


<title>JSP Page</title>

</head>

<body>

<h1>Hello World!!</h1>

</body>

</html>
Output

7.2. Creating and Processing Forms


Myjsp.html

<html>
<head>
<title>Form Handling</title>
</head>
<body>
<form method="post" action ="mypage.jsp">
<table width="400" border="5" align="center">
<tr>
<td colspan="5" align="center"><h1>JSP form
Demo</h1></td>
</tr>
<tr>
<td>User Name:</td>
<td><input type='text' name='name'/></td>
</tr>

<tr>
<td>Phone N0:</td>
<td><input type='text' name='phone'/></td>
</tr>
<tr>

<td colspan='5' align='center'><input type=


'submit' name='submit' value='Done'/></td>

</tr>
</form>
</body>
Mypage.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>

<%--<meta http-equiv="Content-Type" content="text/html;


charset=UTF-8">--%> <title>JSP Page</title>
</head>
<body>
Name= <%= request.getParameter("name")%>
<br>
Phone=<%= request.getParameter("phone")%>
</body>
</html>
Outputs
7.3. Session Management
Index.jsp

<%@page import="java.util.Date"%>

<%

Integer visitCount = new Integer(0);

String visitCountKey = new String("Visit count");

String userID = new String("prashant");

String UserIDKey = new String("userID");

Date creationTime = new Date(session.getCreationTime());

Date lastAcessTime = new Date(session.getLastAccessedTime());

if(session.isNew()){

session.setAttribute(UserIDKey, userID);

session.setAttribute(visitCountKey, visitCount);

visitCount= (Integer)session.getAttribute(visitCountKey);

visitCount = visitCount+1;

session.setAttribute(visitCountKey, visitCount);

creationTime = new Date(session.getCreationTime());

lastAcessTime = new Date(session.getLastAccessedTime());

userID = (String)session.getAttribute(UserIDKey);

%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>

<!DOCTYPE html>

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">


<title>JSP Page</title>

</head>

<body>
<form>

<table width='400' border='5' align='center'>

<tr>

<td colspan='5' align='center'><h1>SESSION INFORMATION</h1></td>

</tr>

<tr>

<td>user ID</td>

<td> <%out.print(userID);%></td>

</tr>

<tr>

<td>Session ID</td>

<td> <%out.print(session.getId());%></td>

</tr>

<tr>

<td>Creation Time</td>

<td><%out.print(creationTime);%></td>

</tr>

<tr>

<td>Last Access Time</td>

<td><%out.print(lastAcessTime);%></td>

</tr>

<tr>

<td>Number of Visits</td>

<td><%out.print(visitCount);%></td>

</tr>
<tr>

<td>GOTO:</td>

<td><a href="afterSession.jsp"> Link to next page</a></td>

</tr>

</form>

</body>

</html>

afterSession.jsp

<%

String user = (String)session.getAttribute("userID");

if(user==null){

%>

<jsp:forward page="index.jsp"></jsp:forward>

<%}%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>

<!DOCTYPE html>

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">


<title>JSP Page</title>

</head>

<body>

<h1>After Session</h1>

<p> <%out.print(user);%></p>

<p><a href="destroySession.jsp">Destroy Session</a></p>


</body>

</html>
beforSession.jsp

<%

String user = (String)session.getAttribute("userID");

if(user==null){

%>

<jsp:forward page="index.jsp"></jsp:forward>

<%}%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>

<!DOCTYPE html>

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">


<title>JSP Page</title>

</head>

<body>

<h1>After Session</h1>

<p> <%out.print(user);%></p>

<p><a href="destroySession.jsp">Destroy Session</a></p>

</body>

</html>
Outputs
8. RMI
8.1. Creating and Executing RMI Application

RMIInterface.java

import java.rmi.Remote;

public interface RMIinterface extends Remote {

public int add( int x, int y);

Client.java

import java.rmi.registry.LocateRegistry;

import java.rmi.registry.Registry;

public class Client {

public static void main(String[] args) {

try {

Registry reg = LocateRegistry.getRegistry("127.0.0.1",1099);

RMIinterface stub = (RMIinterface) reg.lookup("key");

int respons=stub.add(2,5);

System.out.println("SUM="+ respons);

} catch (Exception e) {

Server.java

import java.rmi.registry.LocateRegistry;

import java.rmi.registry.Registry;

import java.rmi.server.UnicastRemoteObject;

public class Server implements RMIinterface{


public static void main(String[] args) {

try {

Server s = new Server();

RMIinterface stub = (RMIinterface) UnicastRemoteObject.exportObject(s,

0); Registry reg = LocateRegistry.createRegistry(1099); reg.bind("key", stub);

System.out.println("Server ready");

} catch (Exception e) {

@Override

public int add(int x, int y) {

return (x+y);

Outputs

SUM= 7

You might also like