0% found this document useful (0 votes)
252 views100 pages

Advance Java

This document provides an index of topics to be covered in the Advanced Java lab manual. It lists 5 sections including Core Java Programming, Database Programming using JDBC, Servlet Programming - I, Session tracking using servlet, and JSP Programming. Each section contains multiple programming tasks related to the topic. For example, the Core Java section includes tasks on string reversal, number to word conversion, exception handling, method overloading/overriding, and multithreading.

Uploaded by

Ninja Appu
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
252 views100 pages

Advance Java

This document provides an index of topics to be covered in the Advanced Java lab manual. It lists 5 sections including Core Java Programming, Database Programming using JDBC, Servlet Programming - I, Session tracking using servlet, and JSP Programming. Each section contains multiple programming tasks related to the topic. For example, the Core Java section includes tasks on string reversal, number to word conversion, exception handling, method overloading/overriding, and multithreading.

Uploaded by

Ninja Appu
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 100

Index

Sr. Title Page Page Date of


No. From To Start
1 Core JAVA Programming 4 19
1) Write a program to accept a String from the
user and print it in reverse.
2) Write a program that accepts a number from
the command line, and displays its digit in word
format. E.g. if the number is 231, it must display
two three one.
3) Write a program to catch multiple exceptions
such as: ArrayIndexOutOfBoundException,
NullPointerException.
4) Demonstrate Method Overloading and
Method Overriding with the help of program.
5) Demonstrate 3 Threads to implement
multithreading. One thread prints even
numbers, Second Thread print odd numbers
and third thread print prime numbers between
the ranges entered by user.
6) Write a program to implement multiple
inheritance.

2 Database Programming using 20 40


1) Write a java application using JDBC API to insert
student’s profile (Roll No, Name, Address, and
Email-ID) into table ‘Record’ in java DB (derby)
database.
2) Implement above program using Applet.
3) Write a java application using JDBC API to edit
(insert. update, delete) Student’s profile stored
in the database.
4) Write a java application using JDBC API to edit
(insert. update, delete) Student’s profile stored
in the database using PreparedStatement.
5) Write a java application using JDBC API to insert
5 records into student table using JDBC
transaction and batch processing.
6) Consider table Employee (id numeric,name
varchar(50),address (50),age numeric). Write a
JDBC application to fetch all records of
Employee and do following using resultset.
a) Increase age of all employees by 5.
b) Insert new record into table.
7) Write a java GUI Swing application to create
STUDENT database in java DB.

3 Servlet Programming –I 41 61
1) Create a new servlet called FirstServlet.java
which reads and displays the form parameters
param1, param2 and param3.
2) Create a Servlet to implement getParameter (),
getParameterValues(), getParameterNames()
methods.
3) Write a program, using servlet and JDBC which
takes students roll number and provides
student information, which includes the name
of the student, the address, email-id, program
of study, and year of admission. You have to use
a database to store student’s information.
4) Perform Servlet chaining using
RequestDispatcher and sendRedirect method.
I. Using Request Dispatcher.
II. Using Send Redirect.

4 Session tracking using servlet 62 81


1) A servlet that sets six cookies. Three have the
default expiration time (-1), meaning that they
should apply only until the user next restarts
the browser. The other three use setMaxAge to
stipulate that they should apply for the next
hour, regardless of whether the user restarts
the browser or reboots the computer to initiate
a new browsing session.
2) Write a servlet that tracks the number of times
a user has visited a site. Though no unique
identifier is to be stored as a cookie, the
number of visits made by the user will persist
over time. Start by checking for the presence of
any cookies, and then a specific cookie named
"count." If the cookie exists, read the value and
then display it to the user. Since the idea of a
counter is to increase on every visit, increment
the counter value and send it back to the user
as a cookie. As you reload the page, the cookie
is incremented, and state information persists
across connections.
3) Write a servlet to display session lifecycle
information using various methods of
HttpSession interface and Session Tracking API.
4) Write a servlet to display use of URL Rewriting
and hidden form field.

5 JSP Programming 82 98
1) Create an index.jsp page to implement various
attributes of Page Directive element by
displaying current date and time and error
message.
2) Create a JSP Page to implement the Include and
Scripting elements with an example.
3) Create a JSP to work with JDBC API and to
access Database of Pr#3 using Page Directive
and Scriptlet elements.
4) With the help of <jsp:useBean>,
<jsp:setProperty>, <jsp:getProperty> action
elements call JavaBean from a JSP page for
StudentInfo (e.g. id, Name, Address) application
.
5) Login Authentication using Bean and Servlet In
JSP:
I) Create a "login.jsp" to login the user.
II) Create a "loginbean.jsp" to set the
parameter using <jsp:useBean> and forward
to the Servlet.
III) Create a bean class "LoginBean.java" to
mapping the parameter from
“loginbean.jsp".
IV) Create a Servlet”login.java" to validate the
username and password from the database.
V) Create a "welcome.jsp" display a message
after successfully user login.
Practical – 1

Aim :- Core Java Programming.


1) Write a program to accept a String from the user and print it in reverse.
2) Write a program that accepts a number from the command line, and
displays its digit in word format. E.g. if the number is 231, it must
display two three one.
3) Write a program to catch multiple exceptions such as:
ArrayIndexOutOfBoundException, NullPointerException.
4) Demonstrate Method Overloading and Method Overriding with
the help of program.
5) Demonstrate 3 Threads to implement multithreading. One thread
prints even numbers, Second Thread print odd numbers and third
thread print prime numbers between the ranges entered by user.
6) Write a program to implement multiple inheritance.
1. Write a program to accept a String from the user and print it in reverse.

Program: -

package practical1;
import java.util.Scanner;
/**
*
* @author hp pc
*/
class StrRev
{
String str;
StrRev(String s)
{
str=s;
}
void srev()
{
StringBuffer s1= new StringBuffer(str);
s1.reverse();
System.out.println("Reversed String: "+s1);
}
}
public class Prac1_1 {

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Scanner in = new Scanner(System.in);
System.out.println("Enter a string to reverse it: ");
String s=in.nextLine();
StrRev obj = new StrRev(s);
obj.srev();
}
}

Output:
2. Write a program that accepts a number from the command line, and
displays its digit in word format. E.g. if the number is 231, it must
display two three one.
Program: -
import java.util.Scanner;
/**
*
* @author 14012011045
*/
class DigitToWord
{
int number;
String s1,w;
char arr[]=new char[10];

DigitToWord(int n)
{
number=n;
}

void compare(char c)
{
switch(c)
{
case '0':w="zero";break;
case '1':w="one";break;
case '2':w="two";break;
case '3':w="three";break;
case '4':w="four";break;
case '5':w="five";break;
case '6':w="six";break;
case '7':w="seven";break;
case '8':w="eight";break;
case '9':w="nine";break;
default:w="unknown";break;
}
}
void wrdconvert()
{
s1=String.valueOf(number);
arr=s1.toCharArray();
for(int i=0;i<arr.length;i++)
{
compare(arr[i]);
System.out.print(w+" ");

}
}
}
public class Prac1_2 {

public static void main(String[] args)


{
int n;
Scanner in =new Scanner(System.in);
System.out.println("Enter number to convert it into digit");
n=in.nextInt();
DigitToWord obj=new DigitToWord(n);
obj.wrdconvert();
}
}

Output:
3. Write a program to catch multiple exceptions such as:
ArrayIndexOutOfBoundException, NullPointerException.

Program: -

package practical1;
import java.util.Scanner;

/**
*
* @author 14012011045
*/
public class Prac1_3 {

public static void main(String[] args)


{
Scanner in=new Scanner(System.in);
int arr[] = new int[5];
int j,a;
arr[0]=1;
arr[1]=2;
arr[2]=4;
try
{
System.out.println("Enter index to print value of array:");
j=in.nextInt();
System.out.println(arr[j]);
String s= null;
s.lastIndexOf(0);
//System.out.println(s.length());
}
catch ( ArrayIndexOutOfBoundsException e1)
{
System.out.println("Error! Array Out of Bound Exeption");
}
ICT Advance Java Lab Manual

catch( NullPointerException e2 )
{
System.out.println("Error! Null pointer Exception");
}
}
}
Output:

17162151016 | NIRMAL PATEL


10
4. Demonstrate Method Overloading and Method Overriding with the
help of program.

a) Overloading

Program: -
package practical1;
import java.util.Scanner;
/**
*
* @author 14012011045
*/
class Shape
{
int ans;
void area(int x)
{
ans=x*x;
}
void area(int x,int y)
{
ans=x*y;
}
void display()
{
System.out.println("area:"+ans);
}
}
public class Prac1_4_a {

public static void main(String[] args)


{
Scanner in=new Scanner(System.in);
Shape obj=new Shape();
int x,y;
System.out.println("Enter side of square");
x=in.nextInt();
obj.area(x);
obj.display();
System.out.println("Enter sides of rectangle:");
x=in.nextInt();
y=in.nextInt();
obj.area(x, y);
obj.display();
}
}

Output:
b) Overriding

Program: -
package practical1;
/**
*
* @author 14012011045
*/
class A
{
String name="Rahul";
void display()
{
System.out.println("Hello "+name);
}
}
class B extends A
{
@Override
void display()
{
System.out.println("Hi"+name);
}
}
public class Prac1_4_b {

public static void main(String[] args)


{
B obj=new B();
obj.display();
}
}

OUTPUT:
5. Demonstrate 3 Threads to implement multithreading. One thread prints
even numbers, Second Thread print odd numbers and third thread print
prime numbers between the ranges entered by user.

Program: -

package practical1;
import java.util.*;

/**
*
* @author 1401201104
*/
class Even extends Thread
{
int start,end;
Even(int s,int e)
{
start=s;
end=e;
}

@Override
public void run()
{

for(int i=start;i<=end;i++)
{
if(i%2==0)
{
System.out.println("even:"+i);
}
}
}
}
class Odd extends Thread
{
int start,end;
Odd(int s,int e)
{
start=s;
end=e;
}

@Override
public void run()
{
for(int i=start;i<=end;i++)
{
if(i%2!=0)
{
System.out.println("odd:"+i);
}
}
}
}

class Prime extends Thread


{
int start,end;
Prime(int s,int e)
{
start=s;
end=e;
}

@Override
public void run()
{
for(int i=start;i<=end;i++)
{
int flag=0;
for (int j = 2; j <i; j++)
{
if(i%j==0)
{
flag=1;
break;

}
}
if(flag==0)
{
System.out.println("prime:"+i);
}
}
}
}
public class Prac1_5 {

public static void main(String[] args)


{
Scanner in=new Scanner(System.in);
System.out.println("Enter Starting and Ending point:");
int s=in.nextInt();
int e=in.nextInt();

Even ev=new Even(s, e);


ev.start();

Odd od =new Odd(s, e);


od.start();

Prime pr=new Prime(s, e);


pr.start();
}
}
OUTPUT:
6. Write a program to implement multiple inheritance.

Program: -

package practical1;
import java.util.Scanner;

/**
*
* @author 14012011045
*/
interface I
{
public void display();
}
class R
{
String name;
R(String s)
{
name=s;
}
}
class P extends R implements I
{

P(String s)
{
super(s);
}
@Override
public void display()
{
System.out.println("Hello "+name);
}
}
public class Prac1_6 {

public static void main(String[] args)


{
Scanner in=new Scanner(System.in);
System.out.println("Enter your name:");
String name=in.next();

P obj=new P(name);
obj.display();
}
}

Output:
Practical – 2

Aim :- Database Programming using JDBC API.


1) Write a java application using JDBC API to insert student’s profile
(Roll No, Name, Address, and Email-ID) into table ‘Record’ in java DB
(derby) database.
2) Implement above program using Applet.
3) Write a java application using JDBC API to edit (insert. update, delete)
Student’s profile stored in the database.
4) Write a java application using JDBC API to edit (insert. update, delete)
Student’s profile stored in the database using PreparedStatement.
5) Write a java application using JDBC API to insert 5 records
into student table using JDBC transaction and batch
processing.
6) Consider table Employee (id numeric,name varchar(50),address
(50),age numeric). Write a JDBC application to fetch all records
of Employee and do following using resultset.
c) Increase age of all employees by 5.
d) Insert new record into table.

7) Write a java GUI Swing application to create STUDENT database


in java DB.
1. Write a java application using JDBC API to insert student’s profile (Roll No,
Name, Address, and Email-ID) into table ‘Record’ in java DB (derby)
database.

Program: -

import java.util.*;
import java.sql.*;
public class database1 {
public static void main(String [] args)
{
try
{
Class.forName("org.apache.derby.jdbc.ClientDriver");
}
catch(ClassNotFoundException ex)
{
System.out.println(ex.getMessage());
}
String url="jdbc:derby://localhost:1527/Mayank";
String username="mayank";
String pwd="mayank0448";
try{
Connection cn=DriverManager.getConnection(url,username,pwd);
Statement st=cn.createStatement();
String query="insert into App.Student
values('13012021019','Rohit','IT','Ahmedabad','rohit.smemon@gmail.com')";
st.executeUpdate(query);
st.close();
cn.close();
System.out.println("Insertion completed");
}
catch(SQLException ex)
{
System.out.println(ex.getMessage());
}
}
}
Output:
2. Implement above program using
Applet. Program: -
import java.util.*;
import java.applet.*;
import java.awt.*;
import java.sql.*;
public class DatabaseApplet extends Applet {

TextField txt1,txt2,txt3,txt4,txt5;
Label l1,l2,l3,l4,l5;
Connection cn;
public void init()
{
txt1=new TextField(10);
txt2=new TextField(10);
txt3=new TextField(10);
txt4=new TextField(10);
txt5=new TextField(10);
l1=new Label();
l2=new Label();
l3=new Label();
l4=new Label();
l5=new Label();
add(l1);
add(txt1);
add(l2);
add(txt2);
add(l3);
add(txt3);
add(l4);
add(txt4);
add(l5);
add(txt5);
try{
Class.forName("org.apache.derby.jdbc.ClientDriver");
}
catch(ClassNotFoundException e)
{ System.out.println(e.getMessage()
);
}
String url="jdbc:derby://localhost:1527/Mayank";
String usname="mayank";
String pwd="mayank0448";
try{
cn=DriverManager.getConnection(url,usname,pwd);
}
catch(SQLException e)
{
System.out.println(e.getMessage());
}
}
public void paint(Graphics g)
{
l1.setText("Enrollment Number");
l2.setText("Name");
l3.setText("Branch");
l4.setText("Address");
l5.setText("E-mail");
if(txt1.getText()!=null && txt2.getText()!=null && txt3.getText()!=null &&
txt4.getText()!=null && txt5.getText()!=null)
{
String a=txt1.getText();
String b=txt2.getText();
String c=txt3.getText();
String d=txt4.getText();
String e=txt5.getText();

try{
String query="insert into App.Student values(?,?,?,?,?)";
PreparedStatement pst = cn.prepareStatement(query);
pst.setString(1,a);
pst.setString(2,b);
pst.setString(3,c);
pst.setString(4,d);
pst.setString(5,e);
pst.executeUpdate();
pst.close();
cn.close();
g.drawString("Data Inserted Successfully",50,50);
}
catch(SQLException ex)
{
System.out.println(ex.getMessage());
}
}
}
public boolean action(Event e,Object w)
{
repaint();
return false;
}
}

Output:
3. Write a java application using JDBC API to edit (insert. update,
delete) Student’s profile stored in the database.
Program: -
import java.util.*;
import java.sql.*;
public class database1 {
public static void main(String [] args)
{
try
{
Class.forName("org.apache.derby.jdbc.ClientDriver");
}
catch(ClassNotFoundException ex)
{
System.out.println(ex.getMessage());
}
String url="jdbc:derby://localhost:1527/Mayank";
String username="mayank";
String pwd="mayank0448";
try{
Connection cn=DriverManager.getConnection(url,username,pwd);
Statement st=cn.createStatement();
String query="insert into App.Student
values('13012021019','Rohit','IT','Ahmedabad','rohit.smemon@gmail.com')";
st.executeUpdate(query);
query="update App.Student set name='Rohit where rollno=3”;
st.executeUpdate(query);
query="delete from App.Student where rollno=3”;
st.executeUpdate(query);
st.close();
cn.close();
System.out.println("Insertion completed");
}
catch(SQLException ex)
{
System.out.println(ex.getMessage());
}
}
}
Output:
4. Write a java application using JDBC API to edit (insert. update,
delete) Student’s profile stored in the database using
PreparedStatement.
Program: -
import java.util.*;
import java.sql.*;
public class practical3 {
public static void main(String[] args) {
try
{
Class.forName("org.apache.derby.jdbc.ClientDriver");
}
catch(ClassNotFoundException ex)
{
System.out.append(ex.getMessage());
}
String url="jdbc:derby://localhost:1527/Mayank";
String username="mayank";
String pwd="mayank0448";
Scanner in=new Scanner(System.in);
int choice;
String rollno,name,address,email;
System.out.print("Enter 1 for Insert, 2 for delete, 3 for update,4 for view:");
choice=in.nextInt();
in.nextLine();
switch (choice)
{
case 1:
System.out.println("Enter Roll Number");
rollno=in.nextLine();

System.out.println("Enter Name");
name=in.nextLine();
System.out.println("Enter Address");
address=in.nextLine();
System.out.println("Enter Email Id");
email=in.nextLine();

try
{
Connection cn=DriverManager.getConnection(url,username,pwd);
String query="insert into App.Student values(?,?,?,?)";
PreparedStatement st=cn.prepareStatement(query);

st.setString(1, rollno);
st.setString(2, name);
st.setString(3,address);
st.setString(4,email);
st.executeUpdate();

st.close();
cn.close();
System.out.println("Insertion complete");

}
catch(SQLException ex)
{
System.out.println(ex.getMessage());
}
break;

case 2:
System.out.println("Enter the rollnumber:");
rollno=in.next();
try
{
Connection cn=DriverManager.getConnection(url,username,pwd);

String query="delete from App.Student where ROLLNO=?";


PreparedStatement st=cn.prepareStatement(query);
st.setString(1,rollno);
st.executeUpdate();
st.close();
cn.close();
System.out.println("Deletion complete");
}
catch(SQLException ex)
{
System.out.println(ex.getMessage());
}
break;
case 3:
System.out.println("Enter 1 if you want to update Address:");
System.out.println("Entrer 2 if you want to update Email Address");
int choice2;
choice2=in.nextInt();
switch(choice2)
{
case 1:
System.out.println("Enter rollno:");
rollno=in.next();
System.out.println("Enter new Address:");
address=in.next();
try
{
Connection cn=DriverManager.getConnection(url,username,pwd);

String query="update App.Student set ADDRESS=? where ROLLNO=?";


PreparedStatement st=cn.prepareStatement(query);
st.setString(1,address);
st.setString(2,rollno);

st.executeUpdate();
st.close();
cn.close();
System.out.println("Address Updated");
}
catch(SQLException ex)
{
System.out.println(ex.getMessage());
}
break;

case 2:
System.out.println("Enter rollno:");
rollno=in.next();
System.out.println("Enter new email address:");
email=in.next();
try
{
Connection cn=DriverManager.getConnection(url,username,pwd);

String query="update App.Student set EMAIL_ID=? where ROLLNO=?";


PreparedStatement st=cn.prepareStatement(query);
st.setString(1,email);
st.setString(2,rollno);
st.executeUpdate();
st.close();
cn.close();
System.out.println("Email address Updated");
}
catch(SQLException ex)
{
System.out.println(ex.getMessage());
}
break;
}
break;

case 4:
System.out.println("Enter the roll number:");
rollno=in.next();
try
{
Connection cn=DriverManager.getConnection(url,username,pwd);

String query="select * from App.Student where ROLLNO=?";


PreparedStatement st=cn.prepareStatement(query);
st.setString(1,rollno);
ResultSet rs=st.executeQuery();
while(rs.next())
{
System.out.println(rs.getString(1)+" "+rs.getString(2)+"
"+rs.getString(3)+""+rs.getString(4));

rs.close();
st.close();
cn.close();
System.out.println("Selection complete");
}
catch(SQLException ex)
{
System.out.println(ex.getMessage());
}
}
}
Output:
5. Write a java application using JDBC API to insert 5 records into
student table using JDBC transaction and batch processing.
Program: -
import java.util.*;
import java.sql.*;
public class TransactionBatch {
public static void main(String [] args)
{ String
name,branch,enroll,add,email;
Scanner in =new Scanner(System.in);
System.out.println("Enter the Name");
name=in.nextLine();
System.out.println("Enter the Branch");
branch=in.nextLine();
System.out.println("Enter the Enrollment Number");
enroll=in.nextLine();
System.out.println("Enter the Address");
add=in.nextLine();
System.out.println("Enter the Email id");
email=in.nextLine();

try
{
Class.forName("org.apache.derby.jdbc.ClientDriver");
}
catch(ClassNotFoundException ex)
{
System.out.println(ex.getMessage());
}
String url="jdbc:derby://localhost:1527/Mayank";
String username="mayank";
String pwd="mayank0448";
Connection cn=null;
Savepoint savepoint=null;
try{
cn=DriverManager.getConnection(url,username,pwd);
cn.setAutoCommit(false);
savepoint=cn.setSavepoint("Savepoint");
String query="insert into App.Student values(?,?,?,?,?)";
PreparedStatement pst=cn.prepareStatement(query);
pst.setString(1,enroll);
pst.setString(2,name);
pst.setString(3,branch);
pst.setString(4,add);
pst.setString(5,email);
pst.addBatch();
pst.executeBatch();
cn.commit();
pst.close();
cn.close();
System.out.println("Insertion completed");
}
catch(SQLException ex)
{
try{ if(cn!
=null)
{
cn.rollback(savepoint);
}
}
catch(SQLException e)
{
System.out.println(e.getMessage());
}

System.out.println(ex.getMessage());
}
}
}

Output:
6. Consider table Employee (id numeric,name varchar(50),address (50),age
numeric). Write a JDBC application to fetch all records of Employee and
do following using resultset.
a) Increase age of all employees by 5.
b) Insert new record into table.

Program: -

import java.util.*;
import java.sql.*;
public class resultset {
public static void main(String [] args){

try
{
Class.forName("org.apache.derby.jdbc.ClientDriver");
}
catch(ClassNotFoundException ex)
{
System.out.println(ex.getMessage());
}
String url="jdbc:derby://localhost:1527/Mayank";
String username="mayank";
String pwd="mayank0448";

try{
Connection cn=DriverManager.getConnection(url,username,pwd);

String query="select * from App.Student";


PreparedStatement
pst=cn.prepareStatement(query,ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_U
PDATABLE);
ResultSet rs=pst.executeQuery();
while(rs.next())
{
String str=rs.getString(1);
long a=Long.parseLong(str);
long a1=a+10;
String str2=String.valueOf(a1);
rs.updateString(1,str2);
rs.updateRow();
}

pst.close();
cn.close();
System.out.println("Insertion completed");
}
catch(SQLException ex)
{
System.out.println(ex.getMessage());
}
}
}

Output:
7. Write a java GUI Swing application to create STUDENT database in java
DB Program: -
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.*;
import java.sql.*;
class SwingCreateDatabase implements ActionListener {

public static JFrame jf;


public JPanel jp;
public JButton jb1,jb2;
public JLabel jl,jl1,jl2,jl3,jl4,jl5;
public JTextField jt1,jt2,jt3,jt4,jt5;
SwingCreateDatabase()
{
jf=new JFrame();
jp=new JPanel();
jb1=new JButton("Insert");
jb2=new JButton("Reset");
jl=new JLabel();
jl1=new JLabel();
jl2=new JLabel();
jl3=new JLabel();
jl4=new JLabel();
jl5=new JLabel();
jt1=new JTextField(20);
jt2=new JTextField(20);
jt3=new JTextField(20);
jt4=new JTextField(20);
jt5=new JTextField(20);
jl1.setText("Enrollment");
jl2.setText("Name");
jl3.setText("Branch");
jl4.setText("Address");
jl5.setText("Email");
jp.setLayout(new GridLayout(7,2));
jb1.addActionListener(this);
jb2.addActionListener(this);
jp.add(jl1);
jp.add(jt1);
jp.add(jl2);
jp.add(jt2);
jp.add(jl3);
jp.add(jt3);
jp.add(jl4);
jp.add(jt4);
jp.add(jl5);
jp.add(jt5);
jp.add(jb1);
jp.add(jb2);
jp.add(jl);

jf.add(jp);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.pack();
jf.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
Object o=e.getSource();
if(o.equals(jb1))
{
createdatabase();
}
else if(o.equals(jb2))
{
jt1.setText("");
jt2.setText("");
jt3.setText("");
jt4.setText("");
jt5.setText("");
jl.setText("");
}

public static void main(String [] args)


{
SwingCreateDatabase s=new SwingCreateDatabase();
jf.pack();
}
public void createdatabase()
{
String enroll=null,name=null,address=null,email=null,branch=null;
if(jt1.getText()!=null && jt2.getText()!=null && jt3.getText()!=null && jt4.getText()!=null
&& jt5.getText()!=null){
name=jt2.getText().toString();
enroll=jt1.getText().toString();
address=jt4.getText().toString();
branch=jt3.getText().toString();
email=jt5.getText().toString();

try
{
Class.forName("org.apache.derby.jdbc.ClientDriver");
}
catch(ClassNotFoundException ex)
{
System.out.println(ex.getMessage());
}
String url="jdbc:derby://localhost:1527/Mayank";
String username="mayank";
String pwd="mayank0448";
try{
Connection cn=DriverManager.getConnection(url,username,pwd);
String query="insert into App.Student values(?,?,?,?,?)";
PreparedStatement pst=cn.prepareStatement(query);
pst.setString(1,enroll);
pst.setString(2,name);
pst.setString(3,branch);
pst.setString(4,address);
pst.setString(5,email);
pst.executeUpdate();
pst.close();
cn.close();
jl.setText("Insertion completed");
}

catch(SQLException ex)
{
jl.setText("Error in Insertion");
System.out.println(ex.getMessage());
}
}
}
}

Output:
Practical – 3

Aim :- Servlet Programming - I.


1) Create a new servlet called FirstServlet.java which reads and displays
the form parameters param1, param2 and param3.
2) Create a Servlet to implement getParameter (),
getParameterValues(), getParameterNames() methods.
3) Write a program, using servlet and JDBC which takes students roll
number and provides student information, which includes the name
of the student, the address, email-id, program of study, and year of
admission. You have to use a database to store student’s information.
4) Perform Servlet chaining using RequestDispatcher and sendRedirect
method.
i. Using Request Dispatcher.
ii. Using Send Redirect.
1. Create a new servlet called FirstServlet.java which reads and displays the
form parameters param1, param2 and param3.

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

</head>
<body>
<br>
<br>
<form action="AJ402" method="post">

<input type="text" name="firstname"><br>


<input type="text" name="middlename"><br>
<input type="text" name="lastname"><br>
<input type="submit" name="submit">
</form>
</body>
</html>

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(name = "AJ402", urlPatterns = {"/AJ402"})


public class AJ402 extends HttpServlet {

protected void processRequest(HttpServletRequest request, HttpServletResponse


response)
throws ServletException, IOException
{ response.setContentType("text/html;charset=UTF-
8"); PrintWriter out = response.getWriter();
try {
String a=request.getParameter("firstname");
String b=request.getParameter("middlename");
String c=request.getParameter("lastname");

out.println("First name is "+a);


out.println("Middle name is "+b);
out.println("Last name is "+c);

catch(Exception ex)
{
ex.getMessage();
}
finally
{ out.close(
);
}
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}

@Override

protected void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

processRequest(request, response);

@Override

public String getServletInfo() {

return "Short description";

Output:
2. Create a Servlet to implement getParameter (), getParameterValues(),
getParameterNames() methods.

Program: -

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

</head>
<body>
<form action="AJ405" method="post">

<input type="checkbox" name="team" value="Chelsea">Chelsea</br>


<input type="checkbox" name="team" value="ManChesterUnited">Manchester
United</br>

<input type="checkbox" name="team" value="Barcelona">Barcelona</br>

<input type="text" name="firstname"></br>


<input type="text" name="lastname"></br>
<input type="submit" value="submit">

</form>
</body>
</html>

import java.util.*;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(name = "AJ405", urlPatterns = {"/AJ405"})


public class AJ405 extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse
response)

throws ServletException, IOException


{ response.setContentType("text/plain;charset=UTF-
8"); PrintWriter out = response.getWriter();
try {
String[] a=request.getParameterValues("team");
Enumeration en=request.getParameterNames();
while(en.hasMoreElements())
{
Object o=en.nextElement();
String p=(String)o;
String s=request.getParameter(p);
out.println("Parameter is :"+p);
out.println("Value is :"+s);

out.println(" <html><body><br> Using GetParameter Values<br></body></html>");

for(int i=0;i<a.length;i++)
{
out.println(a[i]);
}

} finally
{ out.close(
);
}
}

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}

@Override

public String getServletInfo() {


return "Short description";
}
}
Output:
3. Write a program, using servlet and JDBC which takes students roll number
and provides student information, which includes the name of the
student, the address, email-id, program of study, and year of admission.
You have to use a database to store student’s information.

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

</head>
<body>
<form action="AJ404" method="post">
<input type="text" name="rollno">
<input type="submit" value="submit">

</form>
</body>
</html>

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.*;
@WebServlet(name = "AJ404", urlPatterns = {"/AJ404"})
public class AJ404 extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException
{ response.setContentType("text/html;charset=UTF-
8"); PrintWriter out = response.getWriter();
try {
String rn=request.getParameter("rollno");
try
{

Class.forName("org.apache.derby.jdbc.ClientDriver");
}
catch(ClassNotFoundException ex)
{
ex.getMessage();

}
try
{
String url="jdbc:derby://localhost:1527/Student";
String username="mayank";
String pwd="mayank";
Connection cn=DriverManager.getConnection(url,username,pwd);

String query="select * from App.Student where ROLLNO=?";


PreparedStatement st=cn.prepareStatement(query);
st.setString(1,rn);
ResultSet rs=st.executeQuery();
while(rs.next())
{
out.println(rs.getString(1)+" <br> "+rs.getString(2)+" <br> "+rs.getString(3)+"
<br> "+rs.getString(4));
}
rs.close();
st.close();

cn.close();

}
catch(SQLException ex)

{
out.println(ex.getMessage());
}

} finally
{ out.close(
);
}
}

@Override

protected void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
processRequest(request, response);
}

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}

@Override

public String getServletInfo() {


return "Short description";
}
}

Output:
4. Perform Servlet chaining using RequestDispatcher and sendRedirect
method.

i) Using Request
Dispatcher Program: -
<!DOCTYPE html>
<html>
<head>

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

<form action="Validate" method="post">

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


<input type="text" name="pwd">
<input type="submit" value="Submit">

</form>
</body>
</html>

Validate.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(name = "Validate", urlPatterns = {"/Validate"})


public class Validate extends HttpServlet {

* @param request servlet request


protected void processRequest(HttpServletRequest request, HttpServletResponse
response)

throws ServletException, IOException


{ response.setContentType("text/html;charset=UTF-
8"); PrintWriter out = response.getWriter();
try {
String uname=request.getParameter("uname");
String pwd=request.getParameter("pwd");

if(pwd.equals("yadav")&& uname.equals("mayank"))
{
RequestDispatcher rd=request.getRequestDispatcher("Welcome");

rd.forward(request,response);
}

else
{

out.append("Sorry, Username or Password error");


RequestDispatcher rd=request.getRequestDispatcher("AJ406.html");
rd.include(request, response);
}
} finally
{ out.close(
);
}

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
processRequest(request, response);
}

@Override
public String getServletInfo() {

return "Short description";


}// </editor-fold>
}

Welcome.java

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(name = "Welcome", urlPatterns = {"/Welcome"})


public class Welcome extends HttpServlet {

protected void processRequest(HttpServletRequest request, HttpServletResponse


response)
throws ServletException, IOException
{ response.setContentType("text/html;charset=UTF-
8"); PrintWriter out = response.getWriter();
try {
out.println("Welcome"+ " <br>");
out.println(request.getParameter("uname"));
} finally
{ out.close(
);
}
}

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
processRequest(request, response);
}

@Override
public String getServletInfo() {
return "Short description";
}
}

Output:
ii) Using Send Redirect

Program: -
<html>
<head>
<title></title>

</head>
<body>
<form action="SearchServlet" method="post">
<input type="text" name="uname"/>
<input type="submit" value="Submit"/>

</form>
</body>
</html>

SearchServlet

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(name = "SearchServlet", urlPatterns = {"/SearchServlet"})
public class SearchServlet extends HttpServlet {

protected void processRequest(HttpServletRequest request, HttpServletResponse


response)
throws ServletException, IOException
{ response.setContentType("text/html;charset=UTF-
8"); PrintWriter out = response.getWriter();
try {

String uname=request.getParameter("uname");
String url="Servlet2?uname="+uname;
response.sendRedirect(url);
} finally
{ out.close(
);
}
}

@Override

protected void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
processRequest(request, response);
}

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}

@Override

public String getServletInfo() {


return "Short description";
}
}

Servlet2
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(name = "Servlet2", urlPatterns = {"/Servlet2"})
public class Servlet2 extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse
response)

throws ServletException, IOException


{ response.setContentType("text/html;charset=UTF-
8"); PrintWriter out = response.getWriter();
try {
String uname=request.getParameter("uname");
out.println("Your user name is:"+uname);
} finally
{ out.close(
);
}
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
@Override
public String getServletInfo() {
return "Short description";
}
}

Output:
Practical – 4

Aim :- Session Tracking Using Servlet.


1) A servlet that sets six cookies. Three have the default expiration time (-
1), meaning that they should apply only until the user next restarts the
browser. The other three use setMaxAge to stipulate that they should
apply for the next hour, regardless of whether the user restarts the
browser or reboots the computer to initiate a new browsing session.
2) Write a servlet that tracks the number of times a user has visited a site.
Though no unique identifier is to be stored as a cookie, the number of
visits made by the user will persist over time. Start by checking for the
presence of any cookies, and then a specific cookie named "count." If
the cookie exists, read the value and then display it to the user. Since the
idea of a counter is to increase on every visit, increment the counter
value and send it back to the user as a cookie. As you reload the page,
the cookie is incremented, and state information persists across
connections.
3) Write a servlet to display session lifecycle information using various
methods of HttpSession interface and Session Tracking API.
4) Write a servlet to display use of URL Rewriting and hidden form field.
1) A servlet that sets six cookies. Three have the default expiration time (-1),
meaning that they should apply only until the user next restarts the
browser. The other three use setMaxAge to stipulate that they should
apply for the next hour, regardless of whether the user restarts the
browser or reboots the computer to initiate a new browsing session.
Program: -

<html>

<body>

<form method="post" action="prac5_2_1_1">

<input type="submit" value="Click ME">

</form>

</body>

</html>

*prac5_2_1_1.java

import javax.servlet.http.*;

import javax.servlet.*;

import java.io.*;

public class prac5_1 extends HttpServlet {

protected void processRequest(HttpServletRequest request, HttpServletResponse


response)

throws ServletException, IOException

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

8"); PrintWriter out = response.getWriter();


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

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

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

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

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

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

Cookie ck1=new Cookie("name1",name1);

Cookie ck2=new Cookie("name2",name2);

Cookie ck3=new Cookie("name3",name3);

Cookie ck4=new Cookie("name4",name4);

Cookie ck5=new Cookie("name5",name5);

Cookie ck6=new Cookie("name6",name6);

ck1.setMaxAge(-1);

ck2.setMaxAge(-1);

ck3.setMaxAge(-1);

ck4.setMaxAge(0);

ck5.setMaxAge(1000);

ck6.setMaxAge(1000);

try {

/* TODO output your page here. You may use following sample code. */

response.addCookie(ck1);

response.addCookie(ck2);
response.addCookie(ck3);

response.addCookie(ck4);

response.addCookie(ck5);

response.addCookie(ck6);

response.sendRedirect("prac5_1_2");

} finally

{ out.close(

);

protected void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

processRequest(request, response);

protected void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

processRequest(request, response);

*pract5_1_2.java

import javax.servlet.http.*;

import javax.servlet.*;

import java.io.*;

public class prac5_1_2 extends HttpServlet {


protected void processRequest(HttpServletRequest request, HttpServletResponse
response)

throws ServletException, IOException

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

8"); PrintWriter out = response.getWriter();

Cookie[] c=request.getCookies();

try {

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

out.println(c[i].getValue());

} finally

{ out.close(

);

protected void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

processRequest(request, response);

protected void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

processRequest(request, response);

}
Output:
2) Write a servlet that tracks the number of times a user has visited a site.
Though no unique identifier is to be stored as a cookie, the number of
visits made by the user will persist over time. Start by checking for the
presence of any cookies, and then a specific cookie named "count." If the
cookie exists, read the value and then display it to the user. Since the
idea of a counter is to increase on every visit, increment the counter
value and send it back to the user as a cookie. As you reload the page, the
cookie is incremented, and state information persists across connections.
Program: -

<html>

<head>

<title></title>

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

</head>

<body>

<form method="post" action="prac5_2_1_1">

<input type="submit" value="Click ME">

</form>

</body>

</html>

*pract5_2_1_1.java

import javax.servlet.http.*;

import javax.servlet.*;

import java.io.*;

public class prac5_2_1_1 extends HttpServlet {

int count;
protected void processRequest(HttpServletRequest request, HttpServletResponse
response)

throws ServletException, IOException

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

8"); PrintWriter out = response.getWriter();

Cookie ck=new Cookie("xyz",String.valueOf(count));

try {

/* TODO output your page here. You may use following sample code. */

count++;

out.println("Site visited:"+count);

response.addCookie(ck);

response.sendRedirect("prac5_1_2");

} finally

{ out.close(

);

protected void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

processRequest(request, response);

protected void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

processRequest(request, response);
}

*pract5_1_2.java

import javax.servlet.http.*;

import javax.servlet.*;

import java.io.*;

public class prac5_1_2 extends HttpServlet {

protected void processRequest(HttpServletRequest request, HttpServletResponse


response)

throws ServletException, IOException

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

8"); PrintWriter out = response.getWriter();

Cookie[] c=request.getCookies();

try {

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

out.println(c[i].getValue());

} finally

{ out.close(

);

protected void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {


processRequest(request, response);

protected void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

processRequest(request, response);

Output:
3) Write a servlet to display session lifecycle information using
various methods of HttpSession interface and Session Tracking API.
Program: -

<html>

<head>

<title></title>

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

</head>

<body>

<form method="post" action="prac5_2_1_1">

<input type="submit" value="Click ME">

</form>

</body>

</html>

*pract5_3.java

import javax.servlet.http.*;

import javax.servlet.*;

import java.io.*;

public class prac5_3 extends HttpServlet {

protected void processRequest(HttpServletRequest request, HttpServletResponse


response)

throws ServletException, IOException

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

8");
String username=request.getParameter("username");

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

PrintWriter out = response.getWriter();

HttpSession s=request.getSession();

try {

s.setAttribute("username",username);

s.setAttribute("password",password);

response.sendRedirect("prac5_3_2");

} finally

{ out.close(

);

protected void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

processRequest(request, response);

protected void doPost(HttpServletRequest request, HttpServletResponse


response)

throws ServletException, IOException {

processRequest(request, response);

*pract5_3_2.java
import javax.servlet.http.*;

import javax.servlet.*;

import java.io.*;

public class prac5_3_2 extends HttpServlet {

protected void processRequest(HttpServletRequest request, HttpServletResponse


response)

throws ServletException, IOException

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

8");

PrintWriter out = response.getWriter();

HttpSession s=request.getSession();

try {

String username=(String)s.getAttribute("username");

String password=(String)s.getAttribute("password");

String Id=(String)s.getId();

long CreatedTime=(long)s.getCreationTime();

long RecentTime=(long)s.getLastAccessedTime();

s.removeAttribute("password");

s.invalidate();

out.println("Username:"+username);

out.println("Password:"+password);

out.println("ID:"+Id);

out.println("Created Time:"+CreatedTime);

out.println("Recent Time:"+RecentTime);
} finally {

out.close();

protected void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

processRequest(request, response);

protected void doPost(HttpServletRequest request, HttpServletResponse


response)

throws ServletException, IOException {

processRequest(request, response);

}
}

Output:
4) Write a servlet to display use of URL Rewriting and hidden form field.

Program: -

<html>

<body>

<form method="post" action="prac5_5">

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

<input type="submit" value="Click ME">

</form>

</body>

</html>

*pract5_5_1.java

import javax.servlet.http.*;

import javax.servlet.*;

import java.io.*;

public class prac5_5_1 extends HttpServlet {

protected void processRequest(HttpServletRequest request, HttpServletResponse


response)

throws ServletException, IOException

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

8"); PrintWriter out = response.getWriter();

try {
String n = request.getParameter(“name”);

out.println(“<form action=’prac5_5_2’ method=’post’>”);

out.println(“<input type=’hidden’ name=’name’ value=’”+n”’>”);

out.println(“<input type=’submit’ value=’GO’>”);

out.println(“</form>”);

} finally {

out.close();

protected void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

processRequest(request, response);

protected void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

processRequest(request, response);

*pract5_5_2.java

import javax.servlet.http.*;

import javax.servlet.*;

import java.io.*;

public class prac5_4_2 extends HttpServlet {


protected void processRequest(HttpServletRequest request, HttpServletResponse
response)

throws ServletException, IOException

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

8");

PrintWriter out = response.getWriter();

try {

out.println(request.getParameter(“name”))”;

} finally

{ out.close(

);

protected void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

processRequest(request, response);

protected void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

processRequest(request, response);

*pract5_5_1.java

import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;

public class prac5_5_1 extends HttpServlet {

protected void processRequest(HttpServletRequest request, HttpServletResponse


response)

throws ServletException, IOException

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

8"); PrintWriter out = response.getWriter();

try {

String n = request.getParameter(“name”);

out.println(“<a href=’prac5_5_2?name=”\’+n’\”>Click Me</a>”);

} finally {

out.close();

protected void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

processRequest(request, response);

protected void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

processRequest(request, response);

}
*pract5_5_2.java

import javax.servlet.http.*;

import javax.servlet.*;

import java.io.*;

public class prac5_4_2 extends HttpServlet {

protected void processRequest(HttpServletRequest request, HttpServletResponse


response)

throws ServletException, IOException

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

8");

PrintWriter out = response.getWriter();

try {

out.println(request.getParameter(“name”))”;

} finally

{ out.close(

);

protected void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

processRequest(request, response);

protected void doPost(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
processRequest(request, response);

Output:
Practical – 5

Aim :- JSP Programming.


1) Create an index.jsp page to implement various attributes of Page
Directive element by displaying current date and time and error
message.
2) Create a JSP Page to implement the Include and Scripting elements with
an example.
3) Create a JSP to work with JDBC API and to access Database of Pr#3 using
Page Directive and Scriptlet elements.
4) With the help of <jsp:useBean>, <jsp:setProperty>, <jsp:getProperty>
action elements call JavaBean from a JSP page for StudentInfo (e.g. id,
Name, Address) application .
5) Login Authentication using Bean and Servlet In JSP:
i) Create a "login.jsp" to login the user.
ii) Create a "loginbean.jsp" to set the parameter using <jsp:useBean>
and forward to the Servlet.
iii) Create a bean class "LoginBean.java" to mapping the parameter
from “loginbean.jsp".
iv) Create a Servlet”login.java" to validate the username and
password from the database.
v) Create a "welcome.jsp" display a message after successfully user
login.
1) Create an index.jsp page to implement various attributes of Page Directive
element by displaying current date and time and error message.
Program: -
*prac6.1.jsp

<html>

<head>

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

<title>JSP Page</title>

</head>

<body>

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

<%@page contentType="text/html"%>

<%@page session="true"%>

<%@page errorPage="sorry.jsp"%>

<%= 6/0%>

</body>

</html>

*sorry.jsp

<html>

<head>

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

<title>JSP Page</title>
</head>

<body>

<%@page isErrorPage="true"%>

<%="Sorry"%>

</body>

</html>

Output:
2) Create a JSP Page to implement the Include and Scripting elements
with an example.

Program: -
*prac6.2.jsp

<html>

<head>

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

<title>JSP Page</title>

</head>

<body>

<%="Header"%>

<%@include file="header.jsp"%>

<%= "Footer"%>

<%@include file="footer.jsp"%>

</body>

</html>

*header.jsp

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

<html>

<head>

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


<title>JSP Page</title>

</head>

<body>

<p>This is header

</p>

</body>

</html>

*footer.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>

<p>

This is footer

</p>

</body>

</html>
Output:
3) Create a JSP to work with JDBC API and to access Database of Pr#3
using Page Directive and Scriptlet elements.
Program: -
*prac6.3.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="prac6.3.jsp" >

<input type="text" name="roll">

<input type="submit" value="Search">

</form>

<%@page errorPage="sorry.jsp"%>

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

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

<%

Class.forName("org.apache.derby.jdbc.ClientDriver");
String roll=request.getParameter("roll");

String url="jdbc:derby://localhost:1527/Mayank";

String username="mayank";

String pwd="mayank0448";

out.println("roll"+roll);

Connection cn=DriverManager.getConnection(url,username,pwd);

String query="select *from App.Student where enrollmentnumber=?";

PreparedStatement pst=cn.prepareStatement(query);

pst.setString(1,roll);

ResultSet rs=pst.executeQuery();

while(rs.next())

out.println("roll"+roll);

out.println(rs.getString(1)+" "+rs.getString(2)+" "+rs.getString(3)+" "+rs.getString(4)+"


"+rs.getString(5));

rs.close();

pst.close();

cn.close();

%>

</body>
</html>

Output:-

4) With the help of <jsp:useBean>, <jsp:setProperty>, <jsp:getProperty>


action elements call JavaBean from a JSP page for StudentInfo (e.g.
id, Name, Address) application.
Program:-
*jb.java
package mypackage;
import java.io.Serializable;
public class jb implements Serializable {

private int id;


private String name;
public jb()
{
id=0;
name="xyz";
}
public int getId()
{
return id;
}
public void setId(int id)
{
this.id=id;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name=name;
}
}

*prac6.4.1.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="prac6.4.2.jsp">
<input type="text" name="id">
<input type="text" name="name">
<input type="submit" value="Click">
</form>
</body>
</html>

*prac6.4.2.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>
<jsp:useBean id="user" class="mypackage.jb">
</jsp:useBean>>
<jsp:setProperty property="*" name="user"/>
<jsp:getProperty name="user" property="id"/>
<jsp:getProperty name="user" property="name"/>
</body>
</html>

Output:

5) Login Authentication using Bean and Servlet In JSP:


i) Create a "login.jsp" to login the user.
ii) Create a "loginbean.jsp" to set the parameter using
<jsp:useBean> and forward to the Servlet.
iii) Create a bean class "LoginBean.java" to mapping the parameter
from “loginbean.jsp".
iv) Create a Servlet”login.java" to validate the username and
password from the database.
v) Create a "welcome.jsp" display a message after successfully user
login.

i) Create a "login.jsp" to login the


user. Program: -
<%@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">
<input type="text" name="id">
<input type="text" name="name">
<input type="submit" value="Click">
</form>

</body>
</html>

ii) Create a "loginbean.jsp" to set the parameter using


<jsp:useBean> and forward to the Servlet.
Program: -
<%@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>
<jsp:useBean id="user" class="mypackage.LoginBean">
</jsp:useBean>>
<jsp:setProperty property="*" name="user"/>
<jsp:getProperty name="user" property="id"/>
<jsp:getProperty name="user" property="name"/>
</body>
</html>

iii) Create a bean class "LoginBean.java" to mapping the


parameter from “loginbean.jsp".

Program: -

package mypackage;
public class LoginBean implements Serializable {

private int id;


private String name;
public LoginBean()
{
id=0;
name="xyz";
public int getId()
{
return id;
}
public void setId(int id)
{
this.id=id;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name=name;
}
}
iv) Create a Servlet”login.java" to validate the username and
password from the database.

Program: -

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(name = "login", urlPatterns = {"/login"})


public class login extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException
{ response.setContentType("text/html;charset=UTF-
8"); PrintWriter out = response.getWriter();
try {
String id=request.getParameter("id");
String name=request.getParameter("name");
if(id.equals("18") && name.equals("mayank"))
{
response.sendRedirect("welcome.jsp");
}
else
{
response.sendRedirect("login.jsp");
}
/* TODO output your page here. You may use following sample code. */
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet login</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet login at " + request.getContextPath() + "</h1>");
out.println("</body>");
out.println("</html>");
} finally
{ out.close(
);
}

}
v) Create a "welcome.jsp" display a message after successfully
user login.

Program: -

<%@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>
<%="Welcome"%>
</body>

</html>

Output:

You might also like