You are on page 1of 58

SHANTILAL SHAH ENGG.

COLLEGE, BHAVNAGAR

AJT- 170703

PRACTICAL 1 (AWT)
1) Write an AWT program to create check boxes for different courses
belongs to a university such that the course selected would be displayed.
import java.applet.Applet;
import java.awt.*;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.*;
public class pract1 extends Applet implements ItemListener,ActionListener
{
Button b1;
Checkbox IT = null;
Checkbox CE = null;
Checkbox mech = null;
Checkbox EE = null;
Checkbox EC = null;
Checkbox civil = null;
public void init()
{
IT = new Checkbox("IT");
CE = new Checkbox("CE");
mech = new Checkbox("mech");
EE = new Checkbox("EE");
EC = new Checkbox("EC");
civil = new Checkbox("Civil");
b1 = new Button("Output");
add(IT);add(CE);add(mech);add(EE);add(EC);add(civil);
add(b1);
b1.addActionListener(this);
IT.addItemListener(this);
CE.addItemListener(this);
mech.addItemListener(this);
EE.addItemListener(this);
EC.addItemListener(this);
civil.addItemListener(this);
}
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == b1)
{
repaint();
}
}
public void paint(Graphics g)
{
int i=10;
int k=60;
INFORMATION TECHNOLOGY DEPARMENT

SHANTILAL SHAH ENGG. COLLEGE, BHAVNAGAR

AJT- 170703

if(IT.getState()==true)
{
g.drawString("IT",10,k+=20);
}
if(CE.getState()==true)
{
g.drawString("CE",10,k+=20);
}
if(mech.getState()==true)
{
g.drawString("mech",10,k+=20);
}
if(EE.getState()==true)
{
g.drawString("EE",10,k+=20);
}
if(EC.getState()==true)
{
g.drawString("EC",10,k+=20);
}
if(civil.getState()==true)
{
g.drawString("civil",10,k+=20);
}
}
public void itemStateChanged(ItemEvent ie)
{
//repaint();
}
}

Output:

INFORMATION TECHNOLOGY DEPARMENT

SHANTILAL SHAH ENGG. COLLEGE, BHAVNAGAR

AJT- 170703

2) Create a list of vegetables if you click on one of the items of the list items
would be displayed in text box.
import java.applet.Applet;
import java.awt.Graphics;
import java.awt.*;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
/*
<applet code="pract2" width=200 height=200>
</applet>
*/
public class pract2 extends Applet implements ItemListener
{
List list = null;
TextField a;
public void init()
{
a = new TextField( 70);
//create a multi select list
list = new List(5, true);
//add items to a list
list.add("potatoes,");
list.add("Brinjal,");
list.add("Cabbage,");
list.add("Carrot,");
list.add("Onion,");
list.add("Mint,");
list.add("potato,");
//add list
add(list);
add(a);
//add listener
list.addItemListener(this);
}
public void paint(Graphics g)
{
String[] items = list.getSelectedItems();
String msg = "";
for(int i=0; i < items.length; i++)
{
msg = items[i] + " " + msg;
}
a.setText("vegetables:"+ msg);
}
public void itemStateChanged(ItemEvent ie)
{
repaint();
}
}
INFORMATION TECHNOLOGY DEPARMENT

SHANTILAL SHAH ENGG. COLLEGE, BHAVNAGAR

AJT- 170703

Output:

INFORMATION TECHNOLOGY DEPARMENT

SHANTILAL SHAH ENGG. COLLEGE, BHAVNAGAR

AJT- 170703

PRACTICAL 2 (SWING)
3) Create a login form which contains user ID, password field and two
buttons submit and reset. If the user ID and password is left blank on
click of submit button, show a message to the user to fill in the fields, on
click of reset button clear the fields.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
publicclass login extendsJFrame
{
privateJLabel jLabel1;
privateJLabel jLabel2;
privateJTextField jTextField1;
privateJPasswordField jPasswordField1;
privateJButton jButton1;
privateJPanel contentPane;
public login()
{
super();
create();
this.setVisible(true);
}
privatevoid create()
{
jLabel1 = newJLabel();
jLabel2 = newJLabel();
jTextField1 = newJTextField();
jPasswordField1 = newJPasswordField();
jButton1 = newJButton();
contentPane = (JPanel)this.getContentPane();
jLabel1.setHorizontalAlignment(SwingConstants.LEFT);
jLabel1.setForeground(newColor(0, 0, 255));
jLabel1.setText("username:");
jLabel2.setHorizontalAlignment(SwingConstants.LEFT);
jLabel2.setForeground(newColor(0, 0, 255));
jLabel2.setText("password:");
jTextField1.setForeground(newColor(0, 0, 255));
jTextField1.setSelectedTextColor(newColor(0, 0, 255));
jTextField1.setToolTipText("Enter your username");
jTextField1.addActionListener(newActionListener(){
publicvoid actionPerformed(ActionEvent e)
{
jTextField1_actionPerformed(e);
}
}
jPasswordField1.setForeground(newColor(0, 0, 255));
jPasswordField1.setToolTipText("Enter your password");
INFORMATION TECHNOLOGY DEPARMENT

SHANTILAL SHAH ENGG. COLLEGE, BHAVNAGAR

AJT- 170703

jPasswordField1.addActionListener(newActionListener()
{
publicvoid actionPerformed(ActionEvent e)
{
jPasswordField1_actionPerformed(e);
}
}
jButton1.setBackground(newColor(204, 204, 204));
jButton1.setForeground(newColor(0, 0, 255));
jButton1.setText("Login");
jButton1.addActionListener(newActionListener(){
publicvoid actionPerformed(ActionEvent e)
{
jButton1_actionPerformed(e);
}
}
contentPane.setLayout(null);
contentPane.setBorder(BorderFactory.createEtchedBorder());
contentPane.setBackground(newColor(204, 204, 204));
addComponent(contentPane, jLabel1, 5,10,106,18);
addComponent(contentPane, jLabel2, 5,47,97,18);
addComponent(contentPane, jTextField1, 110,10,183,22);
addComponent(contentPane, jPasswordField1, 110,45,183,22);
addComponent(contentPane, jButton1, 150,75,83,28);
this.setTitle("Login To Members Area");
this.setLocation(newPoint(76, 182));
this.setSize(newDimension(335, 141));
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
this.setResizable(false);
}
privatevoid addComponent(Container container,Component c,int x,int y,int
width,int height)
{
c.setBounds(x,y,width,height);
container.add(c);
}
privatevoid jTextField1_actionPerformed(ActionEvent e){}
privatevoid jPasswordField1_actionPerformed(ActionEvent e){}
privatevoid jButton1_actionPerformed(ActionEvent e)
{
System.out.println("\njButton1_actionPerformed(ActionEvent e) called.");
String username = newString(jTextField1.getText());
String password = newString(jPasswordField1.getText());
if(username.equals("") || password.equals(""))
{
jButton1.setEnabled(false);

INFORMATION TECHNOLOGY DEPARMENT

SHANTILAL SHAH ENGG. COLLEGE, BHAVNAGAR

AJT- 170703

JLabel errorFields = newJLabel("<HTML><FONT COLOR =


Blue>You must entera username and password to
login.</FONT></HTML>");
JOptionPane.showMessageDialog(null,errorFields);
jTextField1.setText("");
jPasswordField1.setText("");
jButton1.setEnabled(true);
this.setVisible(true);
}
else{
JLabel optionLabel = newJLabel("<HTML><FONT COLOR =
Blue>You entered</FONT><FONT COLOR =
RED><B>"+username+"</B></FONT><FONT COLOR =Blue>as
your username.<BR> Is this correct?</FONT></HTML>");
int confirm =JOptionPane.showConfirmDialog(null,optionLabel);
switch(confirm)
{
caseJOptionPane.YES_OPTION:
jButton1.setEnabled(false);
break;
caseJOptionPane.NO_OPTION:
jButton1.setEnabled(false);
jTextField1.setText("");
jPasswordField1.setText("");
jButton1.setEnabled(true);
break;
caseJOptionPane.CANCEL_OPTION:
jButton1.setEnabled(false);
jTextField1.setText("");
jPasswordField1.setText("");
jButton1.setEnabled(true);
break;
}
}
}
publicstaticvoid main(String[] args)
{
JFrame.setDefaultLookAndFeelDecorated(true);
JDialog.setDefaultLookAndFeelDecorated(true);
try{
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.Wi
ndowsLookAndFeel");
}
catch(Exception ex){
System.out.println("Failed loading L&F: ");
System.out.println(ex);
INFORMATION TECHNOLOGY DEPARMENT

SHANTILAL SHAH ENGG. COLLEGE, BHAVNAGAR

AJT- 170703

}
new login();
}
}

Output:

Fig: Showing Login Form One with Empty Username And Password

INFORMATION TECHNOLOGY DEPARMENT

SHANTILAL SHAH ENGG. COLLEGE, BHAVNAGAR

AJT- 170703

4) Create a split pane which divides the frame into two parts .process a list
and on selecting an item in a list the items should be displayed in the
other portion.
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.event.*;
public class pract4
{
@SuppressWarnings("deprecation")
public static void main(String[] args)
{
JFrame frame = new SplitPaneFrame();
frame.show();
}
}
class SplitPaneFrame extends JFrame implements ListSelectionListener
{
public SplitPaneFrame()
{
setSize(400, 300);
list = new JList(texts);
list.addListSelectionListener(this);
description = new JTextArea();
JSplitPane innerPane= new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
list, description);
getContentPane().add(innerPane, "Center");
}
public void valueChanged(ListSelectionEvent event)
{
JList source = (JList)event.getSource();
Display value = (Display)source.getSelectedValue();
description.setText(value.getDescription());
}
private JList list;
private JTextArea description;
private Display[] texts =
{
new Display("Text1", "This is text1."),
new Display("Text2", "This is text2."),
new Display("Text3", "This is text3."),
new Display("Text4", "This is text4.")
};
}
class Display
{
public Display(String n, String t)

INFORMATION TECHNOLOGY DEPARMENT

SHANTILAL SHAH ENGG. COLLEGE, BHAVNAGAR

AJT- 170703

{
name = n;
des = t;
}
public String toString()
{
return name;
}
public String getDescription()
{
return des;
}
private String name;
private String des;
}

Output:

Figure: Output of split pan

INFORMATION TECHNOLOGY DEPARMENT

10

SHANTILAL SHAH ENGG. COLLEGE, BHAVNAGAR

AJT- 170703

PRACTICAL 3 (JDBC)
5) Write a JDBC program to insert details of college student in the MS
Access database.
/* database connectivity with MS-Access is done by creating
DataSourceName(dsn) in this example*/
/* Steps to use this example:
* go to ms-access and make a database called "student_base" and create
table named student_base.mdb
* 1. Go to Control Panel
2.
Click on Administrative Tools(windows 2000/xp), Click onODBC(win98) OR if u
have (windows 7) than go to C:\Windows\SysWOW64\odbcad32.exe
3.
click on ODBC
4.
Then , you will see a ODBC dialog box. Click on UserDSn
5.
Click on Add Button
6.
Select Microsoft Access Driver(*.mdb) driver and click on finish
7.
Give a Data Source Name : student_base
8.
Then Click on Select
9.
Browse on the database addItemDB.mdb file on your disk by downloading it link
provided..
will be stored
10. Click on OK.
Once the DSN is created, you can do this example*/
//Java Core Package
import javax.swing.*;
//Java Extension Package
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
public class addItemToDatabase extends JFrame
{
//Initializing Components
private JTextField inputs[];
private JButton add, reset;
private JLabel labels[];
private String fldLabel[] = {"First Name: ","Last Name: ","Branch","Enroll-no "};
private JPanel p1;
Connection con;
Statement st;
ResultSet rs;
String db;

INFORMATION TECHNOLOGY DEPARMENT

11

SHANTILAL SHAH ENGG. COLLEGE, BHAVNAGAR

AJT- 170703

//Setting up GUI
public addItemToDatabase()
{
//Setting up the Title of the Window
super("Adding Data to the Database");
//Set Size of the Window (WIDTH, HEIGHT)
setSize(300,180);
//Exit Property of the Window
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Constructing Components
inputs = new JTextField[4];
labels = new JLabel[4];
add = new JButton("Add");
reset = new JButton("Reset");
p1 = new JPanel();
//Setting Layout on JPanel 1 with 5 rows and 2 column
p1.setLayout(new GridLayout(5,2));
//Setting up the container ready for the components to be added.
Container pane = getContentPane();
setContentPane(pane);
//Setting up the container layout
GridLayout grid = new GridLayout(1,1,0,0);
pane.setLayout(grid);
//Creating a connection to MS Access and fetching errors using "try-catch" to check if
it is successfully connected or not.
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
//db = "jdbc:odbc:Driver={Microsoft Access Driver
(*.accdb)};DBQ=nilesh1.accdb;";
con = DriverManager.getConnection("jdbc:odbc:nilesh");
st = con.createStatement();
JOptionPane.showMessageDialog(null,"Successfully
Connected to Database","Confirmation", JOptionPane.INFORMATION_MESSAGE);
}
catch (Exception e)
{
JOptionPane.showMessageDialog(null,"Failed to Connect to
Database","Error Connection", JOptionPane.ERROR_MESSAGE);
System.exit(0);
}
//Constructing JLabel and JTextField using "for loop" in their desired order
for(int count=0; count<inputs.length && count<labels.length; count++) {
labels[count] = new JLabel(fldLabel[count]);
INFORMATION TECHNOLOGY DEPARMENT

12

SHANTILAL SHAH ENGG. COLLEGE, BHAVNAGAR

AJT- 170703

inputs[count] = new JTextField(20);


//Adding the JLabel and the JTextFied in JPanel 1
p1.add(labels[count]);
p1.add(inputs[count]);
}
//Implemeting Even-Listener on JButton add
add.addActionListener(new ActionListener()
{
//Handle JButton event if it is clicked
public void actionPerformed(ActionEvent event)
{
if (inputs[0].getText().equals("") ||
inputs[1].getText().equals("") || inputs[2].getText().equals("") || inputs[0].getText() == null ||
inputs[1].getText() == null || inputs[2].getText() == null || inputs[3].getText().equals("") ||
inputs[3].getText() == null)
JOptionPane.showMessageDialog(null,"Fill up all the
Fields","Error Input", JOptionPane.ERROR_MESSAGE);
else
try
{
String add = "insert into nilesh
(firstName,LastName,Branch,Enroll-no) values ('"+inputs[0].getText()
+"','"+inputs[1].getText()+"','"+inputs[2].getText()+"','"+inputs[3].getText()+"')";
st.execute(add); //Execute the add sql
Integer.parseInt(inputs[3].getText()); //Convert
JTextField Age in to INTEGER
JOptionPane.showMessageDialog(null,"Item
Successfully Added","Confirmation", JOptionPane.INFORMATION_MESSAGE);
}
catch (NumberFormatException e)
{
JOptionPane.showMessageDialog(null,"Please enter an
integer on the Field Enroll-no","Error Input", JOptionPane.ERROR_MESSAGE);
}
catch (Exception ei)
{
JOptionPane.showMessageDialog(null,"Failure to Add
Item. Please Enter a number on the Field Enroll-no","Error Input",
JOptionPane.ERROR_MESSAGE);
}
}
}
);
INFORMATION TECHNOLOGY DEPARMENT

13

SHANTILAL SHAH ENGG. COLLEGE, BHAVNAGAR

AJT- 170703

//Implemeting Even-Listener on JButton reset


reset.addActionListener(new ActionListener()
{
//Handle JButton event if it is clicked
public void actionPerformed(ActionEvent event) {
inputs[0].setText(null);
inputs[1].setText(null);
inputs[2].setText(null);
inputs[3].setText(null);
}
}
);
p1.add(add);
p1.add(reset);
pane.add(p1);
setVisible(true);
}
//Main Method
public static void main (String[] args) {
addItemToDatabase aid = new addItemToDatabase();
}
}

Output:

INFORMATION TECHNOLOGY DEPARMENT

14

SHANTILAL SHAH ENGG. COLLEGE, BHAVNAGAR

AJT- 170703

Write Jdbc Program To Manage The Hospital Information In The


Database
import java.sql.*;
import java.util.Scanner;
public class ContectManager
{
static Scanner input=new Scanner(System.in);
static int ch=0;
static String cname,surname,query;
static String phone;
static int age,contect_id;
static boolean gender;
public static void main(String[] args)
{
AccessConnection Acon=new AccessConnection();
Connection con=Acon.MakeConnection();
do
{
System.out.println("1. Insert");
System.out.println("2. Delet");
System.out.println("3. Update");
System.out.println("4. Display");
System.out.println("5. Exit");
ch=input.nextInt();
switch(ch)
{
case 1:
System.out.println(" Plz, Insert data");
getinput();
query="insert into
shiv(cname,surname,gender,phone,age)values" +
"('"+cname+"','"+surname+"',"+gender+",'"+pho
ne+"',"+age+")";
try
{
Statement command=con.createStatement();
command.executeUpdate(query);
System.out.println("Data is Inserted");
}
catch(SQLException error)
{
System.out.println("Error In Insert");
}

INFORMATION TECHNOLOGY DEPARMENT

15

SHANTILAL SHAH ENGG. COLLEGE, BHAVNAGAR

AJT- 170703

break;
case 2:
System.out.println("Enter the id to delete row");
contect_id=getcontect_id();
query="delete from shiv where id="+contect_id;
try
{
Statement command1=con.createStatement();
command1.execute(query);
System.out.println("Data is deleted");
}
catch(SQLException error)
{
System.out.println("Error In Deleted id");
}
case 3:
System.out.println("Update your id");
contect_id=getcontect_id();
getinput();
query="update shiv set
cname='"+cname+"',surname='"+surname+"',gender="+gender+"" +
"phone='"+phone+"',age="+age+" where
id="+contect_id;
try
{
Statement command3=con.createStatement();
command3.executeUpdate(query);
System.out.println("contect update");
}
catch(SQLException error)
{
System.out.println("contect Not update");
}
case 4:
System.out.println("Display");
query="select * from shiv";
try
{
Statement command4=con.createStatement();
ResultSet shiv=command4.executeQuery(query);
int count=0;
while(shiv.next())
{

INFORMATION TECHNOLOGY DEPARMENT

16

SHANTILAL SHAH ENGG. COLLEGE, BHAVNAGAR

AJT- 170703

System.out.println("contect
id="+shiv.getInt("id"));
System.out.println("contect
cname="+shiv.getString("cname"));
System.out.println("contect
surname="+shiv.getString("surname"));
System.out.println("contect
gender="+shiv.getBoolean("gender"));
System.out.println("contect
phone="+shiv.getString("phone"));
System.out.println("contect
age="+shiv.getInt("age"));
count++;
}
System.out.println("total Record"+count);
}
catch(SQLException error)
{
System.out.println("error Display");
}
default:
}
}while(ch!=5);
}
public static int getcontect_id()
{
System.out.println("Enter id");
int temp=input.nextInt();
return temp;
}
public static void getinput()
{
System.out.println("Patient Name");
cname=input.next();
System.out.println("Age");
surname=input.next();
System.out.println("1. Male 2. Female");
gender=input.nextBoolean();
System.out.println("Phone no");
phone=input.next();
System.out.println("Symtoms");
age=input.nextInt();
}
}
INFORMATION TECHNOLOGY DEPARMENT

17

SHANTILAL SHAH ENGG. COLLEGE, BHAVNAGAR

AJT- 170703

import java.sql.*;
public class AccessConnection
{
private String ConnectionString=null;
private String DatabaseName=null;
public AccessConnection()
{
System.out.println("constructed called");
ConnectionString="jdbc:odbc:sadashiv";
DatabaseName="sadashiv";
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
System.out.println("Driver Loaded");
}
catch(ClassNotFoundException error)
{
System.out.println("Error in Driver loaded ,check Spelling");
}
}
public Connection MakeConnection()
{
Connection con=null;
try
{
con=DriverManager.getConnection(ConnectionString);
System.out.println("Connection Establish");
}
catch(SQLException error)
{
System.out.println("Error in Connection,check
dsn"+this.ConnectionString);
}
return con;
}
}

INFORMATION TECHNOLOGY DEPARMENT

18

SHANTILAL SHAH ENGG. COLLEGE, BHAVNAGAR

AJT- 170703

PRACTICAL 4 (NETWORKING)
6) Create a UDP echo client server application where in whatever is
written in UDP server is written back to client
Client.java
import java.net.*;
class UDP_Client
{
public static DatagramSocket mySocket;
public static byte myBuffer[]=new byte[2000];
public static void clientMethod() throws Exception
{
while(true)
{
DatagramPacket dataPacket=new
DatagramPacket(myBuffer,myBuffer.length);
mySocket.receive(dataPacket);
System.out.println("Message Recieved :");
System.out.println(new
String(dataPacket.getData(),0,dataPacket.getLength()));
}
}
public static void main(String args[]) throws Exception
{
System.out.println("You need to press CTRL+C in order to quit");
mySocket=new DatagramSocket(777);
clientMethod();
}
}
Server.java
import java.net.*;
class UDP_Server
{
public static DatagramSocket mySocket;
public static byte myBuffer[]=new byte[2000];
public static void serverMethod() throws Exception
{
int position=0;
while(true)
{
int charData=System.in.read();
switch(charData){
case -1: System.out.println("The execution of the
server has been terminated");
return;
case '\r':break;
case '\n':mySocket.send(new

INFORMATION TECHNOLOGY DEPARMENT

19

SHANTILAL SHAH ENGG. COLLEGE, BHAVNAGAR

AJT- 170703

DatagramPacket(myBuffer,position,InetAddress.getLocalHost(),7
77));
position=0;
break;
default:
myBuffer[position++]=(byte) charData;
}
}
}
public static void main(String args[]) throws Exception
{
System.out.println("Please enter some text here");
mySocket=new DatagramSocket(888);
serverMethod();
}
}

Output:

INFORMATION TECHNOLOGY DEPARMENT

20

SHANTILAL SHAH ENGG. COLLEGE, BHAVNAGAR

AJT- 170703

7) Write a java program that implements a simple client/server


application. The client sends data to a server. The server receives
the data, uses it to produce a result, and then sends the result back
to the client. The client displays the result on the console.
Client program
import java.io.*;
import java.net.*;
class Client
{
public static void main(String[] args) throws Exception
{
Socket s=new Socket("localhost",8080);
BufferedReader br;
PrintStream ps;
String str;
System.out.println("enter the radius to send the server");
br=new BufferedReader(new InputStreamReader(System.in));
ps=new PrintStream(s.getOutputStream());
ps.println(br.readLine());
br=new BufferedReader(new InputStreamReader(s.getInputStream()));
str=br.readLine();
System.out.println("Area of circle:"+str);
ps.close();
br.close();
}
}
Server program:
import java.io.*;
import java.net.*;
class Server
{
public static void main(String[] args)
{
try{
ServerSocket ss=new ServerSocket(8080);
System.out.println("wait for client request");
Socket s=ss.accept();
BufferedReader br;
PrintStream ps;
String str;
INFORMATION TECHNOLOGY DEPARMENT

21

SHANTILAL SHAH ENGG. COLLEGE, BHAVNAGAR

AJT- 170703

br=new BufferedReader(new InputStreamReader(s.getInputStream()));


str=br.readLine();
System.out.println("recieved radius"); double r=Double.parseDouble(str);
double area=3.14*r*r;
ps=new PrintStream(s.getOutputStream());
ps.println(String.valueOf(area));
ps.close();
br.close();
s.close();
ss.close();
}
catch(Exception e)
{
System.out.println("exception occur at:"+e.toString());
}
}
}

Output:

INFORMATION TECHNOLOGY DEPARMENT

22

SHANTILAL SHAH ENGG. COLLEGE, BHAVNAGAR

AJT- 170703

8) Create TCP chat application where client and server can chat with
each other.
Client.java
import java.io.*;
import java.net.*;
class TCP_Client
{
public static void main(String args[ ])
throws Exception
{
Socket s = new Socket("localhost", 888);
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
BufferedReader br = new BufferedReader(new
InputStreamReader(s.getInputStream()));
BufferedReader kb = new BufferedReader(new
InputStreamReader(System.in));
String str,str1;
while(!(str = kb.readLine()).equals("exit"))
{
dos.writeBytes(str+"\n"); //send to server
str1 = br.readLine(); //receive from server
System.out.println(str1);
}
dos.close();
br.close();
kb.close();
s.close();
}
}
Server.java
import java.io.*;
import java.net.*;
class TCP_Server
{
public static void main(String args[ ])
throws Exception
{
ServerSocket ss = new ServerSocket(888);
Socket s = ss.accept();
System.out.println("Connection established");
PrintStream ps = new PrintStream(s.getOutputStream());
BufferedReader br = new BufferedReader(new
InputStreamReader(s.getInputStream()));
BufferedReader kb = new BufferedReader(new
InputStreamReader(System.in));
while(true)
{
String str,str1;
while((str = br.readLine()) != null) {
System.out.println(str);
INFORMATION TECHNOLOGY DEPARMENT

23

SHANTILAL SHAH ENGG. COLLEGE, BHAVNAGAR

AJT- 170703

str1 = kb.readLine();
ps.println(str1);
}
ps.close();br.close();kb.close();
ss.close();s.close();System.exit(0);
}
}
}

Output:

INFORMATION TECHNOLOGY DEPARMENT

24

SHANTILAL SHAH ENGG. COLLEGE, BHAVNAGAR

AJT- 170703

9) Create a Client Server application where client request on a


particular file on the server. If the file exists on the server then write
the content on the client
Client.java
import java.io.*;
import java.net.*;
class FileClient
{
public static void main(String args[ ]) throws Exception
{
Socket s = new Socket("localhost", 8888);
BufferedReader kb = new BufferedReader(new
InputStreamReader(System.in));
System.out.print("Enter filename: ");
String fname = kb.readLine();
DataOutputStream out = new DataOutputStream(s.getOutputStream());
out.writeBytes(fname+"\n");
BufferedReader in = new BufferedReader(new
InputStreamReader(s.getInputStream()));
String str;
str = in.readLine();
if(str.equals("Yes")){
while((str = in.readLine()) != null)
System.out.println(str);
kb.close();
out.close();
in.close();
s.close();
}
else System.out.println("File not found");
}
}
Server.java
import java.io.*;
import java.net.*;
class FileServer
{
public static void main(String args[ ]) throws Exception
{
ServerSocket ss = new ServerSocket(8888);
Socket s = ss.accept();
System.out.println("Connection established");
BufferedReader in = new BufferedReader(new
InputStreamReader(s.getInputStream()));
DataOutputStream out = new DataOutputStream(s.getOutputStream());
String fname = in.readLine();
FileReader fr = null;
BufferedReader file = null;
INFORMATION TECHNOLOGY DEPARMENT

25

SHANTILAL SHAH ENGG. COLLEGE, BHAVNAGAR

AJT- 170703

boolean flag;File f = new File(fname);


if(f.exists()) flag = true;
else flag = false;
if(flag == true) out.writeBytes("Yes"+"\n");
else out.writeBytes("No"+"\n");
if(flag == true)
{
fr = new FileReader(fname);
file = new BufferedReader(fr);
String str;
while((str = file.readLine()) != null){
out.writeBytes(str+"\n");
}
file.close();out.close();in.close();fr.close();s.close();ss.close();
}
}
}

Output:

INFORMATION TECHNOLOGY DEPARMENT

26

SHANTILAL SHAH ENGG. COLLEGE, BHAVNAGAR

AJT- 170703

PRACTICAL 5 (RMI)
10) Create a RMI simple RMI application.
HelloWorld.java
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface HelloWorld extends Remote
{ String helloWorld() throws RemoteException;
}
HelloWorldClient.java
import java.rmi.Naming;
import java.rmi.RemoteException;
pu-blic class HelloWorldClient
{
static String message = "blank";
static HelloWorld obj = null;
public static void main(String args[])
{
try {obj = (HelloWorld)Naming.lookup("//"+ "myssec.com"+ "/HelloWorld");
message = obj.helloWorld();
System.out.println("Message from the RMI-server was: \""
+ message + "\"");
}
catch (Exception e) { System.out.println("HelloWorldClient exception: "+
e.getMessage());
e.printStackTrace();
}
}
}
HelloWorldServer.java
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.RMISecurityManager;
import java.rmi.server.UnicastRemoteObject;
public class HelloWorldServer extends UnicastRemoteObject implements HelloWorld {
public HelloWorldServer() throws RemoteException
{
super();
}

INFORMATION TECHNOLOGY DEPARMENT

27

SHANTILAL SHAH ENGG. COLLEGE, BHAVNAGAR

AJT- 170703

public String helloWorld() {


System.out.println("Invocation to helloWorld was succesful!");
return "Hello World from RMI server!";
}
public static void main(String args[]) {
try {
// Create an object of the HelloWorldServer class.
HelloWorldServer obj = new HelloWorldServer();
// Bind this object instance to the name "HelloServer". Naming.rebind("HelloWorld", obj);
System.out.println("HelloWorld bound in registry");
}
catch (Exception e) {
System.out.println("HelloWorldServer error: " + e.getMessage());
e.printStackTrace();
}
}
}

Output:

INFORMATION TECHNOLOGY DEPARMENT

28

SHANTILAL SHAH ENGG. COLLEGE, BHAVNAGAR

INFORMATION TECHNOLOGY DEPARMENT

AJT- 170703

29

SHANTILAL SHAH ENGG. COLLEGE, BHAVNAGAR

AJT- 170703

PRACTICAL 6 (SERVLET)
11)Write a servlet that print Hello World using HTTP and Generic
Servlet.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloWorld extends HttpServlet {
private String message;
public void init() throws ServletException
{
message = "Hello World";
}
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
// Set response content type
response.setContentType("text/html");
// Actual logic goes here.
PrintWriter out = response.getWriter();
out.println("<h1>" + message + "</h1>");
}
public void destroy()
{
}
}

Output:

INFORMATION TECHNOLOGY DEPARMENT

30

SHANTILAL SHAH ENGG. COLLEGE, BHAVNAGAR

AJT- 170703

12) Write a Servlet program for session tracking using cookies.


import java.io.*;
import java.util.Random;
import javax.servlet.http.*;
import javax.servlet.ServletException;
public class CookieServlet extends HttpServlet
{
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
Cookie[] coki = request.getCookies();
Cookie tokenCookie = null;
if(coki !=null)
{
for(int i=0; i<coki.length; i++)
{
if (coki[i].getName().equals("token"))
{
tokenCookie = coki[i];
break;
}
}
}
response.setContentType("text/html");
PrintWriter prnwriter = response.getWriter();
prnwriter.println("<html><head><title>Extracting the token
cookie</title></head><body");
prnwriter.println("style=\"font-family:arial;font-size:12pt\">");
String resetParam = request.getParameter("resetParam");
if(tokenCookie==null || (resetParam != null && resetParam.equals("yes")))
{
Random rnd = new Random();
long cookieid = rnd.nextLong();
prnwriter.println("<p>Welcome. A new token " + cookieid + "is now
established</p>");
tokenCookie = new Cookie("token", Long.toString(cookieid));
tokenCookie.setComment("A cookie named token to identity user");
tokenCookie.setMaxAge(-1);
tokenCookie.setPath("/HandleSession/CookieServlet");
response.addCookie(tokenCookie);
}
else
{
prnwriter.println("Welcome back.. Your token is " +
tokenCookie.getValue() + ".</p>");
}
INFORMATION TECHNOLOGY DEPARMENT

31

SHANTILAL SHAH ENGG. COLLEGE, BHAVNAGAR

AJT- 170703

String requestURLSame = request.getRequestURL().toString();


String requestURLNew = request.getRequestURL() + "?resetParam=yes";
prnwriter.println("<p>Click <a href=" + requestURLSame +" > here
</a>again to continue browsing with the " + " same identity.</p>");
prnwriter.println("<p>Otherwise, click <a href = " + requestURLNew + ">
here</a> to start browsing with a new identity. </p>");
prnwriter.println("</body></html>");
prnwriter.close();
}
}

Output:

13) Assume there is a student database in Oracle with the following fields:
Student enrollment Number, Student Name, Program, Address, School of
Study. Write a code for Servlet which will display all the fields of the
student database in the tabular manner.
Datapage.jsp

INFORMATION TECHNOLOGY DEPARMENT

32

SHANTILAL SHAH ENGG. COLLEGE, BHAVNAGAR

AJT- 170703

<%@page language="java" import="java.util.*" %>


<html>
<head>
<title>Data Page</title>
</head>
<body>
<table border="1" width="303">
<tr>
<td width="119"><b>ID</b></td>
<td width="168"><b>Message</b></td>
</tr>
<%Iterator itr;%>
<% List data= (List)request.getAttribute("data");
for (itr=data.iterator(); itr.hasNext(); )
{
%>
<tr>
<td width="119"><%=itr.next()%></td>
<td width="168"><%=itr.next()%></td>
</tr>
<%}%>
</table>
</body>
</html>
DataServelet.java
import java.io.*; importjava.util.*; importjava.sql.*; importjavax.servlet.*;
importjavax.servlet.http.*;
public class DataServlet extends HttpServlet{
privateServletConfigconfig;
//Setting JSP page
String page="DataPage.jsp";
public void init(ServletConfigconfig)
throwsServletException{
this.config=config;
}
INFORMATION TECHNOLOGY DEPARMENT

33

SHANTILAL SHAH ENGG. COLLEGE, BHAVNAGAR

public void doGet(HttpServletRequest request,


ServletException,IOException
{
PrintWriter out = response.getWriter();
//Establish connection to MySQL database

AJT- 170703

HttpServletResponse response) throws

String connectionURL = "jdbc:mysql://192.168.10.59/messagepaging";


Connection connection=null; ResultSetrs; response.setContentType("text/html"); List
dataList=new ArrayList();
try {
// Load the database driver
Class.forName("com.mysql.jdbc.Driver");
// Get a Connection to the database
connection = DriverManager.getConnection(connectionURL,"root", "root");
//Select the data from the database
String sql = "select * from message";
Statement s = connection.createStatement();
s.executeQuery (sql);
rs = s.getResultSet();
while (rs.next ()){
//Add records into data list
dataList.add(rs.getInt("id"));
dataList.add(rs.getString("message"));
}
rs.close ();
s.close ();
}catch(Exception e){ System.out.println("Exception is ;"+e);
}
request.setAttribute("data",dataList);

INFORMATION TECHNOLOGY DEPARMENT

34

SHANTILAL SHAH ENGG. COLLEGE, BHAVNAGAR

AJT- 170703

//Disptching request
RequestDispatcher dispatcher = request.getRequestDispatcher(page);
if (dispatcher != null){
dispatcher.forward(request, response);
}
}
}
web.xml
<servlet>
<servlet-name>DataServlet</servlet-name>
<servlet-class>DataServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>DataServlet</servlet-name>
<url-pattern>/DataServlet</url-pattern>
</servlet-mapping>

Output:

INFORMATION TECHNOLOGY DEPARMENT

35

SHANTILAL SHAH ENGG. COLLEGE, BHAVNAGAR

AJT- 170703

PRACTICAL 7 (JSP)
15) Write a JSP Program, which displays a web page containing two
web links one for showing details of your department and other for
FAQs on Practical in department. When one click on link
department it goes to a page which shows all the details of
department and time table for CE/IT students .Clicking on link for
FAQs on Practical in department, another JSP page consisting of
some FAQ related to different practical courses in IT/CE will
open.
Index.htm
<html>
<body>
Click on this below link :<br><a href=./faq.html>FAQs</a>
<br><a href=dept.html>Department Info</a>
</body>
</html>
Faq.html
<html>
<body>
<h6>Click on the dept link to get corresponding FAQs</h6>
<br><a href=ce.html>CE</a>
<br><a href=it.html>IT</a>
</body></html>
Ce.html
<html><body>
<h6>CE FAQs</h6>
<ul>
<li> Que 1 Ans : Ans1
<li>Que2 Ans : Ans2
<li>Que3 Ans : Ans3
</ul>
</body></html>
it.html
<html><body>
<h6>IT FAQs</h6>
<ul><li> Que 1 Ans : Ans1
<li>Que2 Ans : Ans2
<li>Que3 Ans : Ans3
</ul></body></html>
INFORMATION TECHNOLOGY DEPARMENT

36

SHANTILAL SHAH ENGG. COLLEGE, BHAVNAGAR

AJT- 170703

Dept.html
<html><body>
<h6>DEPT Information</h6>
Here information about department goes.
<br><br><h4>Timetable of CE</h4>
<table width=800>
<tr><td>MON</td><td>TUE</td><td>WED</td><td>THU</td><td>FRI</td><td
>SAT</td></tr>
<tr><td>sub</td><td>sub</td><td>sub</td><td>sub</td><td>sub</td><td>sub</td>
</tr>
<tr><td>sub</td><td>sub</td><td>sub</td><td>sub</td><td>sub</td><td>sub</td>
</tr>
<tr><td>sub</td><td>sub</td><td>sub</td><td>sub</td><td>sub</td><td>sub</td>
</tr>
<tr><td>sub</td><td>sub</td><td>sub</td><td>sub</td><td>sub</td><td>sub</td>
</tr>
<tr><td>sub</td><td>sub</td><td>sub</td><td>sub</td><td>sub</td><td>sub</td>
</tr>
<tr><td>sub</td><td>sub</td><td>sub</td><td>sub</td><td>sub</td><td>sub</td>
</tr>
</table>
<br><br><h4>Timetable of IT</h4>
<table width=800>
<tr><td>MON</td><td>TUE</td><td>WED</td><td>THU</td><td>FRI</td><td
>SAT</td></tr>
<tr><td>sub</td><td>sub</td><td>sub</td><td>sub</td><td>sub</td><td>sub</td>
</tr>
<tr><td>sub</td><td>sub</td><td>sub</td><td>sub</td><td>sub</td><td>sub</td>
</tr>
<tr><td>sub</td><td>sub</td><td>sub</td><td>sub</td><td>sub</td><td>sub</td>
</tr>
<tr><td>sub</td><td>sub</td><td>sub</td><td>sub</td><td>sub</td><td>sub</td>
</tr>
<tr><td>sub</td><td>sub</td><td>sub</td><td>sub</td><td>sub</td><td>sub</td>
</tr>
<tr><td>sub</td><td>sub</td><td>sub</td><td>sub</td><td>sub</td><td>sub</td>
</tr>
</table>
</body>
</html>

INFORMATION TECHNOLOGY DEPARMENT

37

SHANTILAL SHAH ENGG. COLLEGE, BHAVNAGAR

AJT- 170703

Output:

16) Write a web based User registration application where Emplyee can

register online with their user Number. The registered employee


should be able to log on to the site after getting registered. You are
required to use JSP, Servlet and JDBC.
Index.html
<html>
<head>
<title>registration</title>
</head>
<body>
<form method="post" action="reg">
NAME:<input type="text"name="t1"/><br>
ENROLLMENT:<input type="text"name="t2"/><br>
PASSWORD:<input type="password"name="t3"/><br>
<input type="submit"value="send"/><br>
</form>
<a href='login.html'>if already registered plz login</a>
</body>
</html>
login.html
<html>
<head>
<title>login</title>
</head>
INFORMATION TECHNOLOGY DEPARMENT

38

SHANTILAL SHAH ENGG. COLLEGE, BHAVNAGAR

AJT- 170703

<body>
<form method="post" action="login">
<h2>ENTER VALID USER NAME AND PASSWORD</h2>
<p><strong>USER NAME:</strong>
<input type="text"name="t1"/><br>
<strong>PASSWORD:</strong>
<input type="password"name="t2"/><br>
<input type="submit"value="Login"/><br>
</p>
</form>
<a href='index.html'>new user create account</a>
</body>
</html>
web.xml
<web-app>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>regform</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/reg</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>s2</servlet-name>
<servlet-class>login</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
</web-app>
regform.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class regform extends HttpServlet{
public void doPost(HttpServletRequest req,HttpServletResponse res)throws
IOException,ServletException{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
String n=req.getParameter("t1");
String e=req.getParameter("t2");
String p=req.getParameter("t3");

INFORMATION TECHNOLOGY DEPARMENT

39

SHANTILAL SHAH ENGG. COLLEGE, BHAVNAGAR

AJT- 170703

try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("jdbc:odbc:school");
PreparedStatement st=con.prepareStatement("insert into student values(?,?,?)");
st.clearParameters();
st.setString(1,n);
st.setInt(2,Integer.parseInt(e));
st.setString(3,p);
st.executeUpdate();
con.close();
}
catch(Exception ex){
ex.printStackTrace(System.out);
}
out.write("ur account has been created, <a href='login.html'>u can login now</a>");
}
}
login.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class login extends HttpServlet{
public void doPost(HttpServletRequest req,HttpServletResponse res)throws
IOException,ServletException{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
String n=req.getParameter("t1");
String p=req.getParameter("t2");
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("jdbc:odbc:school");
PreparedStatement st=con.prepareStatement("select * from student where name=? and
pass=?");
st.clearParameters();
st.setString(1,n);
st.setString(2,p);
ResultSet rs=st.executeQuery();
boolean b=rs.next();
if(b==true){
out.write("WELCOME");
}
else{
out.write("Login failed <a href='login.html'>TRY AGAIN</a>");
}
con.close();
}catch(Exception ex){
INFORMATION TECHNOLOGY DEPARMENT

40

SHANTILAL SHAH ENGG. COLLEGE, BHAVNAGAR

AJT- 170703

ex.printStackTrace(System.out);
}
}
}

Output:

Figure: Showing New User Registration Form

Figure: Showing Login Page For Registered User

INFORMATION TECHNOLOGY DEPARMENT

41

SHANTILAL SHAH ENGG. COLLEGE, BHAVNAGAR

AJT- 170703

16)
Create a java Bean and JSP program that use
jsp:setProperty and getProperty action.
Index.html
<html>
<head>
<title>JSP Bean Property Demo</title>
</head>
<body>
<jsp:useBean id="customer" class="org.kodejava.example.bean.Customer"/>
<jsp:setProperty name="customer" property="id" value="1"/>
<jsp:setProperty name="customer" property="firstName" value="John"/>
<jsp:setProperty name="customer" property="lastName" value="Doe"/>
<jsp:setProperty name="customer" property="address" value="Sunset Road"/>
Customer Information: <%= customer.toString() %><br/>
Customer Name: <jsp:getProperty name="customer" property="firstName"/>
<jsp:getProperty name="customer" property="lastName"/>
</body>
</html>
Priority.java
package org.kodejava.example.bean;
public class Customer {
private int id;
private String firstName;
private String lastName;
private String address;
public Customer() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}

INFORMATION TECHNOLOGY DEPARMENT

42

SHANTILAL SHAH ENGG. COLLEGE, BHAVNAGAR

AJT- 170703

public void setFirstName(String firstName) {


this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "Customer{" +
"id=" + id +
", firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
", address='" + address + '\'' +
'}';
}

Output:

INFORMATION TECHNOLOGY DEPARMENT

43

SHANTILAL SHAH ENGG. COLLEGE, BHAVNAGAR

AJT- 170703

PRACTICAL 8 (HIBERNATE)
17) Develop a Java application using hibernate framework in Eclipse
or Netbeans.
1.AddEmployeeServlet.java
package com.kogent.hibernate;
import com.kogent.hibernate.Employee;
import com.kogent.hibernate.EmployeeData;
import java.io.IOException;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.RequestDispatcher;
public class AddEmployeeServlet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException
{
String employeeId = request.getParameter("employeeId");
String name = request.getParameter("name");
String age = request.getParameter("age");
String salary = request.getParameter("salary");
Employee emp = new Employee();
EmployeeData emplData = new EmployeeData();
try{
emp.setEmployeeId(Integer.parseInt(employeeId));
emp.setName(name);
emp.setAge(Integer.parseInt(age));
emp.setSalary(Double.parseDouble(salary));
emplData.addEmployee(emp);
ArrayList employees = EmployeeData.getEmployees();
HttpSession session = request.getSession(true);
session.setAttribute("employees", employees);
}
catch(Exception e) {
System.out.println("Exception caught in AddEmployeeServlet" + e);
}
RequestDispatcher rd=request.getRequestDispatcher("/EmployeeList.jsp");
rd.forward(request,response);
}
}
2.DeleteEmployeeServlet.java
INFORMATION TECHNOLOGY DEPARMENT

44

SHANTILAL SHAH ENGG. COLLEGE, BHAVNAGAR

AJT- 170703

package com.kogent.hibernate;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class DeleteEmployeeServlet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
String employeeId = request.getParameter("employeeId");
System.out.println("employee Iddddddd "+employeeId);
try{
EmployeeData.deleteEmployee(employeeId);
ArrayList employees = EmployeeData.getEmployees();
HttpSession session = request.getSession(true);
session.setAttribute("employees", employees);
}
catch(Exception e)
{System.out.println("Exception caught in AddEmployeeServlet" + e);
}
RequestDispatcher rd=request.getRequestDispatcher("/EmployeeList.jsp");
rd.forward(request,response);
}
}
3.EditEmployeeServlet.java
package com.kogent.hibernate;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class EditEmployeeServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

INFORMATION TECHNOLOGY DEPARMENT

45

SHANTILAL SHAH ENGG. COLLEGE, BHAVNAGAR

AJT- 170703

String employeeId = request.getParameter("employeeId");


String name = request.getParameter("name");
String age = request.getParameter("age");
String salary = request.getParameter("salary");
System.out.println("dsfdsf empid "+employeeId);
Employee emp = new Employee();
EmployeeData emplData = new EmployeeData();
try
{
emp.setEmployeeId(Integer.parseInt(employeeId));
emp.setName(name);
emp.setAge(Integer.parseInt(age));
emp.setSalary(Double.parseDouble(salary));
emplData.editEmployee(emp);
ArrayList employees = EmployeeData.getEmployees();
HttpSession session = request.getSession(true);
session.setAttribute("employees", employees);
}
catch(Exception e) {
System.out.println("Exception caught in EditEmployeeServlet " +
e);
}
RequestDispatcher rd=request.getRequestDispatcher("/EmployeeList.jsp");
rd.forward(request,response);
}
}
4.Employee.hbm.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD
3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.kogent.hibernate.Employee" table="EMPLOYEE"
schema="SCOTT">
<id name="employeeId" type="java.lang.Integer">
<column name="EMPLOYEE_ID" precision="5" scale="0" />
<generator class="assigned" />
</id>
<property name="name" type="java.lang.String">
<column name="NAME" length="20" />
</property>
<property name="age" type="java.lang.Integer">
<column name="AGE" precision="3" scale="0" />
</property>
<property name="salary" type="java.lang.Double">
<column name="SALARY" precision="7" scale="0" />
</property>
</class>
INFORMATION TECHNOLOGY DEPARMENT

46

SHANTILAL SHAH ENGG. COLLEGE, BHAVNAGAR

AJT- 170703

</hibernate-mapping>
5.Employee.java
package com.kogent.hibernate;
public class Employee {
int employeeId;
String name;
int age;
double salary;
public int getEmployeeId() {
return employeeId;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public double getSalary() {
return salary;
}
public void setEmployeeId(int employeeId) {
this.employeeId = employeeId;
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
public void setSalary(Double salary) {
this.salary = salary;
}
}

INFORMATION TECHNOLOGY DEPARMENT

47

SHANTILAL SHAH ENGG. COLLEGE, BHAVNAGAR

AJT- 170703

6.EmployeeData.java
package com.kogent.hibernate;
import java.util.ArrayList;
import java.util.Iterator;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.Query;
import org.hibernate.cfg.Configuration;
import com.kogent.hibernate.Employee;
public class EmployeeData
{
public static Employee getEmployee(String employeeId) throws Exception
{
Session session = null;
Employee employee=null;
try{
SessionFactory sessionFactory = new
Configuration().configure().buildSessionFactory();
session =sessionFactory.openSession();
Transaction tx = session.beginTransaction();
System.out.println("Getting Record");
employee = new Employee();
tx.commit();
System.out.println("Done");
Query query = session.createQuery("select employee1.employeeId,
employee1.name, employee1.age, employee1.salary from Employee
employee1 where employeeId = '"+employeeId +"'");
for(Iterator it=query.iterate();;)
{
Object[] row = (Object[]) it.next();
employee.setEmployeeId((int) new Integer(row[0].toString()));
employee.setName((String) row[1]);
employee.setAge((int) new Integer(row[2].toString()));
employee.setSalary((Double) row[3]);
}
}
catch(Exception e){
System.out.println(e.getMessage());
}
finally{
session.flush();
session.close();
}
return employee;
}
public static ArrayList getEmployees()
INFORMATION TECHNOLOGY DEPARMENT

48

SHANTILAL SHAH ENGG. COLLEGE, BHAVNAGAR

AJT- 170703

{
Session session = null;
Employee employee=null;
ArrayList<Employee> employees = new ArrayList<Employee>();
try
{
SessionFactory sessionFactory = new
Configuration().configure().buildSessionFactory();
session =sessionFactory.openSession();
System.out.println("Selecting Record");
System.out.println("Done");
System.out.println("Employee fffId
Name
Age
Salary");
Query query = session.createQuery("select employee1.employeeId,
employee1.name, employee1.age, employee1.salary from Employee
employee1");
for(Iterator it=query.iterate();it.hasNext();)
{
employee = new Employee();
Object[] row = (Object[]) it.next();
employee.setEmployeeId((int) new
Integer(row[0].toString()));
employee.setName((String) row[1]);
employee.setAge((int) new Integer(row[2].toString()));
employee.setSalary((Double) row[3]);
employees.add(employee);
}
}
catch(Exception e){
System.out.println(e.getMessage());
}
finally{
session.flush();
session.close();
}
return employees;
}
public void addEmployee(Employee emp) throws Exception
{
Employee employee = null;
Session session = null;
try
{
SessionFactory sessionFactory = new
Configuration().configure().buildSessionFactory();
session =sessionFactory.openSession();
Transaction tx = session.beginTransaction();
System.out.println("Selecting Record");
employee = new Employee();
INFORMATION TECHNOLOGY DEPARMENT

49

SHANTILAL SHAH ENGG. COLLEGE, BHAVNAGAR

AJT- 170703

System.out.println("sdfsdfsdfsd fdfd" +emp.getEmployeeId());


employee.setEmployeeId(emp.getEmployeeId());
employee.setName(emp.getName());
employee.setAge(emp.getAge());
employee.setSalary(emp.getSalary());
session.save(employee);
tx.commit();
System.out.println("Done");
System.out.println("Employee fffId Name Age Salary");
}
catch(Exception e)
{
System.out.println("Exception caught in EmployeeData.addEmployee"
+ e);
}
}
public static void deleteEmployee(String employeeId) throws Exception
{
Session session = null;
try{
SessionFactory sessionFactory = new
Configuration().configure().buildSessionFactory();
session =sessionFactory.openSession();
String hqlDelete ="delete Employee employee where employeeId='"
+ employeeId + "'";
Transaction tx = session.beginTransaction();
System.out.println("Deleting Record");
Query query = session.createQuery(hqlDelete);
int row = query.executeUpdate();
System.out.println("Number of rolw deleted " + row);
tx.commit();
System.out.println("Done");
}
catch(Exception e)
{
System.out.println("Exception caught in
EmployeeData.deleteEmployee" + e);
}
}
public void editEmployee(Employee emp) throws Exception
{
Session session = null;
try
{
SessionFactory sessionFactory = new
Configuration().configure().buildSessionFactory();
session =sessionFactory.openSession();
Transaction tx = session.beginTransaction();
System.out.println("Updating Record...");
INFORMATION TECHNOLOGY DEPARMENT

50

SHANTILAL SHAH ENGG. COLLEGE, BHAVNAGAR

AJT- 170703

String hqlUpdate = "update Employee employee set name =


:newName, age = :newAge, salary = :newSalary where employeeId
= :NewEmployeeId";
Query query = session.createQuery(hqlUpdate);
query.setInteger("NewEmployeeId", emp.getEmployeeId());
query.setString("newName", emp.getName());
query.setInteger("newAge", emp.getAge());
query.setDouble("newSalary", emp.getSalary());
int rowCount = query.executeUpdate();
System.out.println("Rows affected: " + rowCount);
tx.commit();
System.out.println("Done");
}
catch(Exception e)
{
System.out.println("Exception caught in EmployeeData.EditEmployee
" + e);
}
}
}
7.EmployeeListServlet.java
package com.kogent.hibernate;
import java.io.IOException;
import java.util.ArrayList;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.kogent.hibernate.EmployeeData;
public class EmployeeListServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
ArrayList employees = EmployeeData.getEmployees();
HttpSession session = request.getSession(true);
session.setAttribute("employees", employees);
ArrayList employees1=((ArrayList) session.getAttribute("employees"));
if(employees1!= null && employees1.size()>0)
{
for(int i=0;i<employees1.size();i++)
{
Employee emp= (Employee) employees1.get(i);
System.out.println(emp.getEmployeeId());
System.out.println(emp.getName());
System.out.println(emp.getAge());
INFORMATION TECHNOLOGY DEPARMENT

51

SHANTILAL SHAH ENGG. COLLEGE, BHAVNAGAR

AJT- 170703

System.out.println(emp.getSalary());
}
}
RequestDispatcher rd=request.getRequestDispatcher("/EmployeeList.jsp");
rd.forward(request,response);
}
}
8.TestHibernate.java
package com.kogent.hibernate;
import java.util.Iterator;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.Query;
import org.hibernate.cfg.Configuration;
import com.kogent.hibernate.Employee;
public class TestHibernate {
public static void main(String[] args) {
Session session = null;
try{
SessionFactory sessionFactory = new
Configuration().configure().buildSessionFactory();
session =sessionFactory.openSession();
Transaction tx = session.beginTransaction();
System.out.println("Inserting Record");
Employee employee = new Employee();
employee.setEmployeeId(2501);
employee.setName("Ambrish");
employee.setAge(new Integer(25));
employee.setSalary(new Double(9856));
session.save(employee);
tx.commit();
System.out.println("Done");
System.out.println("Employee Id Name Age Salary");
Query query = session.createQuery("select employee1.employeeId,
employee1.name, employee1.age, employee1.salary from Employee
employee1");
for(Iterator it=query.iterate();it.hasNext();){
Object[] row = (Object[]) it.next();
System.out.print(row[0]+"
");
System.out.print("
"+row[1]+ " ");
System.out.print("
"+row[2]);
System.out.print("
"+row[3]);
System.out.println();
}
}catch(Exception e){System.out.println(e.getMessage());}
finally{
INFORMATION TECHNOLOGY DEPARMENT

52

SHANTILAL SHAH ENGG. COLLEGE, BHAVNAGAR

AJT- 170703

session.flush();
session.close()
}
}
}
9.hibernate.cfg.xml
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="connection.username">scott</property>
<property name="connection.password">tiger</property>
<property name="connection.url">
jdbc:oracle:thin:@localhost:1521:XE
</property>
<property name="dialect">
org.hibernate.dialect.Oracle10gDialect
</property>
<property name="connection.driver_class">
oracle.jdbc.driver.OracleDriver
</property>
<mapping resource="com/kogent/hibernate/Employee.hbm.xml" />
</session-factory>
</hibernate-configuration>

10.web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<servlet>
<servlet-name>EmployeeList</servlet-name>
<servlet-class>com.kogent.hibernate.EmployeeList</servlet-class>
</servlet>
<servlet>
<servlet-name>EmployeeListServlet</servlet-name>
<servlet-class>com.kogent.hibernate.EmployeeListServlet</servlet-class>
</servlet>
INFORMATION TECHNOLOGY DEPARMENT

53

SHANTILAL SHAH ENGG. COLLEGE, BHAVNAGAR

AJT- 170703

<servlet>
<servlet-name>AddEmployeeServlet</servlet-name>
<servlet-class>com.kogent.hibernate.AddEmployeeServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>DeleteEmployeeServlet</servlet-name>
<servlet-class>com.kogent.hibernate.DeleteEmployeeServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>EditEmployeeServlet</servlet-name>
<servlet-class>com.kogent.hibernate.EditEmployeeServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>EmployeeListServlet</servlet-name>
<url-pattern>/EmployeeListServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>AddEmployeeServlet</servlet-name>
<url-pattern>/AddEmployeeServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>DeleteEmployeeServlet</servlet-name>
<url-pattern>/DeleteEmployeeServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>EditEmployeeServlet</servlet-name>
<url-pattern>/EditEmployeeServlet</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file></welcome-file>
</welcome-file-list>
</web-app>
11.AddEmployee.jsp
<%@ page language="java" %>
<html>
<head>
<title></title>
</head>
<body>
<form action="/HibernateApplication/AddEmployeeServlet">
<table width="500" border="0">
<tr>
<td>Employee Id</td>
<td><input type="text" name="employeeId"></td>
</tr>
<tr>
<td>Employee Name</td>
INFORMATION TECHNOLOGY DEPARMENT

54

SHANTILAL SHAH ENGG. COLLEGE, BHAVNAGAR

AJT- 170703

<td><input type="text" name="name"></td>


</tr>
<tr>
<td>Employee Age</td>
<td><input type="text" name="age"></td>
</tr>
<tr>
<td>Employee Salary</td>
<td><input type="text" name="salary"></td>
</tr>
<tr>
<td><input type="submit" name ="submit" value="submit"></td>
</tr>
</table>
</form>
</body>
</html>
12.EditEmployee.jsp
<%@ page language="java" %>
<%@ page import="com.kogent.hibernate.EmployeeData,
com.kogent.hibernate.Employee" %>
<html>
<head>
<title></title>
</head>
<body>
<%
String employeeId = request.getParameter("employeeId");
Employee emp = null;
emp= EmployeeData.getEmployee(employeeId);
%>
<form action="/HibernateApplication/EditEmployeeServlet">
<table width="500" border="0">
<tr>
<td>Employee Id</td>
<td><%=emp.getEmployeeId() %><input type = "hidden" name ="employeeId"
value=<%=emp.getEmployeeId() %>></td>
</tr>
<tr>
<td>Employee Name</td>
<td><input type="text" name="name" value=<%=emp.getName()%>></td>
</tr>
<tr>
<td>Employee Age</td>
<td><input type="text" name="age" value=<%=emp.getAge() %>></td>
</tr>
<tr>
INFORMATION TECHNOLOGY DEPARMENT

55

SHANTILAL SHAH ENGG. COLLEGE, BHAVNAGAR

AJT- 170703

<td>Employee Salary</td>
<td><input type="text" name="salary" value=<%=emp.getSalary() %>></td>
</tr>
<tr>
<td><input type="submit" name ="submit" value="submit"></td>
</tr>
</table>
</form>
</body>
</html>
13.EmployeeList.jsp
<%@ page import="java.util.ArrayList, com.kogent.hibernate.Employee" %>
<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %>
<html>
<head>
<title></title>
</head>
<body>
<table width="700" border="0" cellspacing="0" cellpadding="0">
<tr align="left">
<th>Employee Id</th>
<th>Name</th>
<th>Age</th>
<th>Salary</th>
</tr>
<!-- iterate over the results of the query -->
<% ArrayList employees=((ArrayList) session.getAttribute("employees"));
if(employees!= null && employees.size()>0)
{
for(int i=0;i<employees.size();i++)
{
Employee emp= (Employee) employees.get(i);
%>
<tr>
<td><%=emp.getEmployeeId() %></td>
<td><%=emp.getName() %></td>
<td><%=emp.getAge() %></td>
<td><%=emp.getSalary() %></td>
<td><A href ="/HibernateApplication/DeleteEmployeeServlet?
employeeId=<%=emp.getEmployeeId() %>"> Delete</A>
<td><A href ="/HibernateApplication/EditEmployee.jsp?
employeeId=<%=emp.getEmployeeId() %>"> Edit</A>
</tr>
<%
}
} %>
</table>
INFORMATION TECHNOLOGY DEPARMENT

56

SHANTILAL SHAH ENGG. COLLEGE, BHAVNAGAR

AJT- 170703

<A href ="/HibernateApplication/AddEmployee.jsp">Add New employee </A>


</body>
</html>

Output:

Fig: Showing The Employee List Page

Figure: Showing the add employee page.

INFORMATION TECHNOLOGY DEPARMENT

57

SHANTILAL SHAH ENGG. COLLEGE, BHAVNAGAR

AJT- 170703

PRACTICAL 9 (STRUT-MVC ARCHITECTURE)


19) Develop a Java application using

Struct framework (MVC

architecture) in Eclipse or Netbeans.


import java.sql.*;
import java.util.*;
publicclass GetEmployeeAddressUsingStruct {
publicstaticvoid main(String s[]) throws Exception {
Driver d= (Driver) ( Class.forName(
"oracle.jdbc.driver.OracleDriver").newInstance());
Properties p=new Properties();
p.put("user","scott");
p.put("password","tiger");
Connection
con=d.connect("jdbc:oracle:thin:@192.168.1.123:1521:XE",p);
Statement st=con.createStatement();
ResultSet rs=st.executeQuery(
"select permanent_address from personaldetails where empno="+s[0]);
if (rs.next()){
System.out.println("Employee Found: Address");
Struct struct=(Struct)rs.getObject(1);
Object addr[]=struct.getAttributes();
System.out.println("Flatno : "+addr[0]);
System.out.println("Street : "+ addr[1]);
System.out.println("Pin : "+addr[4]);
}//if
con.close();
}//main
}//class
Output:

INFORMATION TECHNOLOGY DEPARMENT

58

You might also like