You are on page 1of 50

5.7. Advanced Java Program..

Assignment 1. Write a Java program that connects to a database using JDBC


and does add, delete, modify and retrieve operations. Create Appropriate GUI
using awt for user interaction.

import java.sql.*;
/**
*
*
*/
public class NewJFrame extends javax.swing.JFrame {
Connection c;
PreparedStatement state;
ResultSet r;
int i=0;
DriverManager d;

/**
* Creates new form NewJFrame
*/
public NewJFrame() {
initComponents();
}

/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {

jScrollPane1 = new javax.swing.JScrollPane();


jTextArea1 = new javax.swing.JTextArea();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();

1
jButton4 = new javax.swing.JButton();
jTextField1 = new javax.swing.JTextField();
jTextField2 = new javax.swing.JTextField();

jTextArea1.setColumns(20);
jTextArea1.setRows(5);
jScrollPane1.setViewportView(jTextArea1);

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

jLabel1.setText("rno");

jLabel2.setText("sname");

jButton1.setText("add");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});

jButton2.setText("update");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});

jButton3.setText("delete");
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});

jButton4.setText("select");
jButton4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton4ActionPerformed(evt);
}
});

jTextField1.setText("jTextField1");

jTextField2.setText("jTextField2");

2
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING,
layout.createSequentialGroup()
.addGap(31, 31, 31)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TR
AILING)
.addComponent(jButton1)
.addComponent(jLabel2)
.addComponent(jLabel1)
.addComponent(jButton3))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED,
132, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LE
ADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING,
layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment
.LEADING)
.addComponent(jButton4)
.addComponent(jButton2))
.addGap(99, 99, 99))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING,
layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment
.LEADING)
.addComponent(jTextField2,
javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jTextField1,
javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(90, 90, 90))))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BA
SELINE)
.addComponent(jLabel1)

3
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(26, 26, 26)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BA
SELINE)
.addComponent(jLabel2)
.addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(61, 61, 61)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BA
SELINE)
.addComponent(jButton1)
.addComponent(jButton2))
.addGap(39, 39, 39)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BA
SELINE)
.addComponent(jButton3)
.addComponent(jButton4))
.addContainerGap(62, Short.MAX_VALUE))
);

pack();
}// </editor-fold>

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {


// TODO add your handling code here:
System.out.print("add");
try
{
System.out.println("Inserting");
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
c=DriverManager.getConnection("jdbc:odbc:dsn1","","");
int e1=Integer.parseInt(jTextField1.getText());
state=c.prepareStatement("insert into student values(?,?)");
state.setInt(1,e1);
state.setString(2,jTextField2.getText());
i=state.executeUpdate();
System.out.println(i);
c.commit();
}
catch(Exception e)
{ System.out.println(e);
}

4
}

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {


// TODO add your handling code here:
try
{
System.out.println("Updating");
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
c=DriverManager.getConnection("jdbc:odbc:dsn1","","");
int e1=Integer.parseInt(jTextField1.getText());
state=c.prepareStatement("update student set sname=? where rno=?");
state.setString(1,jTextField2.getText());
state.setInt(2,e1);
i=state.executeUpdate();
System.out.println(i);
c.commit();
}
catch(Exception e)
{ System.out.println(e);
}

private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {


// TODO add your handling code here:
try
{
System.out.println("Deleting");
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
c=DriverManager.getConnection("jdbc:odbc:dsn1","","");
int e1=Integer.parseInt(jTextField1.getText());
state=c.prepareStatement("delete from student where rno=?");
state.setInt(1,e1);
i=state.executeUpdate();
System.out.println(i);
c.commit();
}
catch(Exception e)
{ System.out.println(e);
}

private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {


// TODO add your handling code here:

5
try
{
System.out.println("Searching");
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
c=DriverManager.getConnection("jdbc:odbc:dsn1","","");
state=c.prepareStatement("select * from student where rno=?");
int e1=Integer.parseInt(jTextField1.getText());
state.setInt(1,e1);
r=state.executeQuery();
while(r.next())
{
jTextField2.setText(r.getString("sname"));
}
}
catch(Exception e)
{ System.out.println(e);
}

/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and
feel.
* For details see
http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info :
javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {

java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level
.SEVERE, null, ex);
} catch (InstantiationException ex) {

java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level
.SEVERE, null, ex);
6
} catch (IllegalAccessException ex) {

java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level
.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {

java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level
.SEVERE, null, ex);
}
//</editor-fold>

/* Create and display the form */


java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new NewJFrame().setVisible(true);
}
});
}

// Variables declaration - do not modify


private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JButton jButton4;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextArea jTextArea1;
private javax.swing.JTextField jTextField1;
private javax.swing.JTextField jTextField2;
// End of variables declaration
}

7
8
Assignment 2. Write a Java program(s) that demonstrates the use of
Collection Classes.
package collectionclass1;

import java.util.*

public class Collectionclass1

public static void main(String[] args)

System.out.println("****Arrays Collection Class****"); //1

int ar[]={10,20,30};

Arrays.sort(ar);

System.out.println("Array Element are:-"+Arrays.toString(ar));

int index=Arrays.binarySearch(ar,20);

System.out.println("Index Position of Element 20 is:-"+index);

int[] cp=Arrays.copyOf(ar,3);

System.out.println("Creating Arrays Copy"+Arrays.toString(cp));

System.out.println("****ArrayList collection class****"); //2

ArrayList a=new ArrayList();

a.add("IMCA");

a.add("MCA");

a.add("MBA");

a.add("BCA");

a.add("BBM");

a.add("BBA");

9
int n= a.size();

System.out.println("Size of Array:->"+n);

System.out.println("Element in Array:-");

Iterator it1=a.iterator();

while(it1.hasNext())

System.out.println(it1.next());

a.remove("MCA");

System.out.println("Remove Element MCA");

System.out.println("Element in Array:-");

Iterator it=a.iterator();

while(it.hasNext())

System.out.println(it.next());

System.out.println("Searching Contain IMCA:"+a.contains("IMCA"));

System.out.println( "Is ArrayList Empty:->"+a.isEmpty());

System.out.println("****HashMap collection class****"); //3

HashMap hm=new HashMap();

hm.put(100,"Amul");

hm.put(101,"Pihu");

hm.put(102,"Rahul");

10
int s=hm.size();

System.out.println("Size of Array:->"+s);

Set s1=hm.entrySet();

System.out.println("Elements in HashMap are:-");

Iterator i=s1.iterator();

while(i.hasNext())

Map.Entry m=(Map.Entry)i.next();

System.out.print(m.getKey());

System.out.println("-"+m.getValue());

boolean ck=hm.containsKey(101);

System.out.println("Present Contain Key 101:-"+ck);

boolean cv=hm.containsValue("Priya");

System.out.println("Present Contain Value Priya:-"+cv);

System.out.println("Is HashMap is empty:-"+hm.isEmpty());

hm.clear();

int sizehm=hm.size();

System.out.println("HashMap Size After Clearing Elements-:"+sizehm);

System.out.print("****Linked List Collection Class****\n"); //4

LinkedList l=new LinkedList();

l.addAll(a);

System.out.println("Size of Linked List:-"+l.size());

11
System.out.println("Linked List Elements:"+l);

System.out.println("Searching Contain IMRD:"+l.contains("IMRD"));

l.clear();

System.out.println("After Clearing Linked List Elements are:-"+l.size());

System.out.println("Is Linked List is empty:-"+l.isEmpty());

System.out.print("****Linked List HashSet Collection Class****\n");//5

LinkedHashSet lh=new LinkedHashSet();

lh.addAll(a);

System.out.println("Elements:"+lh);

System.out.println("Searching Contains MCA:"+ lh.contains("MCA"));

lh.clear();

System.out.println("Clearing LinkedList Hashset"+l.size());

System.out.println("****Stack Collection Class****"); //6

Stack st=new Stack();

st.push("A");

st.push("B");

st.push("C");

System.out.println("Stack Elements are:-");

Enumeration e=st.elements();

while(e.hasMoreElements())

System.out.println(e.nextElement());

12
System.out.println("Last Element of Array is:-"+st.peek());

System.out.println("Deleting Element :-"+st.pop());

int sizes=st.size();

System.out.println("After Deleting Size of Stack:-"+sizes);

st.clear();

System.out.println("Clearing the Stack:-"+st.size());

System.out.println("****Vector Collection Class****"); //7

Vector v=new Vector();

v.add("Raj");

v.add("Anand");

v.add("Rahul");

v.add("Hemant");

System.out.println("Element in Vector:-");

Iterator v1=v.iterator();

while(v1.hasNext())

System.out.println(v1.next());

v.remove("Rahul");

System.out.println("After Removing Element 'Rahul'");

System.out.println("Element in Vector:-");

Iterator v2=v.iterator();

13
while(v2.hasNext())

System.out.println(v2.next());

int sizev=v.size();

System.out.println("Size of Elements in Vector :-"+sizev);

System.out.println( "Is Vector Empty:->"+v.isEmpty());

v.clear();

int sizev1=v.size();

System.out.println("Vector Size After Clearing Elements:- "+sizev1);

System.out.println("****HashTable Collection Class");

Hashtable ht=new Hashtable();

ht.put(1,"Kajal");

ht.put(2,"Vaishnavi");

ht.put(3,"Ruchita");

ht.put(4,"Monisa");

Set sht=ht.entrySet();

System.out.println("Elements in HashTable are:-");

Iterator hti=sht.iterator();

while(hti.hasNext())

Map.Entry m=(Map.Entry)hti.next();

System.out.print(m.getKey());

System.out.println("-"+m.getValue());

14
}

ht.remove(3);

System.out.println("After Removing Element 'Ruchita'");

Iterator htj=sht.iterator();

while(htj.hasNext())

Map.Entry m=(Map.Entry)htj.next();

System.out.print(m.getKey());

System.out.println("-"+m.getValue());

boolean b1=ht.containsKey(4);

System.out.println("Present Contain Key 4:-"+b1);

boolean b2=ht.containsValue("priya");

System.out.println("Present Contain Value priya:-"+b2);

ht.clear();

int sizeht=ht.size();

System.out.println("HashTable Size After Clearing Elements-:"+sizeht);

System.out.println("****HashSet Collection Class****"); //9

HashSet hs=new HashSet();

hs.addAll(a);

System.out.println("Element in HashSet Are:-");

Iterator hs1=hs.iterator();

while(hs1.hasNext())

15
System.out.println(hs1.next());

hs.remove("BBA");

System.out.println("After Removing Element 'BBA'");

System.out.println("Element in HashSet:-");

Iterator hs2=hs.iterator();

while(hs2.hasNext())

System.out.println(hs2.next());

int sizehs=hs.size();

System.out.println("Size of Elements in HashSet :-"+sizehs);

System.out.println( "Is HashSet Empty:->"+hs.isEmpty());

hs.clear();

System.out.println("HashSet Size After Clearing Elements:- "+hs.size());

16
Output:-

17
18
19
Assignment 3. Implement the Java program(s) for server and client to
demonstrate networking in Java using Sockets. (Single server and single
client, Single server and multiple clients).

 Single server and single client

Server

package socket1;
import java.util.*;
import java.io.*;
import java.net.*;
public class serverside
{
public static void main(String s[]) throws Exception
{
String str="abc ",str1="xyz ";
ServerSocket ss=new ServerSocket(2553);
Socket s1=ss.accept();
DataInputStream dis=newDataInputStream(s1.getInputStream());
DataOutputStream dos=new DataOutputStream(s1.getOutputStream());
DataInputStream br=new DataInputStream(System.in);
while(!str.equals("stop"))
{
str=dis.readUTF();
System.out.println("client says "+str);
str1=br.readLine();
dos.writeUTF(str1);
dos.flush();
}
dis.close();
dos.close();
s1.close();
ss.close();
}
}

20
Client

package socket1;
import java.util.*;
import java.io.*;
import java.net.*;
public class clientside {
public static void main(String s[]) throws Exception
{
String str="hi ",str1="hey ";
Socket s1=new Socket("localhost",2553);
DataInputStream dis=new DataInputStream(s1.getInputStream());
DataOutputStream dos=new DataOutputStream(s1.getOutputStream());
DataInputStream br=new DataInputStream(System.in);
while(!str.equals("stop"))
{
str=br.readLine();
dos.writeUTF(str);
dos.flush();
str1=dis.readUTF();
System.out.println(str1);
}
dis.close();
dos.close();
s1.close();
}
}

21
Output:-

Client: Server:

22
 Single server and multiple clients

Server

package multisc;
import java.util.*;
import java.net.*;
import java.io.*;
public class server
{

public static void main(String s[]) throws Exception


{
Socket sa=null;
ServerSocket ss2=null;
System.out.println("server listening ");
try
{
ss2=new ServerSocket(4445);
}
catch(IOException e)
{
System.out.println("server error");
}
while(true)
{
try
{
sa=ss2.accept();
System.out.println("connetion established");
ServerThread st =new ServerThread(sa);
st.start();
}
catch (Exception e)
{
System.out.println("connetion error");
}
}
}
}

23
class ServerThread extends Thread
{
String line=null;
DataInputStream is =null;
PrintWriter od=null;
Socket s1=null;
public ServerThread(Socket s)
{
s1=s;
}
public void run()
{
try
{

is = new DataInputStream(s1.getInputStream());
od = new PrintWriter(s1.getOutputStream());

line=is.readLine();

while(!line.equals("QUIT"))
{
od.println(line);
od.flush();
System.out.println("response to client "+line);
line=is.readLine();

}
is.close();
od.close();
s1.close();

}
catch(IOException ie)
{
System.out.println("socket close error");
}
}
}

24
Client

package multisc;
import java.util.*;
import java.net.*;
import java.io.*;

public class client


{

public static void main(String s[]) throws Exception


{
Socket s1=null;
String line=null;
DataInputStream br=null;
DataInputStream is=null;
PrintWriter os=null;
try
{
s1=new Socket("localhost",4445);
br=new DataInputStream(System.in);
is=new DataInputStream(s1.getInputStream());
os=new PrintWriter(s1.getOutputStream());

}
catch (IOException e)
{
System.err.print("IO Exception");

}
System.out.println("Enter data to echo server (enter QUIT to end) :-> ");
String res=null;
try
{
line=br.readLine();
while (line.compareTo("QUIT")!=0)
{
os.println(line);
os.flush();
res=is.readLine();
System.out.println("server response :-> "+res);
line=br.readLine();
}
is.close();

25
os.close();
br.close();
s1.close();
System.out.println("close connection ");
}
catch (IOException e)
{
System.out.println("socket read error");
}
}
}

Output:-

Server.java

26
Client

Client 1:

Client 2:

Client 3:

27
Assignment 4. Write a Java program(s) that demonstrates the use of RMI
technology.

Adder.java

package rmi;

import java.rmi.Remote;

interface Adder extends Remote


{
public int add(int x,int y) throws Exception;
}

AdderRemote.java

package rmi;

import java.util.*;
import java.io.*;
import java.rmi.server.*;
import java.rmi.*;

public class AdderRemote extends UnicastRemoteObject implements Adder


{
AdderRemote() throws RemoteException
{
super();
}
public int add(int x,int y)
{
return x+y;
}
}
client.java

package rmi;

import java.util.*;
import java.io.*;
import java.rmi.registry.*;

28
import java.rmi.*;
public class client.java

{
public static void main(String z[])
{
try
{
Adder stub=(Adder)Naming.lookup("rmi://localhost:6000/ss");
int i=stub.add(120,10);
System.out.println("addition"+i);
}
catch(Exception e)
{
System.out.println("remi server error");
}
}
}

Server.java

package rmi;

import java.util.*;
import java.io.*;
import java.rmi.registry.*;
import java.rmi.*;
public class Server
{
public static void main(String z[]) throws Exception
{
Adder stub=new AdderRemote();
try
{
Registry reg=LocateRegistry.createRegistry(6000);
reg.rebind("ss",stub);
}
catch(Exception e)
{
System.out.println("remi server error");
}

29
Output:-

30
Assignment 5. Write a Java program that implements a multi-thread
application that has three threads. First thread generates random integer
every 1 second and if the value is even, second thread computes the square of
the number and prints. If the value is odd, the third thread will print the value
of cube of the number.

package javaapplication3;
import java.util.Random;
public class JavaApplication3 {
static int i;
static class ThreadDemo1 extends Thread
{
@Override
public void run()
{
try {

Random random = new Random();


int r=random.nextInt(10);
System.out.println(r);
i=r;

Thread.sleep(500);

} catch (Exception e) {
System.out.println("Thread interupted "+e);
}
}
}
static class ThreadDemo2 extends Thread
{
@Override
public void run()
{
try {

if(i%2==0)
System.out.println(i*i);
Thread.sleep(500);

} catch (Exception e) {

System.out.println("Thread Interupted "+e);


}
}
}

31
static class ThreadDemo3 extends Thread
{
@Override
public void run()
{
try {

if(i%2!=0)
System.out.println(i*i*i);
Thread.sleep(500);

} catch (Exception e) {
System.out.println("Thread interupted "+e);
}
}
}
public static void main(String[] args) {
ThreadDemo1 T1=new ThreadDemo1();
T1.start();
ThreadDemo2 T2=new ThreadDemo2();
T2.start();
ThreadDemo3 T3=new ThreadDemo3();
T3.start();
}
}

Output:

32
Assignment 6. Create a Simple Java Web Application Using Servlet, JSP and
JDBC.

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!</h1>

<form action="dbservlet11">

<input type="submit" value="Click to view Records"/>

</form>

</body>

</html>

Servlet

protected void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

try {

33
PrintWriter out=response.getWriter();

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

Connection c=DriverManager.getConnection("jdbc:odbc:dsn1","","");

Statement st=c.createStatement();

ResultSet rs=st.executeQuery("select *from student");

out.println("Record are as Folllows\n");

while(rs.next())

out.println(rs.getInt("rno")+" "+" "+rs.getString("sname"));

} catch (IOException | ClassNotFoundException | SQLException e) {

System.out.println("Exp= "+e);

Output:

Before

34
After

35
Assignment 7. Create a Java Web Application which show the login page
with Username, password and login And register button.On login button it
validate the user name and password entered by user with database
information stored in login info database table if it is correct then show
message login successful and open home page which will show all the record of
login info table into grid. If information is incorrect then show message
invalid credentials.
On Register Button show the register page, on this page show the username,
password, date of Birth field to save this information into login info database
table.
On register page show two button save and cancel.
On save button record should be saved to database table login info and login
page should beOpened. Cancel it will returns back to login page.

login.jsp

<%@page import="java.sql.*"%>

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

<!DOCTYPE html>

<html>

<head>

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

<title>JSP Page</title>

</head>

<body>

<form action="Home.jsp" method="POST">

<br><br><br><br>

<center>

<h1>Login User</h1>

User Name<input type="text" name="uname"><br><br>

Password <input type="password" name="pass"><br><br>

<input type="Submit" name="submit" value="Login">&nbsp;&nbsp; &nbsp;

<a href="Registration.jsp">

<input type="Button" value="Register"></a></center>

</form>

<%

try

String uName,pass,dob;

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

Connection co =

DriverManager.getConnection("jdbc:odbc:dsn3","","");

Statement st = co.createStatement();

uName = request.getParameter("uname");

pass = request.getParameter("pass");

37
dob = request.getParameter("dob");

st.executeUpdate("insert into student values('"+uName+"','"+pass+"','"+dob+"')");

catch (Exception e)

System.out.println("Error : "+e);

%>

</body>

</html>

Home.jsp

<%@page import="java.io.PrintWriter"%>

<%@page import="java.sql.*" %>

<%@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>

<%

String uName,pass,dob;

PrintWriter o = response.getWriter();

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

38
Connection co =

DriverManager.getConnection("jdbc:odbc:dsn3","","");

Statement st = co.createStatement();

try

uName = request.getParameter("uname");

pass = request.getParameter("pass");

ResultSet rs = st.executeQuery("Select * from student where username='"+uName+"' and


password='"+pass+"'");

if(rs.next())

%>

<center><h1>Login Success</h1>

<%

ResultSet rs1 = st.executeQuery("Select *from student");

%>

<table border='1' cellpadding='5'>

<%

while(rs1.next())

%>

<tr>

<td> <%= rs1.getString("username") %> </td>

<td> <%= rs1.getString("password") %> </td>

<td> <%= rs1.getDate("dob") %> </td>

39
</tr>

<%

%>

</table></center>

<%

else

%>

Plzz Enter Valid Username & Password

<%

catch (Exception e)

System.out.println("Error : "+e);

%>

</body>

</html>

40
Registration.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>

<form action="login.jsp" method="POST">

<br><br><br><br>

<center>

<h1>Register User</h1>

User name <input type="text" name="uname"><br><br>

Password <input type="text" name="pass" ><br><br>

41
DOB <input type="date" name="dob"><br><br>

<input type="Submit" name="submit"

value="Save">&nbsp;&nbsp; &nbsp;

<a href="login.jsp"><input type="Button"

value="Cancel"></a></center>

</form>

</body>

</html>

Output:

42
43
Assignment 8. Write a Java program(s) that demonstrates Java Bean.

Index.jsp

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


<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF8">
<title>JSP Page</title>
</head>
<body>
<h1> demonstrates Java Bean <h1>
<jsp:useBean id="student" class="mypackage.packg">
<jsp:setProperty name="student" property="rno" value="1" />
<jsp:setProperty name="student" property="sname" value="Monisa" />
</jsp:useBean>
Roll no <jsp:getProperty name="student" property="rno" /><br>
Student Name <jsp:getProperty name="student" property="sname"/>
</body>
</html>

44
Package .java

package mypackage;

public class packg


{
private int rno;
String sname;
public packg()
{

}
public void setrno(int r)
{
rno=r;
}
public int getrno()
{
return rno;
}
public void setsname(String sn)
{
sname=sn;
}
public String getsname()
{
return sname;
}
}

Output:-

45
Assignment 9. Write a Java program(s) that demonstrates EJB.

calbean.java

package sessionBean;

import javax.ejb.Stateless;

@Stateless

public class calbean implements calbeanLocal

@Override

46
public Integer addition(int a, int b)

return (a+b);

addijsp.jsp

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

<!DOCTYPE html>

<html>

<head>

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

<title>JSP Page</title>

</head>

<body>

<h1>Hello World!</h1>

<form action="calservelet">

First No<input type="text" name="t1"><br>

Second No<input type="text" name="t2"><br>

<input type="submit" name="add" value="add">

</form>

</body>

</html>

47
calservelet

package sessionBean;

import java.io.IOException;

import java.io.PrintWriter;

import javax.ejb.EJB;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

public class calservelet extends HttpServlet {

@EJB

private calbeanLocal calbean;

protected void processRequest(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

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

try (PrintWriter out = response.getWriter())

out.println("<!DOCTYPE html>");

out.println("<html>");

out.println("<head>");

out.println("<title>Servlet calservelet</title>");

out.println("</head>");

out.println("<body>");

48
int a=Integer.parseInt(request.getParameter("t1"));

int b=Integer.parseInt(request.getParameter("t2"));

out.println("<h1>Sum = " +calbean.addition(a, b)+ "</h1>");

out.println("</body>");

out.println("</html>");

calbeanLocal.java

package sessionBean;

import javax.ejb.Local;

@Local

public interface calbeanLocal

Integer addition(int a, int b);

Output:-

49
50

You might also like