0% found this document useful (0 votes)
17 views26 pages

CS282 Lab Manual 2023-24 Updated

The document is a lab manual for the B.Tech. Advance Java Programming Lab at Integral University, detailing the vision, mission, program educational objectives, and specific outcomes for students. It includes a structured index of experiments covering topics such as Applets, AWT, Swing, and JDBC, along with objectives, requirements, and sample Java code for each experiment. The manual aims to equip students with practical skills in Java programming and software development.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views26 pages

CS282 Lab Manual 2023-24 Updated

The document is a lab manual for the B.Tech. Advance Java Programming Lab at Integral University, detailing the vision, mission, program educational objectives, and specific outcomes for students. It includes a structured index of experiments covering topics such as Applets, AWT, Swing, and JDBC, along with objectives, requirements, and sample Java code for each experiment. The manual aims to equip students with practical skills in Java programming and software development.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

Department ofComputerScience & Engineering

LAB MANUAL

B.Tech. (Computer Science and Engineering)

Subject Name: - Advance Java Programming Lab

Subject Code: - CS 282

INTEGRAL UNIVERSITYLUCKNOW
Dasauli, Kursi Road, PO Basha-226026

1
VISION
To produce highly skilled personnel who are empowered enough to transform the society by their
education, research and innovations.

MISSION
● To offer diverse academic programs at undergraduate, postgraduate, and doctorate levels that
are in line with the current trends in Computer Science and Engineering.

● To provide the state of the art infrastructure for teaching, learning and research.

● To facilitate collaborations with other universities, industry and research labs.

2
PROGRAM EDUCATIONAL OBJECTIVES (PEO’s)

To produce graduates who have strong foundation of knowledge and skills in the field
PEO1 of computer science and engineering.

PEO2 To produce graduates who are employable in industries/public sector/research


organizations or work as an entrepreneur.

PEO3 To produce graduates who can provide solutions to challenging problems in their
profession by applying computer engineering theory and practices.

PEO4 To produce graduates who can provide leadership and are effective in multidisciplinary
environment.

PROGRAM SPECIFIC OUTCOMES ( PSO’s)

PSO 1 Ability to understand the principles and working of computer systems. Students have a
sound knowledge about the hardware and software aspects of computer systems.

PSO 2 Ability to design and develop computer programs and understand the structure and
development methodologies of software systems.

PSO 3 Ability to design and develop computer programs and understand the structure and
development methodologies of software systems.

PSO 4 Ability to apply knowledge to provide innovative novel solutions to existing problem
and identify research gaps

3
INDEX
Experiment Objective Page No.
No.
1 Understanding Concept of Applet and Drawing Methods 5-6

2 Understanding Concept of AWT and Event Handling 7-8

3 Introduction to Java Swing 9

4 Understanding the Concept of JDBC 10-12

5 Understanding the concept of RMI 13-14

6 Understanding the concept of Socket Programming 15-16

7 Introduction to Java Servlet, HTTP request and response program 17-18

8 Introduction of Cookies in Servlet 19-22

9 Introduction to JSP 23

10 Introduction to Exception Handling and Action Elements in JSP. 24-26

4
Experiment # 1 Understanding Concept of Applet and Drawing Methods
• Applet is a Java program that can be embedded into a web page. It runs inside the web
browser and works at client side.
• Applets are used to make the web site more dynamic and entertaining.
• All applets are sub-classes of java.applet.Applet class.
• Applets are not stand-alone programs. Instead, they run within either a web browser or an
applet viewer.
• In general, execution of an applet does not begin at main() method.
• Output of an applet window is not performed by System.out.println(). Rather it is handled with
various AWT methods, such as drawString().
Advantages
• It works at client side so less response time.
• Secured
• It can be executed by browsers running under many platforms, including Linux, Windows, Mac
OS etc.
Disadvantages
• Plugin is required at client browser to execute applet.
Experiment #1: A Program to create an Applet demonstrating various drawing methods of Applet and
demonstrate event handling mechanism
Objective
• Learning the working of Java Applet Technologies in Java Programming Model.
• How to recognize different stages of Applet Life Cycle.
• Learning how to create an Applet by extending Applet class
• How to create customized events by implementing various interface methods.
After completing this experiment you will be able to:
• Ready to use Applet Creation Strategies in your Java Programming Development Environment.
• Ready to create multiple Applet to from various 2D and 3D figures by using dedicated Applet
methods.
• Ready to analyze different stages of Applet Life cycle.
Requirements: Tools / Apparatus: Unix/Linux Operating System, Bash Shell, OpenJDK and JRE installed
on Machines.
Solution :
/*JAVA CODE */
import java.applet.*; import
java.awt.*;
import java.awt.event.*;
public class EventApplet extends Applet implements
ActionListener{
Button b; TextField tf;
public void init(){ tf=new
TextField();
tf.setBounds(30,40,150,20);
b=new Button("Click");
b.setBounds(80,150,60,50); add(b);add(tf);
b.addActionListener(this); setLayout(null);}
public void actionPerformed(ActionEvent e){

5
tf.setText("Welcome"); } }
Exercises:
• Write a Program to demonstrate the events handling mechanism in Applet
Programming Development Environment.
• Write a Java Applet to demonstrate the use of various drawing methods and embed
it on web page.
For further reading student may refer to the following books
Herbert Schildt, “THE COMPLETE REFRENCE: JAVA”, TMTT (Available in Departmental and Central
Library at University campus)

6
Experiment # 2 Understanding Concept of AWT and Event Handling
• AWT stands for Abstract Window Toolkit.
• AWT is an API to develop GUI or window-based applications in java.
• AWT components are platform dependent so there look and feel changes according to OS.
• AWT components depend upon native code counterparts(called peers) to handle their
functionality(drawing and rendering). This extra 'baggage' makes them heavy weight
components.
• AWT doesn't support pluggable look and feel.
• AWT doesn't follows MVC(Model View Controller)
• The java.awt package provides classes for AWT api such as TextField, Label, TextArea,
CheckBox, Choice, List etc.
• But some features are missing like Radio Button.
Java AWT Methods
• public void add(Component c) inserts a component on this
component. • public void setSize(int width, int height)
sets the size (width and height) of the component. •
public void setLayout(LayoutManager m) defines the
layout manager for the component. • public void
setVisible(boolean status) changes the visibility of the
component, by default false.
Event Handling
Event is the change in the state of object or source.
For example, click on button, scroll page etc.
Event Handling is mechanism that control the events and decides what should happen if an event
occurs.
The java.awt.event package provides many event classes and Listener interfaces for event handling.

Event classes and Interfaces

Event Classes Description Listener Interface

ActionEvent generated when button is pressed, menu-item is selected ActionListener

generated when mouse is dragged, moved, clicked,


MouseEvent MouseListener
pressed or released

KeyEvent generated when input is received from keyboard KeyListener

ItemEvent generated when check-box or list item is clicked ItemListener

TextEvent generated when value of textarea or textfield is changed TextListener

ContainerEvent
generated when component is added or removed from
ContainerListener
container

WindowEvent
generated when window is activated, deactivated or
WindowListener
closed

7
Experiment #2: A Program to create an AWT frame and demonstrate event handling mechanism.
Requirements: Tools / Apparatus: Unix/Linux Operating System, Bash Shell, OpenJDK and JRE installed
on Machines.
Solution:
/*JAVA CODE */
import java.awt.*; import
java.awt.event.*; public class
ActionListenerExample { public static
void main(String[] args) {
Frame f=new Frame("Java Programming");
Label l=new Label();
l.setBounds(70, 70, 250, 20);

Button b=new Button("Click Here");


b.setBounds(100,100,80,30);

f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});

b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){

l.setText("Do it Yourself");
}

});
f.add(b);f.add(l);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
Exercises:
• Write a Program to demonstrate the events handling mechanism in AWT
Programming Development Environment.
• Write a Java AWT program to demonstrate the use of various components.
For further reading student may refer to the following books
Herbert Schildt, “THE COMPLETE REFRENCE: JAVA”, TMTT (Available in Departmental and Central
Library at University campus)

8
Experiment # 3 Introduction to Java Swing
• Java Swing is a part of Java Foundation Classes (JFC)
• Used to develop GUI or window-based applications in java.
• Java swing components are platform-independent.
• Swing components are lightweight.
• Swing supports pluggable look and feel.
• Swing provides more powerful components such as tables, lists, scrollpanes, colorchooser,
tabbedpane etc.
• Swing follows MVC.
• The javax.swing package provides classes for java swing API such as JButton, JTextField,
JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.
Experiment: A Program to create a JFrameForm using Swing and demonstrate various button event
handling mechanism.
Requirements: Tools / Apparatus: Unix/Linux Operating System, Bash Shell, OpenJDK and JRE installed
on Machines.
Solution:
/*JAVA CODE */
import javax.swing.*; public class
FirstSwingExample { public static void
main(String[] args) {
JFrame f=new JFrame();//creating instance of JFrame

JButton b=new JButton("click");//creating instance of JButton


b.setBounds(130,100,100, 40);//x axis, y axis, width, height

f.add(b);//adding button in JFrame

f.setSize(400,500);//400 width and 500 height


f.setLayout(null);//using no layout managers
f.setVisible(true);//making the frame visible
} }
Exercises:
• Write a Program to demonstrate the various components of Swing.
• Write a Java Swing program to switch from one form to another form.
For further reading student may refer to the following books
Herbert Schildt, “THE COMPLETE REFRENCE: JAVA”, TMTT (Available in Departmental and Central
Library at University campus)

9
Experiment # 4 Understanding the Concept of JDBC

The JDBC API is a Java API that can access any kind of tabular data, especially data stored in a Relational
Database.
JDBC helps you to write Java applications that manage these three programming activities:
1. Connect to a data source, like a database
2. Send queries and update statements to the database
3. Retrieve and process the results received from the database in answer to your query The
following simple code fragment gives a simple example of these three steps:
public void connectToDb(String username, String password) {
Connection con =
DriverManager.getConnection("jdbc:myDriver:myDatabase",
username, password);
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM Table1");
while (rs.next()) { int x = rs.getInt("a"); String
s = rs.getString("b");
float f = rs.getFloat("c");} }
This short code fragment instantiates a DriverManager object to connect to a database driver and
log into the database, instantiates a Statement object that carries your SQL language query to the
database; instantiates a ResultSet object that retrieves the results of your query, and executes a simple
while loop, which retrieves and displays those results. It's that simple.
JDBC includes four components:
1. The JDBC API — The JDBC™ API provides programmatic access to relational data from the
Java™ programming language. Using the JDBC API, applications can execute SQL statements,
retrieve results, and propagate changes back to an underlying data source. The JDBC API can
also interact with multiple data sources in a distributed, heterogeneous environment.
The JDBC API is part of the Java platform, which includes the Java™ Standard Edition (Java™
SE ) and the Java™ Enterprise Edition (Java™ EE). The JDBC 4.0 API is divided into two packages:
java.sql and javax.sql. Both packages are included in the Java SE and Java EE platforms.
2. JDBC Driver Manager — The JDBC DriverManager class defines objects which can connect Java
applications to a JDBC driver. DriverManager has traditionally been the backbone of the JDBC
architecture. It is quite small and simple.
The Standard Extension packages javax.naming and javax.sql let you use a DataSource object
registered with a Java Naming and Directory Interface™ (JNDI) naming service to establish a
connection with a data source. You can use either connecting mechanism, but using a
DataSource object is recommended whenever possible.
3. JDBC Test Suite — The JDBC driver test suite helps you to determine that JDBC drivers will run
your program. These tests are not comprehensive or exhaustive, but they do exercise many
of the important features in the JDBC API.
4. JDBC-ODBC Bridge — The Java Software bridge provides JDBC access via ODBC drivers. Note
that you need to load ODBC binary code onto each client machine that uses this driver. As a
result, the ODBC driver is most appropriate on a corporate network where client installations
are not a major problem, or for application server code written in Java in a three-tier
architecture. This Trail uses the first two of these these four JDBC components to connect to
a database and then build a java program that uses SQL commands to communicate with a
test Relational Database. The last two components are used in specialized environments to
test web applications, or to communicate with ODBC-aware DBMSs.

Experiment: A Program to test Java Databse Connectivity Test and then to add record in the database
Requirements: Tools / Apparatus: Unix/Linux Operating System, Bash Shell, OpenJDK and JRE installed
on Machines

10
Solution
/*JAVA CODE */

//STEP 1. Import required packages import


java.sql.*;
public class FirstExample
{
// JDBC driver name and database URL static final
String JDBC_DRIVER = "com.mysql.jdbc.Driver"; static
final String DB_URL = "jdbc:mysql://localhost/EMP";

// Database credentials static final


String USER = "username"; static final
String PASS = "password";
public static void main(String[]
args) {
Connection conn = null;
Statement stmt = null; try{
//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");

//STEP 3: Open a connection


System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
//STEP 4: Execute a query
System.out.println("Creating statement...");
stmt = conn.createStatement(); String sql;
sql = "SELECT id, first, last, age FROM Employees";
ResultSet rs = stmt.executeQuery(sql);
//STEP 5: Extract data from result set
while(rs.next()){
//Retrieve by column name
int id = rs.getInt("id");
int age = rs.getInt("age");
String first = rs.getString("first");
String last = rs.getString("last");
//Display values
System.out.print("ID: " + id);
System.out.print(", Age: " + age);
System.out.print(", First: " + first);
System.out.println(", Last: " + last);}
//STEP 6: Clean-up environment
rs.close();
stmt.close();
conn.close();
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{ if(stmt!=null)
stmt.close(); }catch(SQLException se2){

11
}// nothing we can do try{
if(conn!=null) conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
}//end main
}//end FirstExample
Now let us compile above example as follows:
C:\>javac FirstExample.java
C:\>
When you run FirstExample, it produces following result:
C:\>java FirstExample
Connecting to database...
Creating statement...
ID: 100, Age: 18, First: Zara, Last: Ali
ID: 101, Age: 25, First: Mahnaz, Last: Fatma ID:
102, Age: 30, First: Zaid, Last: Khan
ID: 103, Age: 28, First: Sumit, Last: Mittal C:\>

Exercises:-
• Write a Program to check connectivity test from Oracle MySQL, MS-Access, IB2
Relational Database Management Systems.
• Write a Java program to create a table in a database then add and retrieve information
from it.
For Further Reading Student May Refer to the following Books
Herbert Schildt, “THE COMPLETE REFRENCE:JAVA”, TMTT (Available in Departmental and Central
Library at University campus)

12
Experiment # 5 Understanding the concept of RMI
Remote method invocation(RMI) allow a java object to invoke method on an object running on
another machine. RMI provide remote communication between java program. RMI is used for building
distributed application.
A RMI application can be divided into two part,Client program and Server program. A Server program
creates some remote object, make their references available for the client to invoke method on it. A
Client program make request for remote objects on server and invoke method on them. Stub and
Skeleton are two important object used for communication with remote object.
Stub act as a gateway for Client program. It resides on Client side and communicate with
Skeletonobject. It establish the connection between remote object and transmit request to it.
Creating a Simple RMI application involves following steps
Define a remote interface.
• Implementing remote interface.
• create and start remote application
• create and start client application
• Define a remote interface
A remote interface specifies the methods that can be invoked remotely by a client. Clients program
communicate to remote interfaces, not to classes implementing it. To be a remote interface, a
interface must extend the Remote interface of java.rmi package.
import java.rmi.*; public interface
AddServerInterface extends Remote
{
public int sum(int a,int b);
}
Implementation of remote interface
For implementation of remote interface, a class must either extend UnicastRemoteObject or use
exportObject() method of UnicastRemoteObject class.
import java.rmi.*; import
java.rmi.server.*;
public class Adder extends UnicastRemoteObject implements
AddServerInterface
{
Adder()throws RemoteException{
super(); }
public int sum(int a,int b)
{
return a+b;
}
}
Create AddServer and host rmi service
You need to create a server application and host rmi service Adder in it. This is done using
rebind()method of java.rmi.Naming class. rebind() method take two arguments, first represent the
name of the object reference and second argument is reference to instance of Adder import
java.rmi.*; import java.rmi.registry.*; public class AddServer{
public static void main(String args[]){
try{
AddServerInterface addService=new Adder();
Naming.rebind("AddService",addService);
//addService object is hosted with name AddService.

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

13
Create client application
Client application contains a java program that invokes the lookup()method of the Naming class. This
method accepts one argument, the rmi URL and returns a reference to an object of type
AddServerInterface. All remote method invocation is done on this object.
import java.rmi.*; public class Client{
public static void main(String
args[]){ try{
AddServerInterface
st=(AddServerInterface)Naming.lookup("rmi://"+args[0]+"/AddService")
;
System.out.println(st.sum(25,8));
}catch(Exception e){System.out.println(e);}
}
}
For Further Reading Student May Refer to the following Books
Herbert Schildt, “THE COMPLETE REFRENCE:JAVA”, TMTT (Available in Departmental and Central
Library at University campus)

14
Experiment # 6 Understanding the concept of Socket Programming
The java.net package of the J2SE APIs contains a collection of classes and interfaces that provide the
low-level communication details, allowing you to write programs that focus on solving the problem at
hand.
The java.net package provides support for the two common network protocols:
TCP: TCP stands for Transmission Control Protocol, which allows for reliable communication between
two applications. TCP is typically used over the Internet Protocol, which is referred to as TCP/IP. UDP:
UDP stands for User Datagram Protocol, a connection-less protocol that allows for packets of data to
be transmitted between applications.
Experiment: A Program to demonstrate the use of InetAddress, UserDatagramSocket,
UserDatagramPacket classes and interfaces
Solution
/*JAVA CODE */
// File Name GreetingServer.java import java.net.*;
import java.io.*; public class GreetingServer extends
Thread{ private ServerSocket serverSocket;
public GreetingServer(int port) throws IOException {
serverSocket = new ServerSocket(port);
serverSocket.setSoTimeout(10000); } public void
run() { while(true) { try
{
System.out.println("Waiting for client on port " +
serverSocket.getLocalPort() + "...");
Socket server = serverSocket.accept();
System.out.println("Just connected to "
+ server.getRemoteSocketAddress());
DataInputStream in = new
DataInputStream(server.getInputStream());
System.out.println(in.readUTF());
DataOutputStream out = new
DataOutputStream(server.getOutputStream());
out.writeUTF("Thank you for connecting to "+
server.getLocalSocketAddress() + \nGoodbye!");
server.close();
}catch(SocketTimeoutException s) {
System.out.println("Socket timed out!");
break;
}catch(IOException e) {
e.printStackTrace(); break;
} } } public static void
main(String [] args) { int port =
Integer.parseInt(args[0]); try {
Thread t = new GreetingServer(port);
t.start();
}catch(IOException e) {e.printStackTrace(); } }} Compile
client and server and then start server as follows:

$ java GreetingServer 6066 Waiting


for client on port 6066...
Check client program as follows:
$ java GreetingClient localhost 6066
Connecting to localhost on port 6066
Just connected to localhost/127.0.0.1:6066
Server says Thank you for connecting to /127.0.0.1:6066 Goodbye!

15
Exercises:-
• Write a Program to implement TCP in Java Programming Model
• Write a Java program to implement UDP in Java Programming Model.
For further reading student may refer to the following books
Herbert Schildt, “THE COMPLETE REFRENCE: JAVA”, TMTT (Available in Departmental and Central
Library at University campus)

16
Experiment # 7 Introduction to Java Servlet, HTTP request and response
program
Java Servlets are programs that run on a Web or Application server and act as a middle layer between
a requests coming from a Web browser or other HTTP client and databases or applications on the
HTTP server.
Using Servlets, you can collect input from users through web page forms, present records from a
database or another source, and create web pages dynamically.
Java Servlets often serve the same purpose as programs implemented using the Common Gateway
Interface (CGI). But Servlets offer several advantages in comparison with the CGI-
Performance is significantly better.
• Servlets execute within the address space of a Web server. It is not necessary to create a
separate process to handle each client request.
• Servlets are platform-independent because they are written in Java.
• Java security manager on the server enforces a set of restrictions to protect the resources on
a server machine. So servlets are trusted.
• The full functionality of the Java class libraries is available to a servlet. It can communicate
with applets, databases, or other software via the sockets and RMI mechanisms that you have
seen already.
Servlet Life cycle: A servlet life cycle can be defined as the entire process from its creation till the
destruction. The following are the paths followed by a servlet.
1. The servlet is initialized by calling the init() method.
2. The servlet calls service() method to process a client's request.
3. The servlet is terminated by calling the destroy() method.
Experiment
// Import required java libraries
import java.io.*; import
javax.servlet.*; import
javax.servlet.http.*;

// Extend HttpServlet class public class


HelloWorld extends HttpServlet {

private String message;


public void init() throws ServletException
{
// Do required initialization
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() {
// do nothing.
}
}

17
Servlet Deployment

<servlet>
<servlet-name>HelloWorld</servlet-name>
<servlet-class>HelloWorld</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>HelloWorld</servlet-name>
<url-pattern>/HelloWorld</url-pattern>
</servlet-mapping>
When a browser requests for a web page, it sends lot of information to the web server which cannot
be read directly because this information travel as a part of header of HTTP request.
HTTP Header Request Example
Following is the example which uses getHeaderNames() method of HttpServletRequest to read the
HTTP header information. This method returns an Enumeration that contains the header information
associated with the current HTTP request.
// Import required java libraries
import java.io.*; import
javax.servlet.*; import
javax.servlet.http.*; import
java.util.*;

// Extend HttpServlet class public class


DisplayHeader extends HttpServlet {

// Method to handle GET method request.


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

// Set response content type


response.setContentType("text/html");

PrintWriter out = response.getWriter();


String title = "HTTP Header Request Example";
String docType =
"<!doctype html public \"-//w3c//dtd html 4.0 " +
"transitional//en\">\n";
out.println(docType
+
"<html>\n" +
"<head><title>" + title + "</title></head>\n"+
"<body bgcolor = \"#f0f0f0\">\n" +
"<h1 align = \"center\">" + title + "</h1>\n" +
"<table width = \"100%\" border = \"1\" align =
\"center\">\n" +
"<tr bgcolor = \"#949494\">\n" +
"<th>Header Name</th><th>Header Value(s)</th>\n"+
"</tr>\n"
);

Enumeration headerNames = request.getHeaderNames();

while(headerNames.hasMoreElements()) {

18
String paramName = (String)headerNames.nextElement();
out.print("<tr><td>" + paramName + "</td>\n");
String paramValue = request.getHeader(paramName);
out.println("<td> " + paramValue + "</td></tr>\n");
}
out.println("</table>\n</body></html>");
}

// Method to handle POST method request. public void


doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request,
response);
}
}
HTTP Header Response Example
You already have seen setContentType() method working in previous examples and following example
would also use same method, additionally we would use setIntHeader() method to set Refresh header.
// Import required java libraries
import java.io.*; import
javax.servlet.*; import
javax.servlet.http.*; import
java.util.*;

// Extend HttpServlet class public class


Refresh extends HttpServlet {

// Method to handle GET method request.


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

// Set refresh, autoload time as 5 seconds


response.setIntHeader("Refresh", 5);

// Set response content type


response.setContentType("text/html");

// Get current time


Calendar calendar = new GregorianCalendar();
String am_pm; int hour =
calendar.get(Calendar.HOUR); int minute =
calendar.get(Calendar.MINUTE); int second =
calendar.get(Calendar.SECOND);
if(calendar.get(Calendar.AM_PM) == 0)
am_pm = "AM"; else
am_pm = "PM";
String CT = hour+":"+ minute +":"+ second +" "+ am_pm;

PrintWriter out = response.getWriter();


String title = "Auto Refresh Header Setting";
String docType =
"<!doctype html public \"-//w3c//dtd html 4.0 " +
"transitional//en\">\n";
out.println(docType
+

19
"<html>\n" +
"<head><title>" + title + "</title></head>\n"+
"<body bgcolor = \"#f0f0f0\">\n" +
"<h1 align = \"center\">" + title + "</h1>\n" +
"<p>Current Time is: " + CT + "</p>\n"
);
}

// Method to handle POST method request. public void


doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { doGet(request,
response);
} }
Exercises:
• Write a Program to demonstrate java servlet.
• Write a Java program to Login form using servlet.
For further reading student may refer to the following books
Herbert Schildt, “THE COMPLETE REFRENCE: JAVA”, TMTT (Available in Departmental and Central
Library at University campus)

20
Experiment # 8 Introduction of Cookies in Servlet
A cookie is a small piece of information that is persisted between the multiple client requests. A cookie
has a name, a single value, and optional attributes such as a comment, path and domain qualifiers, a
maximum age, and a version number.
How Cookie works
By default, each request is considered as a new request. In cookies technique, we add cookie with
response from the servlet. So cookie is stored in the cache of the browser. After that if request is sent
by the user, cookie is added with request by default. Thus, we recognize the user as the old user.
index.html
<form action="servlet1" method="post">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form> FirstServlet.java
import java.io.*; import
javax.servlet.*; import
javax.servlet.http.*;
public class FirstServlet extends
HttpServlet {

public void doPost(HttpServletRequest request,


HttpServletResponse response){ try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();

String n=request.getParameter("userName");
out.print("Welcome "+n);

Cookie ck=new Cookie("uname",n);//creating cookie object


response.addCookie(ck);//adding cookie in the response

//creating submit button


out.print("<form action='servlet2'>");
out.print("<input type='submit' value='go'>");
out.print("</form>");

out.close();

}catch(Exception e){System.out.println(e);}
}
}
SecondServlet.java import
java.io.*; import
javax.servlet.*; import
javax.servlet.http.*;
public class SecondServlet
extends HttpServlet {

public void doPost(HttpServletRequest request,


HttpServletResponse response){ try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();

Cookie ck[]=request.getCookies();
out.print("Hello "+ck[0].getValue());

21
out.close();

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

}
web.xml
<web-app>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>FirstServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>

<servlet>
<servlet-name>s2</servlet-name>
<servlet-class>SecondServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>

</web-app>
Exercises:
• Write a Program to demonstrate types of cookies.
• Write a Java program to demonstrate the use of various cookies.
For further reading student may refer to the following books
Herbert Schildt, “THE COMPLETE REFRENCE: JAVA”, TMTT (Available in Departmental and Central
Library at University campus)

22
Experiment # 9 Introduction to JSP
JSP technology is used to create web application just like Servlet technology. It can be thought of as
an extension to servlet because it provides more functionality than servlet such as expression
language, jstl etc.
A JSP page consists of HTML tags and JSP tags. The jsp pages are easier to maintain than servlet
because we can separate designing and development. It provides some additional features such as
Expression Language, Custom Tag etc.
Advantage of JSP over Servlet
There are many advantages of JSP over servlet. They are as follows:
• Extension to Servlet
JSP technology is the extension to servlet technology. We can use all the features of servlet in
JSP. In addition to, we can use implicit objects, predefined tags, expression language and
Custom tags in JSP, that makes JSP development easy.
• Easy to maintain
JSP can be easily managed because we can easily separate our business logic with
presentation logic. In servlet technology, we mix our business logic with the presentation
logic.
• Fast Development: No need to recompile and redeploy
If JSP page is modified, we don't need to recompile and redeploy the project. The servlet code
needs to be updated and recompiled if we have to change the look and feel of the application.
Less code than Servlet
In JSP, we can use a lot of tags such as action tags, jstl, custom tags etc. that reduces the code.
Moreover, we can use EL, implicit objects etc.
Creating a simple JSP Page
To create the first jsp page, write some html code as given below, and save it by .jsp extension. We
have save this file as index.jsp. Put it in a folder and paste the folder in the web-apps directory in
apache tomcat to run the jsp page.
index.jsp
Let's see the simple example of JSP, here we are using the scriptlet
tag to put java code in the JSP page. We will learn scriptlet tag
later.
<html>
<body>
<% out.print(2*5); %>
</body>
</html>
For Further Reading Student May Refer to the following Books
Herbert Schildt, “THE COMPLETE REFRENCE:JAVA”, TMTT (Available in Departmental and Central
Library at University campus)

23
Experiment # 10 Introduction to Exception Handling and Action Elements
in JSP
The exception is normally an object that is thrown at runtime. Exception Handling is the process to
handle the runtime errors. There may occur exception any time in your web application. So handling
exceptions is a safer side for the web developer.
Example of exception handling in jsp by the elements of page directive
In this case, you must define and create a page to handle the exceptions, as in the error.jsp page. The
pages where may occur exception, define the errorPage attribute of page directive, as in the
process.jsp page.
There are 3 files:
• index.jsp for input values
• process.jsp for dividing the two numbers and displaying the result
• error.jsp for handling the exception
index.jsp
<form action="process.jsp">
No1:<input type="text" name="n1" /><br/><br/>
No1:<input type="text" name="n2" /><br/><br/>
<input type="submit" value="divide"/>
</form> process.jsp
<%@ page errorPage="error.jsp" %>
<%

String num1=request.getParameter("n1");
String num2=request.getParameter("n2");

int a=Integer.parseInt(num1); int


b=Integer.parseInt(num2); int
c=a/b;
out.print("division of numbers is: "+c);

%> error.jsp
<%@ page isErrorPage="true" %>

<h3>Sorry an exception occured!</h3>

Exception is: <%= exception %>

JSP Action Tags


There are many JSP action tags or elements. Each JSP action tag is used to perform some specific tasks.
The action tags are used to control the flow between pages and to use Java Bean. The Jsp action tags
are given below.
jsp:forward action tag
The jsp:forward action tag is used to forward the request to another resource it may be jsp, html or
another resource.
Syntax of jsp:forward action tag without parameter
1. <jsp:forward page="relativeURL | <%= expression %>" />
Syntax of jsp:forward action tag with parameter
• <jsp:forward page="relativeURL | <%= expression %>">
• <jsp:param name="parametername" value="parametervalue | <%=expression%>" /
>
• </jsp:forward>

24
Example of jsp:forward action tag without parameter
In this example, we are simply forwarding the request to the printdate.jsp file. index.jsp
<html>
<body>
<h2>this is index page</h2>

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


</body>
</html>
printdate.jsp
<html>
<body>
<% out.print("Today is:"+java.util.Calendar.getInstance().getT
ime()); %> </body>
</html>

Example of jsp:forward action tag with parameter


In this example, we are forwarding the request to the printdate.jsp file with parameter and
printdate.jsp file prints the parameter value with date and time. index.jsp
<html>
<body>
<h2>this is index page</h2>

<jsp:forward page="printdate.jsp" >


<jsp:param name="name" value="javatpoint.com" />
</jsp:forward>

</body> </html>
printdate.jsp
<html>
<body>

<% out.print("Today is:"+java.util.Calendar.getInstance().getT


ime()); %>
<%= request.getParameter("name") %>

</body>
</html>
Simple example of java bean class
//Employee.java

package mypack;
public class Employee implements java.io.Serializable{
private int id; private String name;

public Employee(){}

public void setId(int id){this.id=id;}

public int getId(){return id;}

public void setName(String name){this.name=name;}

25
public String getName(){return name;}

}
How to access the java bean class?
To access the java bean class, we should use getter and setter
methods.
package mypack;
public class Test{
public static void main(String args[]){

Employee e=new Employee();//object is created

e.setName("Arjun");//setting value to the object

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

}
}
For Further Reading Student May Refer to the following Books
Herbert Schildt, “THE COMPLETE REFRENCE:JAVA”, TMTT (Available in Departmental and Central
Library at University campus)

26

You might also like