You are on page 1of 372

INSTITUTE OF

DISTANCE & ONLINE LEARNING

MASTER OF COMPUTER APPLICATIONS

ADVANCED INTERNET
PROGRAMMING
(THEORY AND PRACTICAL)
MCA631/MCA636

Self Learning Material R101


MASTER OF COMPUTER
APPLICATIONS
ADVANCED INTERNET
PROGRAMMING
(THEORY AND PRACTICAL)

MCA631/MCA636

Kiran Gurbani
CHANDIGARH UNIVERSITY
Institute of Distance and Online Learning
Course Development Committee
Chairman
Prof. (Dr.) R.S. Bawa
Vice Chancellor, Chandigarh University, Punjab
Advisors
Prof. (Dr.) Bharat Bhushan, Director, IGNOU
Prof. (Dr.) Majulika Srivastava, Director, CIQA, IGNOU
Programme Coordinators & Editing Team
Master of Business Administration (MBA) Bachelor of Business Administration (BBA)
Co-ordinator - Prof. Pragya Sharma Co-ordinator - Dr. Rupali Arora
Master of Computer Applications (MCA) Bachelor of Computer Applications (BCA)
Co-ordinator - Dr. Deepti Rani Sindhu Co-ordinator - Dr. Raju Kumar
Master of Commerce (M.Com.) Bachelor of Commerce (B.Com.)
Co-ordinator - Dr. Shashi Singhal Co-ordinator - Dr. Minakshi Garg
Master of Arts (Psychology) Bachelor of Science (Travel & Tourism Management)
Co-ordinator - Ms. Nitya Mahajan Co-ordinator - Dr. Shikha Sharma
Master of Arts (English) Bachelor of Arts (General)
Co-ordinator - Dr. Ashita Chadha Co-ordinator - Ms. Neeraj Gohlan
Master of Arts (Mass Communication and Bachelor of Arts (Mass Communication and
Journalism) Journalism)
Co-ordinator - Dr. Chanchal Sachdeva Suri Co-ordinator - Dr. Kamaljit Kaur
Academic and Administrative Management
Prof. (Dr.) Pranveer Singh Satvat Prof. (Dr.) S.S. Sehgal
Pro VC (Academic) Registrar
Prof. (Dr.) H. Nagaraja Udupa Prof. (Dr.) Shiv Kumar Tripathi
Director – (IDOL) Executive Director – USB

© No part of this publication should be reproduced, stored in a retrieval system, or transmitted in any
form or by any means, electronic, mechanical, photocopying, recording and/or otherwise without the
prior written permission of the author and the publisher.

SLM SPECIALLY PREPARED FOR


CU IDOL STUDENTS

Printed and Published by:


Himalaya Publishing House Pvt. Ltd.,
E-mail: himpub@bharatmail.co.in, Website: www.himpub.com

For: CHANDIGARH UNIVERSITY


Institute of Distance and Online Learning

CU IDOL SELF LEARNING MATERIAL (SLM)


Advanced Internet Programming
(Theory and Practical)
Course Code: MCA631/ MCA636 Credits: 3

Course Objectives:
 To provide knowledge of JDBC, and user interface components.
 To develop skills related to event handling and Java Servlets.
 To inculcate skills related to AJAX.

Syllabus
Unit 1 - Java Data Base Connectivity: JDBC Configuration, Types of Drivers for
connection, CRUD operations, Sequence, Meta Data and Prepared Statement,
Callable statement and Transactions. (Database: Oracle, MySQL and PostgreSQL).
JDBC Configuration, Types of Drivers for connection,
CRUD operations, Sequence,

Unit 2 - User Interface Components: MVC Architecture, Layout Manager, Jcomponent


class, JButton, JLabel, JText, JTextArea, JCheckBox and JRadioButton, JList,
JComboBox, JMenu and JPopupMenu Class, JMenuItem and JCheckBoxMenuItem,
JRadioButtonMenuItem, JscrollBar, Dialogs (Message, confirmation, input),
JFileChooser, JcolorChooser,

Unit 3 - Event Handling: Event sources, Listeners, Mouse and Keyboard Event Handling,
Adapters, Swing component and Container class.

Unit 4 - Java Servlets 1: Server-Side Programming, Web Server, Java Server side
components, Servlet Architecture. Web Container, Servlet Life Cycle, Tomcat
Interface, Servlet interface,

Unit 5 - Java Servlets 2: Servicing client requests, GET and POST request methods.
Retrieving data from database to servlet, Servlet config and Servlet context, Session
Tracking.

CU IDOL SELF LEARNING MATERIAL (SLM)


Unit 6 - AJAX 1: AJAX architecture, AJAX request & response objects, AJAX
Technologies, XMLHttpRequest, AJAX with Database.

Unit 7 - AJAX 2: AJAX -PHP framework, Email Finder, Comment form using AJAX in
Java, Handling XML data using PHP and AJAX, AJAX JSON.

Unit 8 - JSP: JSP: Architecture of JSP, Elements of JSP, Scripting elements, Directives and
actions, JSP configuration, White space preservation, implicit objects,Filter, JSP in
XML and custom tag libraries.

Unit 9 - Java Hibernate: Architecture, Configuration, sessions, persistent class, mapping,


O/R mapping, annotation, query languages, criteria queries, Native SQL, caching and
interceptor.

Unit 10 - Java Struts 1: Environment setup, configuration, actions, interceptors, result types,
File uploads, database access,

Unit 11 - Java Struts 2: Java Struts 2: Sending mails, validation, localization, type
conversion, exception handling, annotation, tags and integrations.

Text Books:
1. Schildt,H.(2017).Java: The Complete Reference. Tenth Edition, New Delhi: McGraw-Hill
Education.
2. Gavin, K.,Bauer C. (2006).Java Persistence with Hibernate,New York: Manning publisher.
Reference Books:
1. Y. D. Liang (2015). Introduction to Java Programming, Delhi: Pearson Education.
2. Jaworski, J. (1999). JAVA 2 Platform Unleashed, New Delhi: Tech Media Publications.
3. JAVA API Documents.

CU IDOL SELF LEARNING MATERIAL (SLM)


Advanced Internet Programming Practical
Course Code: MCA636 Credits: 1

Course Objectives:
 To implement the concepts underlying principles of Advanced Java
 To develop and analyze JavaScript programs
 To develop and analyze AJAX programs

Syllabus
Unit 1 - Basics
1. Implementation of CRUD operations on JDBC Applications with Oracle-MySQL-
PostgreSQL.
2. Implementation of Java Swings with JDBC Applications with Oracle-MySQL-
PostgreSQL.
3. Create Servlet file which contains following functions:
 Connect
 Create Database
 Create Table
 Insert Records into respective table
 Update records of particular table of database
 Delete Records from table.
 Delete table and also database.
4. Create login form and perform state management using Cookies, HttpSession and URL
Rewriting.
5. Study and Implement MVC using Spring Framework
6. Create database of student subject-wise data and retrieve all data using JSP and generate
xml structure along with DTD and XML Schema definition
7. Create a table of the cookies associated with the suitable home page. If there are no
active cookies display as stating “No Cookies” otherwise display cookie name and value
in a tabular format
8. Create a Servlet that uses session tracking to keep per-client access counts. Also show
other generic- info about the session.
9. Make a program which creates a cookie on the server side using servlets & when server
returns a response to the user also send cookies to clients for later retrieve its data from
that client.

CU IDOL SELF LEARNING MATERIAL (SLM)


Unit 2- JavaScript/CSS
(a) Create a registration page using HTML and CSS with right corner of the page having
current date and time.
(b) Design specification for the webpage as follows:
(i) The text box background color will be displayed and shadowed when the cursor
inserts into the text field.
(ii) The text area background color will be displayed and shadowed when the cursor
places into textarea.
(iii) The submit button background color will be displayed and shadowed when the
cursor moves over the submit button.
(c) For the same page and write validation function for registration page and modify the on
Submit event handler in the form code to validate the following form fields:
(i) FirstName
1. Must be entered
2. Must be Character
(ii) Password
1. Password length should be between 6 to 20 characters.
(iii) Gender(Use radio button)
1. Must be selected
(iv) Mobile Number
1. Must be in format(XX-XXXXX-XXXXX)
(v) Email
1. Email address must contain at least an @ sign and a dot(.)
Unit 3 - Java Server Pages:

Experiment: I

(i) Create a bean that represents information needed to calculate an employee's salary. Has
String (employee name) and int (employee ID) properties. Create an application to
demonstrate byautomatically filling in bean properties from request parameters.
Experiment: II

(ii) Create an emp table in the database with fields name, id and designation.
(iii) Create a HTML file with fields name, id and designation. Make sure that the textfields have
the same name as name, id and designation.
(iv) Create a javabean with fields name, id and designation.
(v) On click of the submit button of the HTML, invoke a jsp page which will extract the values
that were given by the HTML page and it invokes a servlet.
(vi) The Servlet will make a connection to the database and store the value in the table.

CU IDOL SELF LEARNING MATERIAL (SLM)


(vii) Connection to the database should have been established using a separate java class.
(viii) You can enhance the program by including more features like deletion, updation and
selecting all records.
Unit 4 -AJAX

(A) Develop a web application to dynamically check for availability of an email-id for
registration. If email-id does not exist in the database, ‘Available!’, else ‘Not Available!’,
should be displayed next to the email textbox. If email-id pattern does not conform to an
email-id, display Invalid Email Id. Perform the check when the textbox loses focus. Consider
the following fields for the Profile table:
EMAIL, PASSWORD, NAME, DATEOFBIRTH, GENDER, CITY, PINCODE, MOBILE
Note*: Check should be performed irrespective of uppercase or lowercase data.

Text Books:
1. Schildt, H., 2017, “Java: The Complete Reference”. Tenth Edition, New Delhi: McGraw-
Hill Education.
2. Gavin, K., Bauer C., 2006, “Java Persistence with Hibernate”, New York: Manning
publisher.
Reference Books:
1. Y. D. Liang, 2015, “Introduction to Java Programming”, Delhi: Pearson Education.
2. Jaworski, J., 1999, “JAVA 2 Platform Unleashed”, New Delhi: Tech Media Publications.
3. JAVA API Documents.

CU IDOL SELF LEARNING MATERIAL (SLM)


CONTENTS
Unit 1: Java Data Base Connectivity 1 - 16

Unit 2: User Interface Components 17 - 58

Unit 3: Event Handling 59 - 75

Unit 4: Java Servlets - I 76 - 91

Unit 5: Java Servlets - II 92 - 113

Unit 6: AJAX - I 114 - 130

Unit 7: AJAX - II 131 - 141

Unit 8: Java Server Pages 142 - 171

Unit 9: Java Hibernate 172 - 210

Unit 10: Java Struts - I 211 - 242

Unit 11: Java Struts - II 243 - 285

Practical Unit 1: Basics 286 - 335

Practical Unit 2: JavaScript/CSS 336 - 342

Practical Unit 3: Java Server Pages 343 - 356

Practical Unit 4: AJAX 357 - 362

CU IDOL SELF LEARNING MATERIAL (SLM)


UNIT 1 JAVA DATA BASE CONNECTIVITY

Structure:
1.0 Learning Objectives

1.1 Introduction

1.2 What is JDBC?

1.3 JDBC has Four Components

1.4 Layers of the JDBC Architecture

1.5 JDBC Driver

1.6 Java Database Connectivity Steps

1.7 JDBC Statements

1.8 Types of ResultSet

1.9 CRUD operation with Examples

1.10 Practical Assignment

1.11 Summary

1.12 Key Words/Abbreviations

1.13 Learning Activity

1.14 Unit End Questions (MCQs and Descriptive)

1.15 References

CU IDOL SELF LEARNING MATERIAL (SLM)


2 Advanced Internet Programming

1.0 Learning Objectives


After studying this unit, you will be able to:

 Explain the JDBC configurations and types of drivers for connection


 Describe CRUD operations
 Define meta data and prepared statements
 Elaborate callable statement and transactions

1.1 Introduction
JDBC stands for Java Database Connectivity, which is a standard Java API for database-
independent connectivity between the Java programming language and a wide range of databases.

The JDBC library includes APIs for each of the tasks mentioned below that are commonly
associated with database usage.

 Making a connection to a database.


 Creating SQL or MySQL statements.
 Executing SQL or MySQL queries in the database.
 Viewing & Modifying the resulting records.

1.2 What is JDBC?


JDBC has been developed under the Java Community Process that allows multiple
implementations to exist and be used by the same application. JDBC provides methods for
querying and updating the data in Relational Database Management system such as SQL, Oracle
etc.

The Java application programming interface provides a mechanism for dynamically loading
the correct Java packages and drivers and registering them with the JDBC Driver Manager that
is used as a connection factory for creating JDBC connections which supports creating and
executing statements such as SQL INSERT, UPDATE and DELETE. Driver Manager is the
backbone of the jdbc architecture.

In short JDBC helps the programmers to write java applications that manage these three
programming activities:

CU IDOL SELF LEARNING MATERIAL (SLM)


Java Data Base Connectivity 3

1. It helps us to connect to a data source, like a database.


2. It helps us in sending queries and updating statements to the database and
3. Retrieving and processing the results received from the database in terms of answering to
your query.

1.3 JDBC has Four Components


1. The JDBC API.
2. The JDBC Driver Manager.
3. The JDBC Test Suite.
4. The JDBC-ODBC Bridge.

1. The JDBC API.


The JDBC application programming interface provides the facility for accessing the
relational database from the Java programming language. The API technology provides the
industrial standard for independently connecting Java programming language and a wide range of
databases. The user not only execute the SQL statements, retrieve results, and update the data but
can also access it anywhere within a network because of it’s “Write Once, Run Anywhere”
(WORA) capabilities.

Due to JDBC API technology, user can also access other tabular data sources like
spreadsheets or flat files even in the heterogeneous environment. JDBC application programming
interface is a part of the Java platform that has included Java Standard Edition (Java SE) and the
Java Enterprise Edition (Java EE) in itself.

The JDBC API has four main interfaces:


The latest version of JDBC 4.0 application programming interface is divided into two
packages

(i) java.sql
(ii) javax.sql.
Java SE and Java EE platforms are included in both the packages.

2. The JDBC Driver Manager.


The JDBC Driver Manager is a very important class that defines objects which connect Java
applications to a JDBC driver. Usually Driver Manager is the backbone of the JDBC architecture.

CU IDOL SELF LEARNING MATERIAL (SLM)


4 Advanced Internet Programming

It’s very simple and small that is used to provide a means of managing the different types of
JDBC database driver running on an application. The main responsibility of JDBC database
driver is to load all the drivers found in the system properly as well as to select the most
appropriate driver from opening a connection to a database. The Driver Manager also helps to
select the most appropriate driver from the previously loaded drivers when a new open database is
connected.

3. The JDBC Test Suite.


The function of JDBC driver test suite is to make ensure that the JDBC drivers will run
user’s program or not. The test suite of JDBC application program interface is very useful for
testing a driver based on JDBC technology during testing period. It ensures the requirement of
Java Platform Enterprise Edition (J2EE).

4. The JDBC-ODBC Bridge.


The JDBC-ODBC bridge, also known as JDBC type 1 driver is a database driver that utilizes
the ODBC driver to connect the database. This driver translates JDBC method calls into ODBC
function calls. The Bridge implements Jdbc for any database for which an Odbc driver is
available. The Bridge is always implemented as the sun.jdbc.odbc Java package and it contains a
native library used to access ODBC.

Now we can conclude this topic: This first two component of JDBC, the JDBC API and the
JDBC Driver Manager manages to connect to the database and then build a java program that
utilizes SQL commands to communicate with any RDBMS. On the other hand, the last two
components are used to communicate with ODBC or to test web application in the specialized
environment.

JDBC is an API specification developed by Sun Microsystems that defines a uniform


interface for accessing various relational databases. JDBC is a core part of the Java platform and
is included in the standard JDK distribution.

1.4 Layers of the JDBC Architecture


JDBC is a platform-independent interface between relational databases and Java. In today’s
Java world, JDBC is a standard application programming interface (API) for accessing enterprise
data in relational databases (such as Oracle, MySQL, Sybase, and DB2) using Structured Query
Language (SQL). JDBC stands for Java Database Connectivity.

CU IDOL SELF LEARNING MATERIAL (SLM)


Java Data Base Connectivity 5

Java Java
Application 1 Application 2

JDBC API

Driver Manager

JDBC-ODBC Bridge
JDBC Driver
ODBC Driver

Microsoft
MySQL Oracle
Access Database
Database Database

Fig. 1.1: JDBC Architecture


Table 1.1: How Does JDBC Work?
How Does JDBC Work? JDBC API
 Class.forName(“oracle.jdbc.driver.OracleDr The JDBC API is comprised of two Java packages:
iver”) java.sql and javax.sql.
 Calling Class.forName() automatically  java.sql: This is the initial package that
creates an instance of the driver and provides the API for accessing and
registers the driver with the processing data stored in a data source
DriverManagerclass. The driver talks to a (usually a relational database) using the Java
particular database such as Oracle or programming language.
MySQL.
 DriverManager is a connection factory  javax.sql: This is an extended package that
class. In fact, it is the only class that can provides the API for server-side data source
create database connections. The access and processing from the Java
DriverManager uses drivers to create programming language.
connections.
 A Java database application uses the
DriverManager class to get the
java.sql.Connection object, which
represents a database connection.

1.5 JDBC Driver


A JDBC Driver allows a Java application/client to communicate with a SQL database. A
JDBC driver is a Java class that implements the JDBC’s java.sql.Driver interface and understands
how to convert program (and typically SQL) requests for a particular database. A Java program

CU IDOL SELF LEARNING MATERIAL (SLM)


6 Advanced Internet Programming

that uses the JDBC API loads the specified driver for a particular DBMS before it actually
connects to a database.

Types of Drivers
The Type 1 driver – JDBC-ODBC BRIDGE
translates its calls into ODBC calls .ODBC then interacts with
Java Application
the desired database. It is the most available but slowest type, and JDBC API
it works only on Microsoft Windows and Sun Solaris. There is
only one driver in existence, sun.jdbc.odbc.JdbcOdbcDriver. Bridge Driver

Advantages DSN
ODBC
 Almost any database for which ODBC driver is installed, Driver

can be accessed.
 A type 1 driver is easy to install.
DB

Fig. 1.2: The JDBC-


ODBC Bridge Driver

Disadvantages
 Performance overhead since the calls have to go through the JDBC overhead bridge to
the ODBC driver, then to the native db connectivity interface.
 The ODBC driver needs to be installed on the client machine.
 Considering the client-side software needed, this might not be suitable for applets.
 Will not be suitable for internet applications.

Type 2 Driver - the Native-API Driver


 It is written partly in the java programming language and partly native code that
communicates with the client API of a database.
 The kind of driver converts JDBC calls into calls on the client API for oracle, Sysbase,
Enformics, IBM, DB-2or other DBMS.
 When you use such a driver you must install some platform specific code in addition to
java library.

CU IDOL SELF LEARNING MATERIAL (SLM)


Java Data Base Connectivity 7

Advantages Java Application

This type of diver is faster than JDBC-ODBC driver. Java API Driver

Disadvantages Native API Driver

 It requires local administration.


Native API
 Native libraries are required.
 It is not a pure java driver.
DB

Fig. 1.3: The Native-API


Driver

Type 3 driver - the Network-Protocol Driver


This driver converts the JDBC calls into a DBMS independent net protocol, which is then
converted to the format as required by database by a middle server.

Advantages Java Application

This type of diver is faster than JDBC-ODBC driver. JDBC API

Disadvantages
Type 3 Driver
 It requires local administration.
Net common Protocol
 Native libraries are required. Middleware
component
 It is not a pure java driver.

DB

Fig. 1.4: The Network-Protocol


Driver

Type IV: Native-Protocol -Java Driver


This is the fastest way to communicate as the JDBC calls are directly converted to a network
protocol used by DBMS. This driver is completely written in Java.

CU IDOL SELF LEARNING MATERIAL (SLM)


8 Advanced Internet Programming

Advantages Java Application

 It is faster than all previous 3 drivers JDBC API

 It is a pure java drivers.


 No local administration is required Thin/Type 4 Driver

Native Protocol

OB

Fig. 1.5: Native-Protocol-Java Driver

1.6 Java Database Connectivity Steps


1. Loading a Database Driver
In this step of the jdbc connection process,
Syntax
we load the driver class by calling
Class.forName() with the Driver class name as an try {
argument. Once loaded, the Driver class creates Class.forName("sun.jdbc.odbc.JdbcOdbcDri
ver"); //Or any other driver
an instance of itself. A client can connect to
}
Database Server through JDBC Driver. Since
catch(Exception x){
most of the Database servers support ODBC
System.out.println( "Unable to load the
driver therefore JDBC-ODBC Bridge driver is
driver class!" );
commonly used. The return type of the
}
Class.forName (String ClassName) method is
“Class”. Class is a class in java.lang package.

2. Establishing Database Connection


The JDBC DriverManager class defines objects which can connect Java applications to a
JDBC driver. DriverManager is considered the backbone of JDBC architecture. DriverManager
class manages the JDBC drivers that are installed on the system. Its getConnection() method is
used to establish a connection to a database. It uses a username, password, and a jdbcurl to
establish a connection to the database and returns a connection object. A jdbc Connection
represents a session/connection with a specific database. Within the context of a Connection, SQL,
PL/SQL statements are executed and results are returned. An application can have one or more

CU IDOL SELF LEARNING MATERIAL (SLM)


Java Data Base Connectivity 9

connections with a single database. DriverManager knows to use the


sun.jdbc.odbc.JdbcOdbcDriver.

Syntax

Connection con=DriverManager.getConnection(url,"loginName","Password")

3. Creating a JDBC Statement object


Once a connection is obtained we can interact with the database. Connection interface
defines methods for interacting with the database via the established connection. To execute SQL
statements, you need to instantiate a Statement object from your connection object by using the
createStatement() method. A statement object is used to send and execute SQL statements to a
database.

Three kinds of Statements


Statement: Execute simple sql queries without parameters.

Statement createStatement()

Creates an SQL Statement object.

Prepared Statement: Execute precompiled sql queries with or without parameters.

PreparedStatementprepareStatement(String sql)
returns a new PreparedStatement object. PreparedStatement objects are precompiled SQL
statements.

Callable Statement: Execute a call to a database stored procedure.

CallableStatementprepareCall(String sql)

returns a new CallableStatement object. CallableStatement objects are SQL stored procedure
call statements.

4. Executing the Statement object, and returning a jdbcresultSet.


Statement interface defines methods that are used to interact with database via the execution
of SQL statements.

The Statement class has three methods for executing statements:

executeQuery(), executeUpdate(), and execute().

For a SELECT statement, the method to use is executeQuery.

CU IDOL SELF LEARNING MATERIAL (SLM)


10 Advanced Internet Programming

For statements that create or modify tables, the method to use is executeUpdate.

execute() executes an SQL statement that is written as String object.

ResultSet provides access to a table of data generated by executing a Statement. The table
rows are retrieved in sequence. A ResultSet maintains a cursor pointing to its current row of data.
The next() method is used to successively step through the rows of the tabular results.

Syntax

stmt=conn.createStatement();
inti=stmt.executeUpdate("insert into t1 values(101, ’ram’, ’3000’);

5. Closing Connection
Closing the connection closes the object statement and ResultSet automatically. The close()
method of Connection interface is used to close the connection. All the connections at the end of
JDBC program every connection to the database and each database session has to be closed
explicitly. One must not rely on the garbage collection especially when we do database
programming as it is considered to be a poor programming practice. Any connection, which is
associated with any connection object, must be closed using close() method.

One must ensure that connection is closed and for that finally block must be inserted in the
code. A finally block always executes, regardless if an exception occurs or not.

To close above opened connection you should call close() method as follows:
Syntax

conn.close();
pstmt.close();
rs.close();

1.7 JDBC Statements


There are three types of statements:

Statement: It is an interface which creates an object that is used to execute static SQL
statements and obtain the result produced by it..Executes simple query without any
parameter.createStatement() creates an SQL statement object.

CU IDOL SELF LEARNING MATERIAL (SLM)


Java Data Base Connectivity 11

Syntax

stmt=conn.createStatement();
inti=stmt.executeUpdate("insert into t1 values(101, ’ram’, ’3000’);
Prepared Statement: It executes precompiled sql queries with or without parameters. A
SQL statement is given to a PreparedStatement object, unlike a Statement object, when it is
created. In most cases, this SQL statement is sent to the DBMS right away, where it is compiled.
The PreparedStatement object contains not just a SQL statement, but a precompiled SQL
statement. This means that when PreparedStatement is executed, the DBMS can just run
PreparedStatement SQL statement without having to compile it first. PreparedStatement objects
can be used for SQL statements with no parameters, but they must be used with SQL statements
having parameters. One can use the same statement and supply it with different values every time
it gets executed which is the main advantage of PreparedStatement. For example:
prepareStatement (String sql) returns a new PreparedStatement object. PreparedStatement objects
are precompiled SQL statements.

Syntax

PreparedStatementpstmt=null;
pstmt=conn.prepareStatement("select * from t1");
rs=pstmt.executeQuery();
while(rs.next())
{
System.out.println("ID Is:"+rs.getInt("id"));
System.out.println("Name Is:"+rs.getString("name"));
System.out.println("Sal:"+rs.getDouble("salary"));
}

Callable Statement: a callable statement creates CallableStatement object just as a


Connection object creates the Statement and PreparedStatement objects which is used to execute
a call to a database stored procedure.

CallableStatementprepareCall(String sql) returns a new CallableStatement object.


CallableStatement objects are SQL stored procedure call statements.

1.8 Types of ResultSet


The possible RSType are given below. If you do not specify any ResultSet type, you will
automatically get one that is TYPE_FORWARD_ONLY.

CU IDOL SELF LEARNING MATERIAL (SLM)


12 Advanced Internet Programming

Type Description
1. ResultSet.TYPE_FORWARD_ONLY: The cursor can only move forward in the result
set.
2. ResultSet.TYPE_SCROLL_INSENSITIVE: The cursor can scroll forward and
backward, and the result set is not sensitive to changes made by others to the database
that occur after the result set was created.
3. ResultSet.TYPE_SCROLL_SENSITIVE.: The cursor can scroll forward and
backward, and the result set is sensitive to changes made by others to the database that
occur after the result set was created.

Concurrency of ResultSet
The possible RSConcurrency are given below. If you do not specify any Concurrency type,
you will automatically get one that is CONCUR_READ_ONLY.

Concurrency Description
1. ResultSet.CONCUR_READ_ONLY- Creates a read-only result set. This is the default
2. ResultSet.CONCUR_UPDATABLE- Creates an updateable result set.

1.9 CRUD operation with Examples


Example Based on Java Database Connectivity.
Program 1: MySQL Database Connectivity using Command Prompt.

import java.awt.*; s3=dis.readLine();


import java.awt.event.*; Class.forName("com.mysql.jdbc.Driver") ;
import java.sql.*; // System.out.println("driver Registered
import java.io.*; Successfully");
con=DriverManager.getConnection("jdbc:mysql
://localhost:3306/cbs","root","cbs123");
class jdbcinsertdemo
//System.out.println("Database Connected
{ Successfully");
public static void main(String args[]) PreparedStatement ps=
{ con.prepareStatement(q);
DataInputStream dis=new ps.setString(1,s1);
DataInputStream(System.in); ps.setString(2,s2);
try ps.setString(3,s3);

CU IDOL SELF LEARNING MATERIAL (SLM)


Java Data Base Connectivity 13

{ ps.executeUpdate();
Connection con; System.out.println("Successful...");
String q="insert into }
emp1(empid,empname,city)values(?,?,?)"; catch(Exception e)
String s1,s2,s3; {
System.out.println("Enter Employee Id:"); System.out.println("Got an Exception");
s1=dis.readLine(); System.err.println(e.getMessage());
System.out.println("Enter Employee }
Name:");
} }
s2=dis.readLine();
System.out.println("Enter City.....:");

Execution of the Program. Database After Insertion

1.10 Practical Assignment


1. Develop JDBC application to create Login Form with MYSQL as backend.
2. Develop JDBC application for CRUD operations.

1.11 Summary
Java Database Connectivity(JDBC) is an Application Programming Interface(API) used to
connect Java application with Database. JDBC is used to interact with various type of Database
such as Oracle, MS Access, My SQL and SQL Server. JDBC can also be defined as the platform-
independent interface between a relational database and Java programming. It allows java
program to execute SQL statement and retrieve result from database.

CU IDOL SELF LEARNING MATERIAL (SLM)


14 Advanced Internet Programming

1.12 Key Words/Abbreviations


 Database server: It is similar to data warehouse where the website store or maintain
their data and information. A Database Server is a computer in a LAN that is dedicated
to database storage and retrieval. The database server holds the Database Management
System (DBMS) and the databases. Upon requests from the client machines, it searches
the database for selected records and passes them back over the network.
 JDBC: Java Database Connectivity
 ODBC: Open Database Connectivity
 DSN: data source name

1.13 Learning Activity


1. Explain CURD operations.
-----------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------
2. Explain JDBC-ODBC bridge.
-----------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------

1.14 Unit End Questions (MCQs and Descriptive)


A. Descriptive Types Questions
1. What is JDBC? Explain the architecture of JDBC in detail.
2. Write and Explain steps of Java Database Connectivity.
3. Write short notes on JDBC Drivers?
4. What are Scrollable Resultset in JDBC?
5. Explain Rowsets and its types in JDBC?
6. Write short notes on JDBC transactions?
7. How to use Save Points in JDBC?
8. Write a program to show connectivity steps using MySql.
9. Write a program to retrieve data from oracle database using JDBC.

CU IDOL SELF LEARNING MATERIAL (SLM)


Java Data Base Connectivity 15

8. Write a program to show connectivity steps using MySql.


9. Write a program to retrieve data from oracle database using JDBC.

B. Multiple Choice/Objective Type Questions


1. Which of the following is true about JDBC architecture?
(a) JDBC API layer provides the application-to-JDBC Manager connection.
(b) JDBC Driver API layer supports the JDBC Manager-to-Driver Connection.
(c) Both of the above.
(d) None of the above.
2. Which of the following holds data retrieved from a database after you execute an SQL
query using Statement objects?
(a) ResultSet (b) JDBC driver
(c) Connection (d) Statement
3. Which of the following type of JDBC driver is typically used for development and
testing purposes only?
(a) Type 1 (b) Type 2
(c) Type 3 (d). Type 4
4. Which of the following type of JDBC driver should be used when you are accessing one
type of database, such as Oracle, Sybase, or IBM?
(a) Type 1 (b) Type 2
(c) Type 3 (d) Type 4
5. Which of the following is a Metadata interfaces of JDBC?
(a) DatabaseMetaData (b) ResultSetMetaData
(c) Both of the above. (d) None of the above.

Answers
1. (c), 2. (a), 3. (d), 4. (a), 5. (c)

CU IDOL SELF LEARNING MATERIAL (SLM)


16 Advanced Internet Programming

1.15 References
1. https://www.studytonight.com/java/introduction-to-jdbc.php
2. https://www.javaworld.com/article/3388036/what-is-jdbc-introduction-to-java-database-
connectivity.html
3. JDBC 4.2, Servlet 3.1, and JSP 2.3 Includes JSF 2.2 and Design Patterns, Black Book,
2ed

CU IDOL SELF LEARNING MATERIAL (SLM)


UNIT 2 USER INTERFACE COMPONENTS

Structure:
2.0 Learning Objectives

2.1 Introduction

2.2 MVC Architecture

2.3 Layout Manager

2.4 Introduction To JFC and SWING

2.5 Need of Swing Component

2.6 Difference between AWT and Swing

2.7 Hierarchy of Java Swing classes

2.8 Swing Features And Concepts

2.9 Swing API Components

2.10 Container class (Swing API Components - Top-Level Containers)

2.11 Jcomponent class

2.12 JButton

2.13 JLabel

2.14 JText

2.15 JTextArea

2.16 JcheckBox and JradioButton

2.17 Jlist

CU IDOL SELF LEARNING MATERIAL (SLM)


18 Advanced Internet Programming

2.18 JcomboBox

2.19 JMenu and JPopupMenu Class

2.20 JMenu Item and JCheck Box Menu Item

2.21 J Radio Button Menu Item,

2.22 J scrollBar

2.23 Dialogs (Message, Confirmation, Input)

2.24 J File Chooser

2.25 Jcolor Chooser

2.26 Summary

2.27 Practical Assignment

2.28 Key Words/Abbreviations

2.29 Learning Activity

2.30 Unit End Questions (MCQs and Descriptive)

2.31 References

2.0 Learning Objectives


After studying this unit, you will be able to:

 Describe MVC architecture


 Elaborate layout manager and Jcomponent class
 Explain various user interface components

2.1 Introduction
 MVC stands for Model View and Controller. It is a design pattern that separates the
business logic, presentation logic and data.

CU IDOL SELF LEARNING MATERIAL (SLM)


User Interface Components 19

 Controller acts as an interface between View and Model. Controller intercepts all the
incoming requests.
 Model represents the state of the application i.e. data. It can also have business logic.
 View represents the presentation i.e. UI(User Interface).
Java Swing is a part of Java Foundation Classes (JFC) which was designed for enabling
large-scale enterprise development of Java applications. Java Swing is a set of APIs that provides
graphical user interface (GUI) for Java programs. Java Swing is also known as Java GUI widget
toolkit.

Java Swing or Swing was developed based on earlier APIs called Abstract Windows Toolkit
(AWT). Swing provides richer and more sophisticated GUI components than AWT. The GUI
components are ranging from a simple label to complex tree and table. Besides emulating look
and feel of various platforms, Swing also provides the pluggable look and feel to allow look and
feel of Java programs independent from the underlying platform.

2.2 MVC Architecture


Model–view–controller (MVC) is a software architectural pattern for implementing user
interfaces on computers. It divides a given application into three interconnected parts.

“Model” consist of database operations(CRUD operations; Create, Read, Update, Delete


queries), “View” consist of Front end development (HTML, CSS, JavaScript etc) and
“Controller” consist of the main business logic (Backend programming through server side
languages such as PHP, JAVA etc). ‘Controller” controls the interaction/transactions between the
“Model” and “Viewer”.

VIEWER
MODEL

CONTROLLER

Fig. 2.1: MVC Architecture


Struts 2 MVC is realised by three core framework components: actions, results, and the
ServletFilter. The diagram below shows how these three components interact with each other.

CU IDOL SELF LEARNING MATERIAL (SLM)


20 Advanced Internet Programming

request Invoke action Model

Controller Action

Servlet Filter

Interceptor
Web Browser Select result
Client

View

Result

Render result

Fig. 2.2: MVC Struts 2

Servlet Filter

The servlet filter acts as a controller in Struts 2. It inspects each incoming request to
determine which Struts 2 action should handle the request. The framework handles all of the
controller work for the application. All request URLs need to be mapped to actions with XML-
based configuration files or Java annotations.

Interceptors
Interceptors execute before and after the request processing. They provide cross-cutting tasks
so that they can be easily reused as well as separated from other architectural concerns. For
example, validation parameters before invoking login action.

Action
Action handles the client requests in two different ways. First, the action plays an important
role in the transfer of data from the request through to the view, whether it’s a JSP or other type
of result. Second, the action must assist the framework in determining which result should render
the view that will be returned in the response to the request.

Result
Result is a JSP or HTML page to create a view for client response. Struts 2 provide their own
tags that we can use in JSP pages to create a response. Struts tags are great example of JSP
Custom Tags.

CU IDOL SELF LEARNING MATERIAL (SLM)


User Interface Components 21

2.3 Layout Manager


Understanding LayoutManagers
The Layout Managers are used to arrange components in a particular manner. Layout
Manager is an interface that is implemented by all the classes of layout managers. There are
following classes that represent the layout managers:

java.awt.BorderLayout javax.swing.BoxLayout
java.awt.FlowLayout javax.swing.GroupLayout
java.awt.GridLayout javax.swing.ScrollPaneLayout
java.awt.CardLayout javax.swing.SpringLayout etc.
java.awt.GridBagLayout

BorderLayout
The BorderLayout is used to arrange the components in five regions: north, south, east, west
and center. Each region (area) may contain one component only. It is the default layout of frame
or window. The BorderLayout provides five constants for each region:

1. public static final int NORTH 4. public static final int WEST
2. public static final int SOUTH 5. public static final int CENTER
3. public static final int EAST

Constructors used
BorderLayout(): creates a border layout but with no gaps between the components.

JBorderLayout(inthgap, intvgap): creates a border layout with the given horizontal and
vertical gaps between the components.

Example:

Import java.awt.*; f.add(b1,BorderLayout.NORTH);


Import javax.swing.*; f.add(b2,BorderLayout.SOUTH);
public class BorderLayoutExample { f.add(b3,BorderLayout.EAST);
JFrame f; f.add(b4,BorderLayout.WEST);
BorderLayoutExample() { f.add(b5,BorderLayout.CENTER);
f=new JFrame(); f.setSize(300,300);
JButton b1=new JButton("NORTH");; f.setVisible(true); }

CU IDOL SELF LEARNING MATERIAL (SLM)


22 Advanced Internet Programming

JButton b2=new JButton("SOUTH");; public static void main(String[] args) {


JButton b3=new JButton("EAST");; newBorderLayoutExample();
JButton b4=new JButton("WEST");;
} }
JButton b5=new JButton("CENTER");;

Output

NORTH

WEST CENTER EAST

SOUTH

GridLayout
The GridLayout is used to arrange the components in rectangular grid. One component is
displayed in each rectangle.

Constructors
1. GridLayout():creates a grid layout with one column per component in a row.
2. GridLayout(int rows, int columns): creates a grid layout with the given rows and
columns but no gaps between the components.
3. GridLayout(int rows, int columns, inthgap, intvgap): creates a grid layout with the
given rows and columns alongwith given horizontal and vertical gaps.

Example:
Import java.awt.*; f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5)
Import javax.swing.*; ;

public class MyGridLayoutExample { f.add(b6);f.add(b7);f.add(b8);f.add(b9)


f.setLayout(new GridLayout(3,3));
JFrame f;
f.setSize(300,300);
MyGridLayoutExample() {
f.setVisible(true);
f=new JFrame(); }
JButton b1=new JButton("A"); public static void main(String[] args) {
JButton b2=new JButton("B"); new MyGridLayoutExample();

CU IDOL SELF LEARNING MATERIAL (SLM)


User Interface Components 23

JButton b3=new JButton("C");


}}
JButton b4=new JButton("D");
Output:
JButton b5=new JButton("E");
JButton b6=new JButton("F");
JButton b7=new JButton("G"); A B C
JButton b8=new JButton("H");
JButton b9=new JButton("I"); D E F

;
G H I

FlowLayout
The FlowLayout is used to arrange the components in a line, one after another (in a flow). It
is the default layout of applet or panel.
Fields of FlowLayout class:

public static final int LEFT public static final int LEADING
public static final int RIGHT public static final int TRAILING
public static final int CENTER

Constructors
 FlowLayout():creates a flow layout with centered alignment and a default 5 unit
horizontal and vertical gap.
 FlowLayout(int align):creates a flow layout with the given alignment and a default 5
unit horizontal and vertical gap.
 FlowLayout(int align, inthgap, intvgap):creates a flow layout with the given alignment
and the given horizontal and vertical gap

Example:
Import java.awt.*; f.setLayout(new
Import javax.swing.*; FlowLayout(FlowLayout.RIGHT));

public class FlowLayoutDemo { f.setSize(300,300);

JFrame f; f.setVisible(true);

FlowLayoutDemo() { }

f=new JFrame(); public static void main(String[] args) {

JButton b1=new JButton("A"); new FlowLayoutDemo();

CU IDOL SELF LEARNING MATERIAL (SLM)


24 Advanced Internet Programming

JButton b2=new JButton("B"); }}


JButton b3=new JButton("C");
Output
JButton b4=new JButton("D");
JButton b5=new JButton("5");
f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b
5);

BoxLayout
The BoxLayout is used to arrange the components either vertically or horizontally. For this
purpose, BoxLayout provides four constants. They are as follows:

Class in BoxLayout
public static final int X_AXIS public static final int LINE_AXIS
public static final int Y_AXIS public static final int PAGE_AXIS

Constructor
BoxLayout(Container c, int axis):creates a box layout that arranges the components with
the given axis.

Example:
importjava.awt.*;
importjavax.swing.*;
Output:
public class BoxLayoutDemo extends Frame {
Button buttons[];
public BoxLayoutDemo () {
buttons = new Button [5];
for (inti = 0;i<5;i++) {
buttons[i] = new Button ("Button " + (i + 1));
add (buttons[i]); }
setLayout (new BoxLayout (this,
BoxLayout.Y_AXIS));
setSize(400,400);
setVisible(true); }
public static void main(String args[]) {
BoxLayoutDemo b=new BoxLayoutDemo();
} }

CU IDOL SELF LEARNING MATERIAL (SLM)


User Interface Components 25

CardLayout
The CardLayout class manages the components in such a manner that only one component is
visible at a time. It treats each component as a card that is why it is known as CardLayout.

Constructors
 CardLayout():creates a card layout with zero horizontal and vertical gap.
 CardLayout(inthgap, intvgap):creates a card layout with the given horizontal and
vertical gap.

Methods of CardLayout
 public void next(Container parent):is used to flip to the next card of the given
container.
 public void previous(Container parent):is used to flip to the previous card of the given
container.
 public void first(Container parent): is used to flip to the first card of the given
container.
 public void last(Container parent): is used to flip to the last card of the given container.
 public void show(Container parent, String name): is used to flip to the specified card
with the given name.

Example:
Import java.awt.*; b3=new JButton("Animal");
Import java.awt.event.*; b1.addActionListener(this);
Import javax.swing.*; b2.addActionListener(this);
public class CardLayoutDemo extends JFrame b3.addActionListener(this);
implements ActionListener { c.add("a",b1);c.add("b",b2);c.add("c",b3); }
CardLayout card; public void actionPerformed(ActionEvent e) {
JButton b1,b2,b3; card.next(c); }
Container c; public static void main(String[] args) {
CardLayoutDemo() { CardLayoutDemo cl=new CardLayoutDemo();
c=getContentPane(); cl.setSize(400,400);
card=new CardLayout(40,30); cl.setVisible(true);
c.setLayout(card); cl.setDefaultCloseOperation(EXIT_ON_CLOSE
b1=new JButton("Book"); ); } }
b2=new JButton("Flower");

CU IDOL SELF LEARNING MATERIAL (SLM)


26 Advanced Internet Programming

Output:

Flower

2.4 Introduction to JFC and Swing

JFC is short for Java Foundation Classes, which encompass a group of features for building
graphical user interfaces(GUIs) and adding rich graphics functionality and interactivity to Java
applications.

Swing is a set of program components for Java programmers that provide the ability to create
graphical user interface ( GUI ) components, such as buttons and scroll bars that are independent
of the windowing system for specific operating system . Swing components are used with the
Java Foundation Classes ( JFC ).

2.5 Need of Swing Component


Swing was developed to provide a more sophisticated set of GUI components than the earlier
Abstract Window Toolkit (AWT). Unlike AWT components, Swing components are not
implemented by platform-specific code. Instead, they are written entirely in Java and therefore are
platform-independent.

It is defined as containing the features shown in the table below.

CU IDOL SELF LEARNING MATERIAL (SLM)


User Interface Components 27

2.6 Difference between AWT and Swing


Table 2.1: Difference between AWT and Swing
Feature Description
AWT components are platform-dependent. Java swing components are platform-
independent.
AWT components are heavyweight. Swing components are lightweight.

AWT doesn’t support pluggable look and feel. Swingsupports pluggable look and feel.
AWT provides less components than Swing. Swing provides more powerful components such
as tables, lists, scroll panes, color chooser, tabbed
pane etc.
AWTdoesn’t follows MVC (Model View Swingfollows MVC.
Controller) where model represents data, view
represents presentation and controller acts as an
interface between model and view.

2.7 Hierarchy of Java Swing Classes


Object

Component JLabel

JList

JTable
Container JComponent

JComboBox

Window Panel JSlider

JMenu
Applet

AbstractButton
Frame Dialog

JButton

Fig. 2.3: Hierarchy of Java Swing Classes

CU IDOL SELF LEARNING MATERIAL (SLM)


28 Advanced Internet Programming

2.8 Swing Features and Concepts


Swing Components and the Containment Hierarchy- Swing provides many standard GUI
components such as buttons, lists, menus, and text areas, which you combine to create your
program’s GUI. It also includes containers such as windows and toolbars.

Layout Management: Layout management is the process of determining the size and
position of components. By default, each container has a layout manager—an object that
performs layout management for the components within the container. Components can provide
size and alignment hints to layout managers, but layout managers have the final say on the size
and position of those components.

Event Handling: Event handling is how programs respond to external events, such as the
user pressing a mouse button. Swing programs perform all their painting and event handling in
the event-dispatching thread. Every time the user types a character or pushes a mouse button, an
event occurs. Any object can be notified of the event. All it has to do is implement the appropriate
interface and be registered as an event listener on the appropriate event source. Swing
components can generate many kinds of events. Here are a few examples:
Table 2.2: Event Handling Examples
Act that results in the event Listener type
User clicks a button, presses Return while typing in a text field, or chooses Action Listener
a menu item
User closes a frame(main window) Window Listener
User presses a mouse button while the cursor is over a component Mouse Listener
User moves the mouse over a component Mouse Motion Listener
Component becomes visible Component Listener
Component gets the keyboard focus Focus Listener
Table or list selection changes List Selection Listener
Painting: Painting means drawing the component on-screen.

Although it’s easy to customize a component’s painting, most programs don't do anything
more complicated than customizing a component’s border.

Threads and Swing: If you do something to a visible component that might depend on or
affect its state, then you need to do it from the event-dispatching thread. This isn’t an issue for
many simple programs, which generally refer to components only in event-handling code.

CU IDOL SELF LEARNING MATERIAL (SLM)


User Interface Components 29

More Swing Features and Concepts: Swing offers many features, many of which rely on
support provided by the JComponent class. Some of the interesting features include support for
icons, actions, Pluggable Look & Feel technology, assistive technologies, and separate models.

2.9 Swing API Components


2.9.1 JFrames
A frame, Implemented as an instance of the JFrame class, is a window that has decorations
such as a border, a title, and buttons for closing and iconifying the window. Applications with a
GUI typically use at least one frame. By default, when the user closes a frame on screen, the
frame is hidden .Although invisible, the frame still exists and the program can make it visible
again. If you want different behavior, then you need to either register a window listener that
handles window-closing events, or you need to specify default close behavior using the
setDefaultCloseOperation method. You can even do both.

The argument to setDefaultCloseOperation must be one of the following values, which are
defined in the Window Constants interface:

 DO_NOTHING_ON_CLOSE:- Don’t do anything when the user’s requests that the


frame close. Instead, the program should probably use a window listener that performs
some other action in its window closing method.
 HIDE_ON_CLOSE (the default): Hide the frame when the user closes it. This removes
the frame from the screen.
 DISPOSE_ON_CLOSE:Hide and dispose of the frame when the user closes it. This
removes the frame from the screen and frees up any resources used by it.

Constructors
JFrame() Create a frame that is initially invisible. Call set Visible(true)on the frame
JFrame(String) to make it visible. The String argument provides a title for the frame. You
can also use set Title to set a frame’s title.

Methods
1. ContainergetContentPane()-Returns the content Pane object for this frame.
2. JMenuBargetJMenuBar() –Returns the menu bar set on this frame.
3. voidsetDefaultCloseOperation(int operation) -Sets the operation that will happen by default
when the user initiates a "close" on this frame.

CU IDOL SELF LEARNING MATERIAL (SLM)


30 Advanced Internet Programming

4. voidsetJMenuBar(JMenuBarmenubar)-Sets the menubar for this frame.


5. void setVisible(Boolean b) - Shows or hides this component depending on the value of parameter
b.
6. voidsetLocation(intx,inty)-Moves this component to a new location. The top-left corner of the
new location is specified by the x and y parameters in the coordinate space of this component's
parent.
7. voidpack()-Causes this Window to be sized to fit the preferred size and layouts of its sub
components. If the window and/or its owner are not yet displayable, both are made displayable
before calculating the preferred size. The Window will be validated after the preferred Size is
calculated.
8. voidsetTitle(Stringtitle)-Sets the title for this frame to the specified string.

2.9.2 JApplet
JApplet is an extended version of java.applet. Applet that adds support for the JFC/Swing
component architecture. The JAppletclass is slightly incompatible with java.applet.Applet.
JApplet contains a JRootPane as it’s only child. The content Pane should be the parent of any
children of the JApplet.

To add the child to the JApplet’s content Pane we use the getContentPane()method and add
the components to the content Pane. The same is true for setting LayoutManagers, removing
components, listing children, etc. All these methods should normally be sent to the
contentPane()insteadoftheJAppletitself.ThecontentPane()willalwaysbe non-null. Attempting to set
it to null will cause the JApplet to throw an exception. The default contentPane() will have a
Border Layout manager set on it.

JApplet adds two major features to the functionality that it inherits from java.applet.Applet.
First, Swing applets provide support for assistive technologies. Second, because JApplet is a top-
level Swing container, each Swing applet has a root pane. The most noticeable results of the root
pane’s presence are support for adding a menu bar and the need to use a contentpane.

Constructor
JApplet()- Creates a swing applet instance

CU IDOL SELF LEARNING MATERIAL (SLM)


User Interface Components 31

Methods
1. Container getContentPane()-Returns the contentPane object for this applet.
2. void setJMenuBar (JMenuBarmenuBar)- Sets the menubar for this applet.
3. void setLayout (LayoutManagermanager) - By default the layout of this component may not be
set, the layout of its contentPane should be set instead.
4. void update(Graphics g)-Just calls paint(g).

java.applet.Applet class
For creating any applet java.applet.Applet class must be inherited. It provides 4 life cycle
methods of applet.

1. Public void init(): is used to initialized the Applet. It is invoked only once.
2. public void start():is invoked after the init() method or browser is maximized. It is used
to start the Applet.
3. public void stop():is used to stop the Applet. It is invoked when Applet is stop or
browser is minimized.
4. public void destroy():is used to destroy the Applet. It is invoked only once.

java.awt.Component class
The Component class provides 1 life cycle method of applet.

1. public void paint(Graphics g):is used to paint the Applet. It provides Graphics class
object that can be used for drawing oval, rectangle, arc etc.

How to run an Applet?


There are two ways to run an applet
1. By html file.
2. By appletViewertool .

Simple example of Applet by appletviewer tool:


To execute the applet by appletviewer tool, create an applet that contains applet tag in
comment and compile it. After that run it by: appletviewer First.java. Now Html file is not
required but it is for testing purpose only.

CU IDOL SELF LEARNING MATERIAL (SLM)


32 Advanced Internet Programming

//First.java /*
Import java.applet.Applet; <applet code="First.class" width="300"
Import java.awt.Graphics; height="300">

Public class First extends Applet { </applet>

Public void paint(Graphicsg) { */

g.drawString("welcome to applet",150,150); To execute the applet by appletviewer tool,


write in command prompt:
}
c:\>javac First.java
}
c:\>appletviewer First.html

2.9.3 J Window
A JWindow is a container that can be displayed anywhere on the user’s desktop. It does not
have the title bar, window- management buttons, or other trimmings associated with a JFrame,
but it is still a "first-class citizen" of the user’s desktop, and can exist anywhere on it. The
JWindow component contains a JRootPane as its only child. The content Pane should be the
parent of any children of the JWindow. From the older java.awt.Window object you would
normally do something like this:

window.add(child);
However, using JWindow you would code:
window.getContentPane().add(child);

The same is true of setting Layout Managers, removing components, listing children, etc. All
these methods should normally be sent to the content Pane instead of the JWindow itself. The
content Pane will always be non-null. Attempting to set it to null will cause the JWindow to throw
an exception. The default content Pane will have a Border Layout manager set on it.

Constructor
1. JWindow()-Creates a window with no specified owner.
2. JWindow (Frameowner)-Creates a window with the specified owner frame.

Methods
1. ConatinergetContentPane()-Returns the content Pane object for this applet.
2. voidsetLayout(LayoutManagermanager)- By default the layout of this component may not be
set, the layout fits content Pane should be set instead.
3. voidupdate(Graphicsg)-Just calls paint(g).
4. void windowInit() - Called by the constructors to init the JWindow properly.

CU IDOL SELF LEARNING MATERIAL (SLM)


User Interface Components 33

2.10 Container Class (Swing API Components - Top-Level Containers)


Swing provides three generally useful top-level container classes: JFrame JDialog, and
JApplet. To appear on screen, every GUI component must be part of a containment hierarchy.
Each containment hierarchy has a top-level container as its root. Each top-level container has a
content pane that, generally speaking, contains the visible components in that top-level container's
GUI. You can optionally add a menu bar to a top-level container. The menu bar is positioned
within the top-level container, but outside the content pane.

2.10.1 Top-Level Containers and Containment Hierarchies


Each program that uses Swing components has at least one top-level container. This top-level
container is the root of a containment hierarchy—the hierarchy that contains all of the Swing
components that appear inside the top-level container. As a rule, a standalone application with a
Swing-based GUI has at least one containment hierarchy with a JFrame as its root.

2.10.2 Adding Components to the ContentPane


Here’s the code that is used to get a frame’s content pane and add the yellow label to it:

frame.getContentPane().add(yellow Label, Border Layout.CENTER);

As the code shows, you find the contentpane of a top-level container by calling the
getContentPane method. The default content pane is a simple intermediate container that inherits
from JComponent, and that uses a BorderLayout as its layout manager. It’s easy to customize the
content pane -- setting the layout manager or adding a border, for example. The getContentPane
method returns a Container object, not a JComponentobject.

2.10.3 Adding a MenuBar


All top-level containers can, in theory, have a menubar. In practice, however, menubars
usually appear only in frames and perhaps in applets. To add a menubar to a frame or applet, you
create a JMenuBarobject, populate it with menus, and then call setJMenuBar .To adds a menu bar
to its frame use this code:
frame.setJMenuBar(MenuBar_Name);

2.11 Jcomponent class


The JComponent Class
With the exception of top-level containers, all Swing components whose names begin with
“J” descend from the JComponentclass. For example, JPanel, JScrollPane, JButton, and JTable all

CU IDOL SELF LEARNING MATERIAL (SLM)


34 Advanced Internet Programming

inherit from JComponent. However, JFrame and JDialog don’t because they implement top-level
containers.

The JComponent class extends the Container class, which itself extends Component. The
Component class includes everything from providing layout hints to supporting painting and
events. The Container class has support for adding components to the container and laying them
out. This section’s API tables summarize the most often used methods of Component and
Container, as well as of JComponent.

Constructor
JComponent() :- Default JComponent constructor.

Methods
Modifier and Type Method Description
void setActionMap(ActionMap am) It sets the ActionMap to am.

void setBackground(Color bg) It sets the background color of this component.

void setFont(Font font) It sets the font for this component.

void setMaximumSize(Dimension It sets the maximum size of this component to


maximumSize) a constant value.

void setMinimumSize(Dimension It sets the minimum size of this component to


minimumSize) a constant value.

protected void setUI(ComponentUI newUI) It sets the look and feel delegate for this
component.

void setVisible(boolean aFlag) It makes the component visible or invisible.

void setForeground(Color fg) It sets the foreground color of this component.

String getToolTipText(MouseEvent It returns the string to be used as the tooltip for


event) event.

Container getTopLevelAncestor() It returns the top-level ancestor of this


component (either the containing Window or
Applet), or null if this component has not been
added to any container.
TransferHandler getTransferHandler() It gets the transferHandler property.

CU IDOL SELF LEARNING MATERIAL (SLM)


User Interface Components 35

Java JComponent Example


Import java.awt.Color; JFrame
Import java.awt.Graphics; frame=newJFrame("JComponentExample");

Import javax.swing.JComponent; frame.setSize(300,200);

Import javax.swing.JFrame; frame.setDefaultCloseOperation(JFrame.EXIT


_ON_CLOSE);
Class MyJComponent extends JComponent{
//addtheJComponenttomainframe
Public void paint (Graphicsg) {
frame.add(com);
g.setColor(Color.green);
frame.setVisible(true);
g.fillRect(30,30,100,100);
}
} }
}
public class JComponentExample {
public static void main(String[]arguments) { Output
MyJComponent com=new MyJComponent();
//createabasicJFrame
JFrame.setDefaultLookAndFeelDecorated(true);

2.12 JButton
A JButton class provides the functionality of a pushbutton. JButton allows an icon, a string
or both to be associated with the push button. JButton is a sub class of Abstract Button which
extends JComponent.

Constructor Purpose
JButton(Action) Create a JButton instance, initializing it to have the specified
JButton(String, Icon) JButton(String) text/image/action.
JButton(Icon)
JButton()

Methods
void setAction(Action) ActiongetAction() Set or get the button’s properties according to values
from the Action instance.
void setText(String) StringgetText() Set or get the text displayed by the button.
voidsetIcon(Icon) IcongetIcon() Set or get the image displayed by the button when
the button isn’t selected or pressed.

CU IDOL SELF LEARNING MATERIAL (SLM)


36 Advanced Internet Programming

void setDisabledIcon(Icon) Set or get the image displayed by the button when it
IcongetDisabledIcon() is disabled. If you do not specify a disabled image,
then the look and feel creates one by manipulating
the default image.
void setPressedIcon(Icon) Set or get the image displayed by the button when it
IcongetPressedIcon() is being pressed.
void setAction(Action) ActiongetAction() Set or get the button’s properties according to values
from the Action instance.

Button Example
import java.awt.*; f.setSize(400,400);
import java.swing.*; f.setLayout(null);
public class Button1 f.setVisible(true);
{ }}
public static void main(String[] args)
Output:
{
JFrame f=new JFrame("Button Example");
JButton b=new JButton("Click Here");
b.setBounds(50,100,80,30);
f.add(b);

2.13 Jlabel
With the JLabel class, you can display unselectable text and images. If you need to create a
component that displays a string, an image, or both, you can do so by using or extending JLabel.
If the component is interactive and has a certain state, use a button instead of a label.

By specifying HTML code in a label’s text, you can give the label various characteristics
such as multiple lines, multiple fonts or multiple colors. If the label uses just a single color or font,
you can avoid the overhead of HTML processing by using the set Foreground or set Font method
instead. See Using HTML in Swing Components for details.

Note that labels are not opaque by default. If you need to paint the label’s background, it is
recommended that you turn its opacity property to “true”. The following code snippet shows how
to do this. label.setOpaque(true);

CU IDOL SELF LEARNING MATERIAL (SLM)


User Interface Components 37

Method or Constructor Purpose


Creates aJLabelinstance, initializing it to have the specified
JLabel(Icon)
text/image/alignment. Theintargument specifies the horizontal
JLabel(Icon, int) alignment of the label’s contents within its drawing area. The
JLabel(String) horizontal alignment must be one of the following constants defined in
JLabel(String, Icon, int) theSwing Constants interface
JLabel(String, int) (whichJLabelimplements):LEFT,CENTER,RIGHT,LEADING,
orTRAILING. For ease of localization, we strongly recommend
JLabel()
usingLEADINGandTRAILING, rather thanLEFTandRIGHT.
void setText(String) Sets or gets the text displayed by the label. You can use HTML tags to
String getText() format the text, as described inUsing HTML in Swing Components.

void setIcon(Icon)
Sets or gets the image displayed by the label.
Icon getIcon()

void setDisabledIcon(Icon) Sets or gets the image displayed by the label when it is disabled. If you
do not specify a disabled image, then the look and feel creates one by
Icon getDisabledIcon() manipulating the default image.

Example:
import java.awt.GridLayout; // We can position of the text, relative to the icon:
import java.awt.event.WindowAdapter; jlbLabel1.setVerticalTextPosition(JLabel.BOTTOM);
import java.awt.event.WindowEvent; jlbLabel1.setHorizontalTextPosition(JLabel.CENTE
import javax.swing.JLabel; R);
import javax.swing.JPanel; jlbLabel2 = new JLabel("Text Only Label");
import javax.swing.JFrame; jlbLabel3 = new JLabel(icon); // Label of Icon Only
import javax.swing.ImageIcon; // Add labels to the Panel
public class JlabelDemo extends JPanel { add(jlbLabel1);
JLabel jlbLabel1, jlbLabel2, jlbLabel3; add(jlbLabel2);
public JlabelDemo() { add(jlbLabel3);
ImageIcon icon = new ImageIcon("java- }
swing-tutorial.JPG", "My Website"); public static void main(String[] args) {
// Creating an Icon JFrame frame = new JFrame("jLabel Usage
setLayout(new GridLayout(3, 1)); Demo");
// 3 rows, 1 column Panel having Grid frame.setContentPane(new JlabelDemo());
Layout frame.pack();
jlbLabel1 = new JLabel("Image with Text", frame.setVisible(true);
icon, JLabel.CENTER); }
}

CU IDOL SELF LEARNING MATERIAL (SLM)


38 Advanced Internet Programming

2.14 JText
A text field is a basic text control that enables the user to type a small amount of text. When
the user indicates that text entry is complete (usually by pressing Enter), the text field fires an
action event. If you need to obtain more than one line of input from the user, use a text area.

Method or Constructor Purpose


JTextField()
Creates a text field. When present, theintargument specifies the
JTextField(String)
desired width in columns. TheStringargument contains the field's
JTextField(String, int)
initial text.
JTextField(int)
void setText(String)
String getText() Sets or obtains the text displayed by the text field.
(defined inJTextComponent)
The object of a TextField class is a text component that allows the editing of a single line text.
It inherits TextComponent class.

Swing TextField Class Declaration


public class TextField extends TextComponent

Example:
import java.awt.*; f.add(t1); f.add(t2);
import java.swing.*; f.setSize(400,400);
class TextFielddemo f.setLayout(null);
{ f.setVisible(true);
public static void main(String args[]) }
{ }
JFrame f= new JFrame("TextField Demo");
Output:
JTextField t1,t2;
t1=new JTextField("Welcome to cbs college.");
t1.setBounds(50,100, 200,30);
t2=new JTextField("core java ");
t2.setBounds(50,150, 200,30);

CU IDOL SELF LEARNING MATERIAL (SLM)


User Interface Components 39

2.15 JtextArea
The JTextArea class provides a component that displays multiple lines of text and optionally
allows the user to edit the text. If you need to obtain only one line of input from the user, you
should use atext field. If you want the text area to display its text using multiple fonts or other
styles, you should use an editor pane or text pane. If the displayed text has a limited length and is
never edited by the user, use a label.

Many of the Tutorial’s examples use uneditable text areas to display program output. Here is
a picture of an example called TextDemo that enables you to type text using a text field (at the top)
and then appends the typed text to a text area (underneath).

Method or Constructor Purpose


JTextArea() Creates a text area. When present,
JTextArea(String) theStringargument contains the initial text.
JTextArea(String, int, int) Theintarguments specify the desired width in
JTextArea(int, int) columns and height in rows, respectively.

void setText(String) Sets or obtains the text displayed by the text area.
String getText()
(defined inJTextComponent)

Example
import java.awt.Dimension; JTextArea text
import java.awt.FlowLayout; Areal=newJTextArea(text,5,10);

import javax.swing.JFrame; textAreal.setPreferredSize(newDimensio


n(100,100));
import javax.swing.JScrollPane;
JTextArea
import javax.swing.JTextArea; textArea2=newJTextArea(text,5,10);
public class JTextAreaTest { textArea2.setPreferredSize(newDimensi
public static void main(String[]args) { on(100,100));
JFrame frame=newJFrame("JTextAreaTest"); JScrollPane scroll
frame.setLayout(newFlowLayout()); Pane=newJScrollPane(textArea2,JScroll
Pane.VERTICAL_SCROLLBAR_ALWA
frame.setDefaultCloseOperation(JFrame.EXIT_ON_C
YS,
LOSE);
JScrollPane.HORIZONTAL_SCROLLBA
String R_ALWAYS);
text="AJTextAreaobjectrepresentsamultilineareafordis
textAreal.setLineWrap(true);
playingtext."
textArea2.setLineWrap(true);

CU IDOL SELF LEARNING MATERIAL (SLM)


40 Advanced Internet Programming

+"Youcanchangethenumberoflinesthatcanbedisplayed frame.add(textAreal);
atatime," frame.add(scrollPane);
+"aswellasthenumberofcolumns.Youcanwraplinesand frame.pack();
wordstoo."
frame.setVisible(true);
+"YoucanalsoputyourJTextAreainaJScrollPanetomakei
tscrollable."; }}

2.16 JCheckBox and JradioButton


A JCheckBox class provides the functionality of a Check box. Its immediate superclass is
JToggleButton which provides supportfor2statebuttons.

Constructor Purpose
JCheckBox(String) Create a JCheckBox instance. The string argument
JCheckBox(String,boolean) specifies the text, if any, that the check box should
display. Similarly, the Icon argument specifies the
JCheckBox(Icon)
image that should be used instead of the look and
JCheckBox(Icon,boolean) feel’s default checkbox image. Specifying the
JCheckBox(String,Icon) JCheckBox(String,Icon, Boolean argument as true initializes the check box to
boolean) be selected. If the Boolean argument is absent or
JCheckBox() false, then the checkbox is initially unselected

Methods
StringgetActionCommand() Returns the action command for this button.
StringgetText() Returns the button’s text.
booleanisSelected() Returns the state of the button.
voidsetEnabled(booleanb) Enables (or disables) the button.
voidsetSelected(booleanb) Sets the state of the button.
voidsetText(Stringtext) Sets the button’s text.

Example of checkBox:
import javax.swing.*; JCheckBox c4 =new JCheckBox("DBMS");
import java.io.*; p.add(c1);
import java.awt.*; p.add(c2);
class checkboxdemo p.add(c3);
{ p.add(c4);

CU IDOL SELF LEARNING MATERIAL (SLM)


User Interface Components 41

public static void main(String arg[]) f.add(p);


{ f.setSize(200,200);
JFrame f=new JFrame("frame window"); f.setVisible(true);
JPanel p=new JPanel(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CL
JLabel l=new JLabel("programming OSE);
languages"); }}
p.add(l);
Output:
JCheckBox c1 =new JCheckBox("SQL");
JCheckBox c2 =new
JCheckBox("ASP.NET");
JCheckBox c3 =new JCheckBox("LINUX");

This class represents swing RadioButtons. RadioButtons are a list of options out of which
anyone is selected at a time.
The RadioButton must be configured into a group such that only one of the buttons can be
selected at a time. For this we use the Button Group class.

Constructors
JRadioButton(Icon i) JRadioButton(String s, boolean state)
JRadioButton(Icon i, boolean state) JRadioButton( String s,Iconi)
JRadioButton(String s) JRadioButton( String s,Iconi, boolean state)

Example of RadioButton
import javax.swing.*; JRadioButton r4=new JRadioButton(" BMM");
import java.io.*; bg.add(r1);
import java.awt.*; bg.add(r2);
class radiobutton bg.add(r3);
{ bg.add(r4);
public static void main(String arg[]) p.add(r1);
{ p.add(r2);
JFrame f=new JFrame(" frame window"); p.add(r3);
JPanel p=new JPanel(); p.add(r4);
JLabel l=new JLabel("Courses:"); f.add(p);
JRadioButton r1=new JRadioButton(" f.setSize(300,300);
BSc(IT)"); f.setVisible(true);
JRadioButton r2=new JRadioButton(" f.setDefaultCloseOperation(JFrame.EXIT_ON_CLO
BMS"); SE);

CU IDOL SELF LEARNING MATERIAL (SLM)


42 Advanced Internet Programming

JRadioButton r3=new JRadioButton(" } }


BBI");
Output:
ButtonGroupbg=new ButtonGroup();

2.17 Jlist
This is a box like component that displays text-items in multiple rows. List items are usually
scrollable .

Constructors
JList()
JList(s) where ‘s ’is a string array.

Methods
getSelectedValue() To retrieve the selected item

setSelectedValue(object o, Boolean s) To set an item

In order to use the above methods we have to implement the ListSelectionListener.

Example
import javax.swing.*; JList l=new JList(s);
import java.io.*; p.add(l);
class listdemo f.add(p);
{ f.setSize(300,300);
public static void main(String arg[]) f.setVisible(true);
{ f.setDefaultCloseOperation(JFrame.EXIT_ON_CL
JFrame f=new JFrame("list demo"); OSE);

JPanel p=new JPanel(); }}

String s[]={"Dbms","Java","Linux","OS"};

Output

CU IDOL SELF LEARNING MATERIAL (SLM)


User Interface Components 43

2.18 JcomboBox
This class represents the combobox which is a pull down list with the capability of
displaying the selected item in a display area. The swing ComboBox is an enhancement of the
AWTcomponent call choice.

Constructors
JComboBox() void addItem(Object obj)
JcomboBox(vector v) where ‘obj’ is the object that is added to the
where ‘v’ is a vector.Items to the ComboBox ComboBox.

Example
import javax.swing.*; b.addItem(s3);
import java.io.*; b.addItem(s4);
class comboboxdemo p.add(l);
{ p.add(b);
public static void main(String arg[]) f.add(p);
{ f.setSize(200,200);
JFrame f=new JFrame(" frame window "); f.setVisible(true);
JPanel p=new JPanel(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOS
JLabel l=new JLabel("cities"); E);
String s1="Mumbai"; }
String s2="Nagpur"; Output
String s3="Pune";
String s4="Delhi";
JComboBox b=new JComboBox();
b.addItem(s1);
b.addItem(s2);

2.19 JMenu and JPopupMenu Class


JMenuBar
An implementation of a menu bar. You add JMenu objects to the menu bar to construct a
menu. When the user selects a JMenu object, its associated JPopup Menu is displayed, allowing
the user to select one of the JMenu Items on it.

CU IDOL SELF LEARNING MATERIAL (SLM)


44 Advanced Internet Programming

JMenu
A menu provides a space-saving way to let the user choose one of several options. Other
components with which the user can make a one-of-many choice include combo boxes, lists,
radio buttons, spinners, and tool bars. If any of your menu items performs an action that is
duplicated by another menu item or by a tool-bar button, then in addition to this section you
should read How to Use Actions.

Menus are unique in that, by convention, they aren’t placed with the other components in the
UI. Instead, a menu usually appears either in a menu bar or as a popup menu. A menu bar
contains one or more menus and has a customary, platform-dependent location — usually along
the top of a window. A popup menu is a menu that is invisible until the user makes a platform-
specific mouse action, such as pressing the right mouse button, over a popup-enabled component.
The popup menu then appears under the cursor.

Constructor or Method Purpose


JMenu() Creates a menu. The string specifies the text to display
JMenu(String) for the menu. TheActionspecifies the text and other
JMenu(Action) properties of the menu (seeHow to Use Actions).
Dsd
Method Description
JMenuadd(JMenu) Appends the specified menu to the end of the menu bar.
OverridesJComponent.addNotifyto register this menu bar
voidaddNotify() with the current keyboard manager.
dsd
Method Description
Gets the Accessible Context associated with this
AccessibleContextgetAccessibleContext() JMenuBar.
ComponentgetComponent() Implemented to be aMenu Element.

Popup Menu
A popup menu is a free-floating menu which associates with an underlying component. This
component is called the invoker. Most of the time, popup menu is linked to a specific component
to display context-sensitive choices.

In order to create a popup menu, you use the class JPopupMenu. You then can add menu
items JMenu Item to popup menu like normal menu. To display the popup menu, you call method
show(). Normally popup menu is called in response to a mouse event.

CU IDOL SELF LEARNING MATERIAL (SLM)


User Interface Components 45

Example:

import javax.swing.JButton; JMenuItem pasteMenuItem = new


import javax.swing.JFrame; JMenuItem("Paste");

import javax.swing.JMenuItem; pasteMenuItem.setEnabled(false);

import javax.swing.JPopupMenu; popupMenu.add(pasteMenuItem);

public class PopupMenuExample // Separator

{ popupMenu.addSeparator();

public static void main(final String args[]) { // Find

JFrame frame = new JFrame("Popup Menu JMenuItem findMenuItem = new


Example"); JMenuItem("Find");
frame.setDefaultCloseOperation(JFrame.EXIT_ON popupMenu.add(findMenuItem);
_CLOSE); JButton label = new JButton();
// Create popup menu, attach popup menu listener frame.add(label);
JPopupMenu popupMenu = new label.setComponentPopupMenu(popupMenu);
JPopupMenu("Title");
frame.setSize(350, 250);
// Cut
frame.setVisible(true);
JMenuItem cutMenuItem = new JMenuItem("Cut");
}}
popupMenu.add(cutMenuItem);
// Copy
Output:
JMenuItem copyMenuItem = new
JMenuItem("Copy");
popupMenu.add(copyMenuItem);
// Paste

2.20 JMenuItem and JCheckBoxMenuItem


JMenuItem
An implementation of an item in a menu. A menu item is essentially a button sitting in a list.
When the user selects the “button”, the action associated with the menu item is performed. A
JMenuItem contained in a JPopupMenu performs exactly that function.

Menu Items are added using JMenuItem.

CU IDOL SELF LEARNING MATERIAL (SLM)


46 Advanced Internet Programming

Constructors
JMenu() JMenu(String label,boolean off)
JMenu(String label) JMenuItem(String s)
where s represents name of menu item.

Example
import java.awt.*; submenu.add(m5);
class AWTMenu extends Frame menu1.add(submenu);
{ mbar.add(menu1);
MenuBar mbar; menu2=new Menu("Edit");
Menu menu1,submenu,menu2,menu3; m6=new MenuItem("Undo");
MenuItem m7=new MenuItem("Redo");
m1,m2,m3,m4,m5,m6,m7,m8,m9;
menu2.add(m6);
public AWTMenu()
menu2.add(m7);
{
mbar.add(menu2);
setTitle("AWT Menu");
menu3=new Menu("Help");
setSize(400,400);
m8=new MenuItem("About Us");
setLayout(new FlowLayout());
menu3.add(m8);
setVisible(true);
mbar.add(menu3);
setLocationRelativeTo(null);
setMenuBar(mbar);
mbar=new MenuBar();
menu1=new Menu("File"); }

submenu=new Menu("Color"); public static void main(String args[])

m1=new MenuItem("New"); {

m2=new MenuItem("Save clt+s" ); new AWTMenu();

m3=new MenuItem("Save as"); }}

m4=new MenuItem("Red"); Output


m5=new MenuItem("Blue");
m9=new MenuItem("Exit");
menu1.add(m1);
menu1.add(m2);
menu1.add(m3);
menu1.add(m9);
submenu.add(m4);

CU IDOL SELF LEARNING MATERIAL (SLM)


User Interface Components 47

JCheckBox-MenuItem
A menu item that can be selected or deselected. If selected, the menu item typically appears
with a checkmark next to it. If unselected or deselected, the menu item appears without a
checkmark. Like a regular menu item, a check box menu item can have either text or a graphic
icon associated with it, or both.

Eitheris Selected set Selected or get State/set State can be used to determine/specify the
menu item’s selection state. The preferred methods are is Selected and set Selected, which work
for all menus and buttons. The get State and setState methods exist for compatibility with other
component sets.

For further information and examples of using check box menu items, see How to Use
Menus, a section in The Java Tutorial. For the keyboard keys used by this component in the
standard Look and Feel (L&F) renditions, see the JCheckBox MenuItem key assignments

Constructor Description
JCheckBoxMenuItem() Creates an initially unselected check box menu item with no set text
or icon.
JCheckBoxMenuItem(Action) Creates a menu item whose properties are taken from the Action
supplied.
JCheckBoxMenuItem(Icon) Creates an initially unselected check box menu item with an icon.
JCheckBoxMenuItem(String) Creates an initially unselected check box menu item with text.
Ds
Method Description

AccessibleContextgetAccessibleCon Get the Accessible Context associated with this JComponent


text()
Returns an array (length 1) containing the check box menu
Object[]getSelectedObjects() item label or null if the check box is not selected.
booleangetState() Returns the selected-state of the item.
String paramString() Returns a string representation of this JCheckBoxMenuItem.

2.21 JRadioButtonMenuItem
An implementation of a radiobutton menu item. AJRadioButton Menu Item is a menu item
that is part of a group of menu items in which only one item in the group can be selected. The
selected item displays its selected state. Selecting it causes any other selected item to switch to the

CU IDOL SELF LEARNING MATERIAL (SLM)


48 Advanced Internet Programming

unselected state. To control the selected state of a group of radio button menu items, use a Button
Group object.

For further documentation and examples see How to Use Menus, a section in The Java
Tutorial. For the keyboard keys used by this component in the standard Look and Feel (L&F)
renditions, see the JRadioButton MenuItemkey assignments.

Constructor Description
JRadioButtonMenuItem() Creates aJRadioButton Menu Itemwith no set text or icon.
JRadioButtonMenuItem(Action) Creates a radio button menu item whose properties are taken
from theAction supplied.
JRadioButtonMenuItem(Icon) Creates aJRadioButton Menu Itemwith an icon.
JRadioButtonMenuItem(Icon,boolean) Creates a radio button menu item with the specified image
and selection state, but no text.
Ds
Method Description
AccessibleContextgetAccessibleConte Returns theAccessible Context associated with this
xt() JRadioButton Menu Item.
StringgetUIClassID() Returns the name of the L&F class that renders this
component.
StringparamString() Returns a string representation of this JRadioButton Menu
Item.
voidrequestFocus() OverridesComponent. requestFocusto not grab focus.

2.22 JScrollBar
Scroll bars are used to select continuous values between a specified minimum and maximum.
Scroll bars may be oriented horizontally or vertically. A scroll bar is actually a composite of
several individual parts. Each end has an arrow that you can click to move the current value of the
scroll bar one unit in the direction of the arrow. The current value of the scroll bar relative to its
minimum and maximum values is indicated by the slider box (or thumb) for the scroll bar. The
slider box can be dragged by the user to a new position. The scroll bar will then reflect this value.
In the background space on either side of the thumb, the user can click to cause the thumb to jump
in that direction by some increment larger than 1. This action translates into some form of page up
and page down. Scroll bars are encapsulated by the Scrollbar class.

Scrollbar defines the following constructors:

CU IDOL SELF LEARNING MATERIAL (SLM)


User Interface Components 49

1. Scrollbar( )
2. Scrollbar(int style)
3. Scrollbar(int style, int initial Value, int thumb Size, int min, int max)
The first form creates a vertical scroll bar.

The second and third forms allow you to specify the orientation of the scroll bar. If style is
Scrollbar. VERTICAL, a vertical scroll bar is created. If style is Scrollbar. HORIZONTAL, the
scroll bar is horizontal.

In the third form of the constructor, the initial value of the scroll bar is passed in initial Value.
The number of units represented by the height of the thumb is passed in thumb Size. The
minimum and maximum values for the scroll bar are specified by min and max.

If you construct a scroll bar by using one of the first two constructors, then you need to set its
parameters by using set Values( ), shown here, before it can be used:

void setValues(int initialValue, int thumbSize, int min, int max)

The parameters have the same meaning as they have in the third constructor just described.

To obtain the current value of the scroll bar, call getValue( ). It returns the current setting. To
set the current value, call setValue( ).

These methods are as follows:

1. int getValue( )
2. void setValue(intnewValue)
Here, new Value specifies the new value for the scroll bar. When you set a value, the slider
box inside the scroll bar will be positioned to reflect the new value.

You can also retrieve the minimum and maximum values via getMinimum( ) and
getMaximum( ), shown here:

1. int getMinimum( )
2. int getMaximum( )
They return the requested quantity.

By default, 1 is the increment added to or subtracted from the scroll bar each time it is
scrolled up or down one line. You can change this increment by calling set UnitIncrement( ). By

CU IDOL SELF LEARNING MATERIAL (SLM)


50 Advanced Internet Programming

default, page-up and page-down increments are 10. You can change this value by calling set
BlockIncrement( ).

These methods are shown here:

1. void setUnitIncrement(intnewIncr)
2. void setBlockIncrement(intnewIncr)

Handling Scroll Bars


To process scroll bar events, you need to implement the Adjustment Listener interface. Each
time a user interacts with a scroll bar, an Adjustment Event object is generated. Its
getAdjustmentType( ) method can be used to determine the type of the adjustment.

2.23 Dialogs (Message, Confirmation, Input)


The JOptionPane class is used to provide standard dialog boxes such as message dialog box,
confirm dialog box and input dialog box. These dialog boxes are used to display information or
get input from the user. The JOptionPane class inherits JComponent class.

Common Constructors of JOptionPane class


JOptionPane() :- It is used to create a JOptionPane with a test message.
JOptionPane(Object message) :- It is used to create an instance of JOptionPane to display a message.
JOptionPane(Object message, int messageType) :- It is used to create an instance of JOptionPane to
display a message with specified message type and default options.

Common Methods of JOptionPane class


JDialog createDialog(String title): It is used to create and return a new parentless JDialog
with the specified title.

static void show MessageDialog(Component parentComponent, Object message): It is used


to create an information-message dialog titled “Message”.

static void showMessageDialog(Component parentComponent, Object message, String title,


int messageType) :- It is used to create a message dialog with given title and message Type.

static int showConfirmDialog(Component parentComponent, Object message): It is used to


create a dialog with the options Yes, No and Cancel; with the title, Select an Option.

static String showInputDialog(Component parentComponent, Object message): It is used to


show a question-message dialog requesting input from the user parented to parentComponent.

CU IDOL SELF LEARNING MATERIAL (SLM)


User Interface Components 51

void setInputValue(Object newValue): It is used to set the input value that was selected or
input by the user.

1. Where Component: The first parameter is a component which determines the Frame in
which the dialog is displayed; if null, or if the parentComponent has no Frame, a default
Frame is used.
2. Object: The second parameter can be any objects.(In some older versions of Java you
might get a compiler error when using primitive types directly).
3. String: The third parameter is a String placed as the title of the message dialog window.
4. Int: The int that follows the String is the Message Type. The different Message Types
for JOptionPane, are:
 ERROR_MESSAGE  INFORMATION_MESSAGE
 WARNING_MESSAGE  QUESTION_MESSAGE
 PLAIN_MESSAGE
5. Icon: The last parameter is an Icon that is displayed inside the dialog and overrides the
default MessageType icon.

Java JOptionPane Example: showMessageDialog()


import javax.swing.JOptionPane;
Output:
public class SimpleDialog1 {
public static void main(String[] args){
JOptionPane.showMessageDialog(null,
"Simple Information Message");
}
}

Java JOptionPane Example:


showMessageDialog()
import javax.swing.*; pdated.","Alert",JOptionPane.WARNING_M
public class OptionPaneExample { ESSAGE);

JFrame f; }

OptionPaneExample() { publicstaticvoidmain(String[]args) {

f=newJFrame(); newOptionPaneExample();

JOptionPane.showMessageDialog(f,"SuccessfullyU } }

CU IDOL SELF LEARNING MATERIAL (SLM)


52 Advanced Internet Programming

Output:

Java JOptionPane Example:


showInputDialog()
import javax.swing.*; publicstaticvoidmain(String[]args){
public class OptionPaneExample{ newOptionPaneExample();
JFrame f; } }
OptionPaneExample() {
Output:
f=newJFrame();
Stringname=JOptionPane.showInputDialog(f,"EnterNa
me");
}

Java JOptionPane Example:


showConfirmDialog()
import javax.swing.*; f.setVisible(true);
import java.awt.event.*; }
public class OptionPaneExample extends public void windowClosing(WindowEvent e)
WindowAdapter { {
JFrame f; int
OptionPaneExample() { a=JOptionPane.showConfirmDialog(f,"Arey
ousure?");
f=newJFrame();
if(a==JOptionPane.YES_OPTION){
f.addWindowListener(this);
f.setDefaultCloseOperation(JFrame.EXIT_
f.setSize(300,300);
ON_CLOSE);
f.setLayout(null);
} }
f.setDefaultCloseOperation(JFrame.DO_NOTHING
public static void main(String[]args) {
_ON_CLOSE);
new OptionPaneExample();
} }

CU IDOL SELF LEARNING MATERIAL (SLM)


User Interface Components 53

Output:

2.24 JFileChooser
A JFileChooser is a dialog to select a file or files.

The return value of the three methods is one of the following:

JFileChooser.CANCEL_OPTION, if the user clicks Cancel.

JFileChooser.APPROVE_OPTION, if the user click an OK/Open/Save button.

JFileChooser.ERROR_OPTION, if the user closes the dialog

JFileChooser has supporting classes: FileFilter class, FileSystemView class, FileView.

FileFilter class is for restricting files and directories to be listed in the FileView of the
JFileChooser. The FileView controls how the directories and files are listed within the
JFileChooser. The FileSystemView is an abstract class that tries to hide file system-related
operating system specifics from the file chooser.

Example:
import javax.swing.JFileChooser; this.getContentPane().add(fileChooser);
import javax.swing.JFrame; fileChooser.setVisible(true);
public class filechooser extends JFrame }
{ public static void main(String[] args)
public filechooser() {
{ JFrame frame = new filechooser();
JFileChooser fileChooser = new Jframe.setDefaultCloseOperation(JFrame.EXIT_ON_
JFileChooser(); CLOSE);
fileChooser.setDialogTitle("Choose a frame.pack();
file");
frame.setVisible(true);
}}

CU IDOL SELF LEARNING MATERIAL (SLM)


54 Advanced Internet Programming

Output:

2.25 JColorChooser
The JColorChooser class is used to create a color chooser dialog box so that user can select
any color.

Constructors
JColorChooser(): is used to create a color chooser pane with white color initially.

JColorChooser(Color initialColor): is used to create a color chooser pane with the specified
color initially.

Methods
public static Color showDialog(Component c, String title, Color initialColor): is used to
show the color-chooser dialog box.

Example:
import java.awt.event.*; public static void main(String[] args) {
import java.awt.*; JColorChooserdemo ch=new
import javax.swing.*; JColorChooserdemo();

public class JColorChooserdemo extends ch.setSize(400,400);


JFrame implements ActionListener{ ch.setVisible(true);
JButton b; ch.setDefaultCloseOperation(EXIT_ON_CLOSE);
Container c; }}

CU IDOL SELF LEARNING MATERIAL (SLM)


User Interface Components 55

JColorChooserdemo(){
Output:
c=getContentPane();
c.setLayout(new FlowLayout());
b=new JButton("Colordemo");
b.addActionListener(this);
c.add(b); }
public void actionPerformed(ActionEvent e) {
Color initialcolor=Color.RED;
Color
color=JColorChooser.showDialog(this,"Select
a color",initialcolor);
c.setBackground(color);
}

2.26 Practical Assignment


1. Develop a swing application to accept empno, name and salary details.
2. Develop a swing application to display BIO-DATA.

2.27 Summary
A component is an independent visual control. Swing Framework contains a large set
of components which provide rich functionalities and allow high level of customization.
They all are derived from JComponent class. All these components are lightweight
components. This class provides some common functionality like pluggable look and feel,
support for accessibility, drag and drop, layout, etc.
A container holds a group of components. It provides a space where a component can be
managed and displayed. Containers are of two types:

1. Top level Containers


 It inherits Component and Container of AWT.
 It cannot be contained within other containers.
 Heavyweight.
 Example: JFrame, JDialog, JApplet

CU IDOL SELF LEARNING MATERIAL (SLM)


56 Advanced Internet Programming

2. Lightweight Containers
 It inherits JComponent class.
 It is a general purpose container.
 It can be used to organize related components together.
 Example: JPanel

2.28 Key Words/Abbreviations


 Event: An event in Java is an object that is created when something changes within a
graphical user interface.
 Listener: Listeners. A user interface listener is a method which is called when the user
does something (eg, click a button) that the programmer has indicated they want to be
notified of

2.29 Learning Activity


1. what is JFC?
-----------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------
2. Differentiate between AWT and SWING.
-----------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------

2.30 Unit End Questions (MCQs and Descriptive)

A. Descriptive Types Questions


1 Explain MVC Architecture
2. List and explain different Layout Manager
3. Write note on SWING
4. Write Difference between AWT and Swing
5. Explain SWING FEATURES
6 Explain JButton with suitable example
7. Explain JLabel with suitable example

CU IDOL SELF LEARNING MATERIAL (SLM)


User Interface Components 57

8. Explain JText with suitable example


9. Explain JTextArea with suitable example
10. Explain JcheckBox with suitable example
11. Explain JradioButton with suitable example
12. Explain Jlist with suitable example
13. Explain JcomboBox with suitable example
14. Explain JMenuItem with suitable example
15. Explain JMenu with suitable example
16. Explain JPopupMenu with suitable example
17. Explain JCheckBoxMenuItem with suitable example
18. Explain JRadioButtonMenuItem with suitable example
19. Explain JscrollBar with suitable example
20. Explain different Dialogs boxes with suitable example
21. Explain JFileChooser with suitable example
22. Explain JcolorChooser with suitable example

B. Multiple Choice/Objective Type Questions


1. Public void pack() is use to __________ frame.
(a) resize (b) display
(c) pack (d) position
2. The GridLayout Breaks the GUI up into __________ and __________.
(a) Rows and Columns (b) Rows and Data
(c) Columns and Data (d) Horizontal and vertical gaps
3. swing Componnets are also known as __________.
(a) Light Weight (b) Heavy Weight
(c) Medium Weight (d) Good Weight
4. JFrame Class has __________ Methods.
(a) 3 (b) 2
(c) 5 (d) 7

CU IDOL SELF LEARNING MATERIAL (SLM)


58 Advanced Internet Programming

5. Swing Classes supports __________.


(a) JComponet (b) AWT Componet
(c) AWT tool (d) Frame

Answers
1. (d), 2. (a), 3. (a), 4. (b), 5. (a)

2.31 References
1. https://www.startertutorials.com/corejava/introduction-to-swing.html
2. https://www.javatpoint.com/java-swing
3. Dave Wood, Marc Loy, and Robert Eckstein, “Java Swing”.

CU IDOL SELF LEARNING MATERIAL (SLM)


UNIT 3 EVENT HANDLING

Structure:
3.0 Learning Objectives

3.1 Introduction

3.2 Event Delegation Model

3.3 Events

3.4 AWT Event

3.5 Event Listener Interfaces

3.6 Event Handling in Java with mouse and keyboard

3.7 Different Types of Event in Java AWT

3.8 Adapter Classes

3.9 Swing Components

3.10 Container class


3.11 Practical Assignment
3.12 Summary

3.13 Key Words/Abbreviations

3.14 Learning Activity

3.15 Unit End Questions (MCQs and Descriptive)

3.16 References

CU IDOL SELF LEARNING MATERIAL (SLM)


60 Advanced Internet Programming

3.0 Learning Objectives


After studying this unit, you will be able to:

 Define sources, listeners


 Discuss mouse and keyboard event handling
 Describe adapters, swing and container class

3.1 Introduction
Event: Change in the state of an object is known as event i.e. event describes the change in
state of source. Events are generated as result of user interaction with the graphical user interface
components. For example, clicking on a button, moving the mouse, entering a character through
keyboard, selecting an item from list, scrolling the page are the activities that causes an event to
happen.

Event Handling is the mechanism that controls the event and decides what should happen if
an event occurs. This mechanism have the code which is known as event handler that is executed
when an event occurs. Java Uses the Delegation Event Model to handle the events.

3.2 Event Delegation Model


The Delegation Event Model

The modern approach to handling events is based on the delegation event model, which
defines standard and consistent mechanisms to generate and process events.

Its concept is quite simple:

1. Source generates an event and sends it to one or more listeners.


2. The listener simply waits until it receives an event. Once received, the listener processes
the event and then returns.
3. The advantage of this design is that the application logic that processes events is cleanly
separated from the user interface logic that generates those events.
4. A user interface element is able to delegate the processing of an event to a separate piece
of code.
5. In the delegation event model, listeners must register with a source in order to receive an
event notification.

CU IDOL SELF LEARNING MATERIAL (SLM)


Event Handling 61

6. This provides an important benefit: notifications are sent only to listeners that want to
receive them.

Event Manger
AddListener();
removeListener(); Event Objects
//called when event generated
fireEvent();

The methods
addlistener() and
remove Listener()
has to be used to
Event Listeners register and be
register to the event

All the listeners will


be registering to a
Event through the Event Source
Event Manager
ActionPerformed(){
................
................. Event Source is
responsible for
..................
} generating the
This method will be called by events
the event manager, when the
event will get generated. The
API user has to implement this
method in the listener class

Fig. 3.1: Event Delegation Model

Events
In the delegation model, an event is an object that describes a state change in a source. It can
be generated as a consequence of a person interacting with the elements in a graphical user
interface. Some of the activities that cause events to be generated are pressing a button, entering a
character via the keyboard, selecting an item in a list, and clicking the mouse. Many other user
operations could also be cited as examples. Events may also occur that are not directly caused by
interactions with a user interface.

3.1.1 Event Sources


A source is an object that generates an event. This occurs when the internal state of that
object changes in some way. Sources may generate more than one type of event. A source must
register listeners in order for the listeners to receive notifications about a specific type of event.
Each type of event has its own registration method. Here is the general form:

CU IDOL SELF LEARNING MATERIAL (SLM)


62 Advanced Internet Programming

public void addTypeListener(Type Listener el)

Type is the name of the event and el is a reference to the event listener. The method that
registers a keyboard event listener is called addKeyListener(). The method that registers a mouse
motion listener is called addMouseMotionListener( ).

When an event occurs, all registered listeners are notified and receive a copy of the event
object know as multicasting the event In all cases, notifications are sent only to listeners that
register to receive them. Some sources may allow only one listener to register.

General Form:
public void addTypeListener(TypeListener el) throws java.util.

TooManyListenersException Type is the name of the event and el is a reference to the event
listener. When such an event occurs, the registered listener is notified. This is known as uni
casting the event. A source must also provide a method that allows a listener to unregister an
interest in a specific type of event.

The general form of such a method is this:

public void removeTypeListener(TypeListener el)

3.1.2 Event Listeners


A listener is an object that is notified when an event occurs. It has two major requirements.
First, it must have been registered with one or more sources to receive notifications about specific
types of events. Second, it must implement methods to receive and process these notifications.
The methods that receive and process events are defined in a set of interfaces found in
java.awt.event.

For example, the MouseMotionListener interface defines two methods to receive


notifications when the mouse is dragged or moved. Any object may receive and process one or
both of these events if it provides an implementation of this interface.

Event Classes
The Event classes represent the event. Java provides us various Event classes but we will
discuss those which are more frequently used.

It is the root class from which all event state objects shall be derived. All Events are
constructed with a reference to the object, the source, that is logically deemed to be the object
upon which the Event in question initially occurred upon.This class is defined in java.util package.

CU IDOL SELF LEARNING MATERIAL (SLM)


Event Handling 63

Event Object(Object src) Here, src is the object that generates this event. Event Object
contains two methods: getSource( ) and toString( ). The getSource( ) method returns the source of
the event. Its general form is shown here: Object getSource( )

3.3 Events
Events are the integral part of the java platform. You can see the concepts related to the event
handling through the example and use methods through which you can implement the event
driven application.

For any event to occur, the objects registers themselves as listeners. No event takes place if
there is no listener i.e., nothing happens when an event takes place if there is no listener. No
matter how many listeners there are, each and every listener is capable of processing an event.

ActionListener can be implemented by any Class including Applet. One point to remember
here is that all the listeners are always notified. Moreover, you can also call AWTEvent.consume()
method whenever you don’t want an event to be processed further. There is another method
which is used by a listener to check for the consumption. The method is isConsumed( ) method.
The processing of the events gets stopped with the consumption of the events by the system once
a listener is notified. Consumption only works for InputEvent and its subclasses. Moreover, if you
don’t want any input from the user through keyboard then you can useconsume( ) method for the
KeyEvent.

The step by step procedure of Event handling is as follow:

1. When anything interesting happens then the subclasses of AWTEvent are generated by
the component.
2. Any class can act like a Listener class permitted by the Event sources. For example,
addActionListener() method is used for any action to be performed, where Action is the
event type. There is another method by which you can remove the listener class which is
removeXXXListener() method, where XXX is the event type.
3. A listener type has to be implemented for an event handling such as ActionListener.
4. There are some special type of listener types as well for which you need to implement
multiple methods like key Events. There are three methods which are required to be
implemented for Key events and to register them i.e., one for key release, key typed and
one for key press. There are some special classes as well which are known as adapters
that are used to implement the listener interfaces and stub out all the methods.

CU IDOL SELF LEARNING MATERIAL (SLM)


64 Advanced Internet Programming

3.4 AWT Event


Most of the times every event-type has Listener interface as Events subclass the AWTEvent
class. However, PaintEvent and InputEvent don’t have the Listener interface because only the
paint() method can be overriden with PaintEvent etc.

Low-level Events
A low-level input or window operation is represented by the Low-level events. Types of
Low-level events are mouse movement, window opening, a key press etc. For example, three
events are generated by typing the letter ‘A’ on the Keyboard one for releasing, one for pressing,
and one for typing. The different type of low-level events and operations that generate each event
are show below in the form of a table.
Table 3.1: Different Type of Low-level Events
FocusEvent Used for Getting/losing focus.
MouseEvent Used for entering, exiting, clicking, dragging, moving, pressing, or releasing.
ContainerEvent Used for Adding/removing component.
KeyEvent Used for releasing, pressing, or typing (both) a key.
WindowEvent Used for opening, deactivating, closing, Iconifying, deiconifying, really closed.
ComponentEvent Used for moving, resizing, hiding, showing.

Semantic Events
The interaction with GUI component is represented by the Semantic events like changing the
text of a text field, selecting a button etc. The different events generated by different components
is shown below.
Table 3.2: The Different Events Generated by Different Components
ItemEvent Used for state changed.
ActionEvent Used for do the command.
TextEvent Used for text changed.
AdjustmentEvent Used for value adjusted.

Event Sources
If a component is an event source for something then the same happens with its subclasses.
The different event sources are represented by the following table.

CU IDOL SELF LEARNING MATERIAL (SLM)


Event Handling 65

Table 3.3: Low-level Events


Window WindowListener
Container ContainerListener
ComponentListener, FocusListener, KeyListener
Component
MouseListener, MouseMotionListener
Table 3.4: Semantic Events
Scrollbar AdjustmentListener

TextArea, TextField TextListener

Button, List, MenuItem, TextField ActionListener


Choice, Checkbox, Checkbox, CheckboxMenuItem List ItemListener

3.5 Event Listeners


Every listener interface has at least one event type. Moreover, it also contains a method for
each type of event the event class incorporates. For example as discussed earlier, the KeyListener
has three methods, one for each type of event that the KeyEvent has: keyTyped(), keyPressed(),
and keyReleased().

The Listener interfaces and their methods are as follow:


Table 3.5: The Listener Interfaces and their Methods
Interface Methods
windowActivated(WindowEvent e)
windowDeiconified(WindowEvent e)
windowOpened(WindowEvent e)
WindowListener windowClosed(WindowEvent e)
windowClosing(WindowEvent e)
windowIconified(WindowEvent e)
windowDeactivated(WindowEvent e)
ActionListener actionPerformed(ActionEvent e)
AdjustmentListener adjustmentValueChanged(AdjustmentEvent e)
MouseListener mouseClicked(MouseEvent e)

CU IDOL SELF LEARNING MATERIAL (SLM)


66 Advanced Internet Programming

mouseEntered(MouseEvent e)
mouseExited(MouseEvent e)
mousePressed(MouseEvent e)
mouseReleased(MouseEvent e)
focusGained(FocusEvent e)
FocusListener
focusLost(FocusEvent e)
ItemListener itemStateChanged(ItemEvent e)
KeyListener keyReleased(KeyEvent e)
keyTyped(KeyEvent e)
keyPressed(KeyEvent e)
componentHidden(ComponentEvent e)
componentMoved(ComponentEvent e)
ComponentListener
componentShown(ComponentEvent e)
componentResized(ComponentEvent e)

mouseMoved(MouseEvent e)
MouseMotionListener
mouseDragged(MouseEvent e)
TextListener textValueChanged(TextEvent e)
ContainerListener componentAdded(ContainerEvent e)
componentRemoved(ContainerEvent e)

3.6 Event Handling In Java with Mouse and Keyboard


In this section you will learn about how to handle events in Java. Events in any programming
language specifies the external effects that happens and your application behaves according to
that event. For example, an application produce an output when a user inputs some data, or the
data received from the network or it may be something else. In Java when you works with the
AWT components like button, textbox, etc. (except panel, label) generates an event. This event is
handled by the listener. Event listener listens the event generated on components and performs the
corresponding action.
In Java event handling may comprised the following four classes:

CU IDOL SELF LEARNING MATERIAL (SLM)


Event Handling 67

1. Event Sources: Sources for generating an event may be the components. In Java
java.awt.Component specifies the components that may or may not generate events.
These components classes are the subclass of the above class. These event sources may
be the button, combobox, textbox etc.
2. Event Classes: Event Classes in Java are the classes defined for almost all the
components that may generate events. These events classes are named by giving the
specific name such as for the component source button the event class is ActionEvent.
Following are the list of Event Classes:
 ActionEvent: Button, TextField, List, Menu
 WindowEvent: Frame
 ItemEvent: Checkbox, List
 AdjustmentEvent: Scrollbar
 MouseEvent: Mouse
 KeyEvent: Keyboard
3. Event Listeners: Event Listeners are the Java interfaces that provides various methods
to use in the implemented class. Listeners listens the event generated by a component. In
Java almost all components has its own listener that handles the event generated by the
component. For example, there is a Listener named ActionListener handles the events
generated from button, textfield, list, menus.
4. Event Adapters: Event Adapters classes are abstract class that provides some methods
used for avoiding the heavy coding. Adapter class is defined for the listener that has
more than one abstract methods.
5. Here I am giving a simple example which will demonstrate you about how to handle an
event. In this example we will give a simple example into which you will see how an
event generated after clicking on the button is handled. To handle the event you would
have to implement a corresponding listener and add the listener on the component i.e.
button. Then you have to override the method declared in the listener.
You can add the listener by following ways:

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

CU IDOL SELF LEARNING MATERIAL (SLM)


68 Advanced Internet Programming

b = (JButton)ae.getSource();
sayHi();
}
});

In the second way you can add listener as follows:

b.addActionListener(this)
publi void actionPerformed(ActionEvent ae){
b = (JButton)ae.getSource();
sayHi();
}

3.7 Different Types of Event in Java AWT


Introduction
There are many types of events that are generated by your AWT Application. These events
are used to make the application more effective and efficient. Generally, there are twelve types of
event are used in Java AWT:

1. ActionEvent: This is the ActionEvent class extends from the AWTEvent class. It
indicates the component-defined events occurred i.e., the event generated by the
component like Button, Checkboxes etc. The generated event is passed to every
EventListener objects that receives such types of events using the addActionListener()
method of the object.
2. AdjustmentEvent: This is the AdjustmentEvent class extends from the AWTEvent class.
When the Adjustable Value is changed then the event is generated.
3. ComponentEvent: ComponentEvent class also extends from the AWTEvent class. This
class creates the low-level event which indicates if the object moved, changed and it’s
states (visibility of the object). This class only performs the notification about the state of
the object. The ComponentEvent class performs like root class for other component-level
events.
4. ContainerEvent: The ContainerEvent class extends from the ComponentEvent class.
This is a low-level event which is generated when container’s contents changes because
of addition or removal of a components.

CU IDOL SELF LEARNING MATERIAL (SLM)


Event Handling 69

5. FocusEvent: The FocusEvent class also extends from the ComponentEvent class. This
class indicates about the focus where the focus has gained or lost by the object. The
generated event is passed to every objects that is registered to receive such type of events
using the addFocusListener() method of the object.
6. InputEvent: The InputEvent class also extends from the ComponentEvent class. This
event class handles all the component-level input events. This class acts as a root class
for all component-level input events.
7. ItemEvent: The ItemEvent class extends from the AWTEvent class. The ItemEvent
class handles all the indication about the selection of the object i.e. whether selected or
not. The generated event is passed to every ItemListener objects that is registered to
receive such types of event using the addItemListener() method of the object.
8. KeyEvent: KeyEvent class extends from the InputEvent class. The KeyEvent class
handles all the indication related to the key operation in the application if you press any
key for any purposes of the object then the generated event gives the information about
the pressed key. This type of events check whether the pressed key left key or right key,
‘A’ or ‘a’ etc.
9. MouseEvent: MouseEvent class also extends from the InputEvent class. The
MouseEvent class handle all events generated during the mouse operation for the object.
That contains the information whether mouse is clicked or not if clicked then checks the
pressed key is left or right.
10. PaintEvent: PaintEvent class also extends from the ComponentEvent class. The
PaintEvent class only ensures that the paint() or update() are serialized along with the
other events delivered from the event queue.
11. TextEvent: TextEvent class extends from the AWTEvent class. TextEvent is generated
when the text of the object is changed. The generated events are passed to every
TextListener object which is registered to receive such type of events using the
addTextListener() method of the object.
12. WindowEvent: WindowEvent class extends from the ComponentEvent class. If the
window or the frame of your application is changed (Opened, closed, activated,
deactivated or any other events are generated), WindowEvent is generated.

CU IDOL SELF LEARNING MATERIAL (SLM)


70 Advanced Internet Programming

3.8 Adapter Classes


An adapter class provides the default implementation of all methods in an event listener
interface. Adapter classes are very useful when you want to process only few of the events that
are handled by a particular event listener interface. You can define a new class by extending one
of the adapter classes and implement only those events which is relevant.

There are some event listeners that have multiple methods to implement. That is some of the
listener interfaces contain more than one method. For instance, the MouseListener interface
contains five methods such as mouse Clicked, mouse Pressed, mouse Released etc. If you want to
use only one method out of these then also you will have to implement all of them. Thus, the
methods which you do not want to care about can have empty bodies. To avoid such thing, we
have adapter class.

Adapter classes help us in avoiding the implementation of the empty method bodies.
Generally an adapter class is there for each listener interface having more than one method. For
instance, the Mouse Adapter class implements the MouseListener interface. An adapter class can
be used by creating a subclass of it and then overriding the methods which are of use only. Hence
avoiding the implementation of all the methods of the listener interface. The following example
shows the implementation of a listener interface directly.

Example of MouseAdapter
import java.awt.*; f.setVisible(true);
import java.awt.event.*; }
public class MouseAdapterExample extends public void mouseClicked(MouseEvent e) {
MouseAdapter { Graphics g=f.getGraphics();
Frame f; g.setColor(Color.BLUE);
MouseAdapterExample(){ g.fillOval(e.getX(),e.getY(),30,30);
f=new Frame("Mouse Adapter"); }
f.addMouseListener(this); public static void main(String[] args) {
f.setSize(300,300); new MouseAdapterExample();
f.setLayout(null); } }

CU IDOL SELF LEARNING MATERIAL (SLM)


Event Handling 71

3.9 Swing Components


Swing Framework contains a large set of components which provide rich functionalities and
allow high level of customization. All these components are lightweight components. They all are
derived from JComponent class. It supports the pluggable look and feel.

Swing Components Example with Event Handling:


Buttton with ActionListener:
import java.awt.*; tf.setText("Welcome to cbs college");
import java.awt.event.*; }
import java.swing.*; });
public class Buttondemo { f.add(b);f.add(tf);
public static void main(String[] args) { f.setSize(400,400);
JFrame f=new JFrame("Button Example"); f.setLayout(null);
final JTextField tf=new JTextField(); f.setVisible(true);
tf.setBounds(50,50, 150,20); }}
JButton b=new JButton("Click Here"); Output:
b.setBounds(50,100,60,30);
b.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{

3.10 Container Class


When you create an application, initially you should have a base container and you have to
add the required components like buttons and text fields in the container.

And when you click or perform any operation on any fields, the event will occur and your
code should listen to the events and also handle the event.

Swing Container
A container is a root element for an Application. All the other components are added to that
root and it forms a hierarchy.

There are three container classes:


 JFrame  JDialog  JApplet

CU IDOL SELF LEARNING MATERIAL (SLM)


72 Advanced Internet Programming

Example of JFrame:
import java.awt.FlowLayout; panel.add(button);
import javax.swing.JButton; frame.add(panel);
import javax.swing.JFrame; frame.setSize(200, 300);
import javax.swing.JLabel; frame.setLocationRelativeTo(null);
import javax.swing.Jpanel; frame.setDefaultCloseOperation(JFrame.EXIT_ON
public class JFrameExample { _CLOSE); frame.setVisible(true);

public static void main(String s[ ]) { }

JFrame frame = new JFrame("JFrame Exam }


ple"); JPanel panel = new JPanel();
Output:
panel.setLayout(new FlowLayout());
JLabel label = new JLabel("JFrame By Exam
ple"); JButton button = new JButton();
button.setText("Button");
panel.add(label);

Example of JDialog:
// java Program to create a simple JDialog f.add(p);
import java.awt.event.*; f.setSize(400, 400);
import java.awt.*; f.show(); }
import javax.swing.*; public void actionPerformed(ActionEvent
class solve extends JFrame implements e) {
ActionListener { String s = e.getActionCommand();
static JFrame f; if (s.equals("click")) {
public static void main(String[] args) { JDialog d = new JDialog(f, "dialog
// create a new frame Box");

f = new JFrame("frame"); JLabel l = new JLabel("this is a dialog


box");
solve s = new solve();
d.add(l);
JPanel p = new JPanel();
d.setSize(100, 100);
JButton b = new JButton("click");
d.setVisible(true);
b.addActionListener(s);
} } }
p.add(b);
Output:

CU IDOL SELF LEARNING MATERIAL (SLM)


Event Handling 73

Example of JApplet:
import javax.swing.*; prsMe.addActionListener(this);
import java.awt.*; answr.addActionListener(this); }

import java.awt.event.*; public void actionPerformed(ActionEvent e)

public class JHello2JavaExample extends JApplet {


implements ActionListener String name = answr.getText();
{ cntnr.remove(Grtng);
JLabel Grtng = new JLabel("Hello. Who are you?"); cntnr.remove(PrsMe);
Font FntOne = new Font("Arial", Font.BOLD, 36) cntnr.remove(answr);
Font FntTwo = new Font("Arial", Font.ITALIC, 48); PrsnlGrtng.setText("Hello, " + name + "! ");
JTextField answr = new JTextField(10); cntnr.add(PrsnlGrtng);
JButton PrsMe = new JButton("Press me"); cntnr.setBackground(Color.CYAN);
JLabel PrsnlGrtng = new JLabel(" "); validate();
Container cntnr = getContentPane( ); }
public void init( ) { }
Grtng.setFont(FntOne);
Output
PrsnlGrtng.setFont(FntTwo);
cntnr.add(Grtng);
cntnr.add(answr);
cntnr.add(PrsMe);
cntnr.setLayout(new FlowLayout());
cntnr.setBackground(Color.YELLOW);

3.11 Practical Assignment

1. Develop AWT Application which accepts name of User through textbox and one Button,
set flowlayout for desigining and on click of Button Welcome to name typed in text box.
2. Develop a Java application to demonstrate all mouse movements Like click, mouse move
etc.

3.12 Summary
Any program that uses GUI (graphical user interface) such as Java application written for
windows, is event driven. Event describes the change in state of any object. For
Example: Pressing a button, Entering a character in Textbox, Clicking or Dragging a mouse, etc.

CU IDOL SELF LEARNING MATERIAL (SLM)


74 Advanced Internet Programming

3.13 Key Words/Abbreviations


 pluggable look and feel: Pluggable look and feel is a mechanism used in the Java
Swing widget toolkit allowing to change the look and feel of the graphical user interface
at runtime.The look and feel can be changed at runtime.
 JComponent : JComponent is an abstract class that almost all Swing components extend;
it provides much of the underlying functionality common throughout the Swing
component library

3.14 Learning Activity


1. Explain container class
-----------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------
2. What is event handling
-----------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------

3.15 Unit End Questions (MCQs and Descriptive)


A. Descriptive Types Questions
1. Write short notes on Event Delegation Model
2. Different types of event in Java AWT
3. What are Events and Event Classes ?
4. Explain how Event Handling is done in Java
5. What are Adapter classes ?
6. What are AWT Events Explain?
7. Explain Need of swing Components.
8. Explain different Swing components.
9. Explain AWT and Swing Components.
10. Explain Container class.

CU IDOL SELF LEARNING MATERIAL (SLM)


Event Handling 75

B. Multiple Choice/Objective Type Questions


1. Which of these packages contains all the classes and methods required for even handling
in Java?
(a) java.applet (b) java.awt
(c) java.event (d) java.awt.event
2. Which of these methods are used to register a keyboard event listener?
(a) KeyListener() (b) addKistener()
(c) addKeyListener() (d) eventKeyboardListener()
3. Which is the container that doesn’t contain title bar and MenuBars but it can have other
components like button, textfield etc?
(a) Window (b) Frame
(c) Panel (d) Container
4. Which method is used to set the graphics current color to the specified color in the
graphics class?
(a) public abstract void setFont(Font font)
(b) public abstract void setColor(Color c)
(c) public abstract void drawString(String str, int x, int y)
(d) None of the above
5. Which object can be constructed to show any number of choices in the visible window?
(a) Labels (b) Choice
(c) List (d) Checkbox

Answers
1. (d), 2. (c), 3. (c), 4. (b), 5. (c)

3.16 References
1. https://www.studytonight.com/java/event-handling-in-java.php
2. https://www.javatpoint.com/java-swing
3. Java AWT Reference by John Zukowski

CU IDOL SELF LEARNING MATERIAL (SLM)


UNIT 4 JAVA SERVLETS - I

Structure:
4.0 Learning Objectives

4.1 Introduction

4.2 Introduction to Servelts

4.3 Server-Side Programming

4.4 Web Server

4.5 Servlet Architecture

4.6 Web Container

4.7 Servlet Life Cycle

4.8 Tomcat Interface

4.9 Servlet Interface

4.10 Practical Assignment

4.11 Summary

4.12 Key Words/Abbreviations

4.13 Learning Activity

4.14 Unit End Questions (MCQs and Descriptive)

4.15 References

CU IDOL SELF LEARNING MATERIAL (SLM)


Java Servlets - I 77

4.0 Learning Objectives


After studying this unit, you will be able to:

 Describe server side programming


 Elaborate web server, and Java serverside components
 Explain Servlet Architecture, WebContainer, Servlet Life Cycle
 Discuss Tomcat Interface, and Servlet interface

4.1 Introduction
Servlets provide a component-based, platform-independent method for building Webbased
applications, without the performance limitations of CGI programs. Servlets have access to the
entire family of Java APIs, including the JDBC API to access enterprise databases. This tutorial
will teach you how to use Java Servlets to develop your web based applications in simple and
easy steps.

4.2 Introduction to Servlets


Servlets are Java programs that run on Web or application servers, acting as a middle layer
between requests coming from Web browsers or other HTTP clients and databases or applications
on the HTTP server. Their job is to perform the following tasks, as illustrated in Figure

Database
Legacy Application

Java Application

Web Service
Client (End User) Web Server
(Servlets/JSP)

Fig. 4.1: Servlets


 Read the explicit data sent by the client: The end user normally enters the data in an
HTML form on a Web page. However, the data could also come from an applet or a
custom HTTP client program.
 Read the implicit HTTP request data sent by the browser: Figure 1 shows a single
arrow going from the client to the Web server (the layer where servlets and JSP execute),

CU IDOL SELF LEARNING MATERIAL (SLM)


78 Advanced Internet Programming

but there are really two varieties of data: the explicit data that the end user enters in a
form and the behind-the-scenes HTTP information. Both varieties are critical.
 Generate the results: This process may require talking to a database, executing an RMI
or EJB call, invoking a Web service, or computing the response directly. Your real data
may be in a relational database. Fine. But your database probably doesn’t speak HTTP or
return results in HTML, so the Web browser can’t talk directly to the database. Even if it
could, for security reasons, you probably would not want it to. The same argument
applies to most other applications. You need the Web middle layer to extract the
incoming data from the HTTP stream, talk to the application, and embed the results
inside a document.
 Send the explicit data (i.e., the document) to the client: This document can be sent in a
variety of formats, including text (HTML or XML), binary (GIF images), or even a
compressed format like gzip that is layered on top of some other underlying format. But,
HTML is by far the most common format, so an important servlet/JSP task is to wrap the
results inside of HTML.
 Send the implicit HTTP response data: Figure 1 shows a single arrow going from the
Web middle layer (the servlet or JSP page) to the client. But, there are really two
varieties of data sent.both varieties are critical to effective development. Sending HTTP
response data involves telling the browser or other client what type of document is being
returned (e.g., HTML), setting cookies and caching parameters, and other such tasks.

Web Server HTTP Request

Client

HTTP Response
Servlet Container

Fig. 4.2: Deployment Diagram of a Web Server

4.3 Server-Side Programming


All of us would have started programming in java with the famous “hello world” program. If
you can recollect, we saved the file with a ‘.java’ extension and later compiled the program using
‘javac’ and then executed the program using ‘java’. Apart from introducing you to the language
basics, the important point is that it is a client-side program. That means you write, compile and

CU IDOL SELF LEARNING MATERIAL (SLM)


Java Servlets - I 79

execute the program in the client machine (i.e., your PC). No doubt, it is the easiest and fastest
way to write, compile and execute the program. However, it has little practical significance when
it comes to real-world programming.

Why Server Side Programming


Though it is technically feasible to implement almost any business logic using client-side
programs, logically or functionally it server no purpose when it comes to enterprises application
(e.g., banking, air ticketing, e-shopping, etc). To further explain, going by the client-side
programming logic; a bank having 10,000 `1.. customers would mean that each customer would
have a copy of the program(s) in his or her PC (and now even mobiles) which translates to 10,000
programs! In addition, there are issues like security, resource pooling, concurrent access and
manipulations to the database which simply cannot be handled by client-side programs. The
answer to most of the issues cited above is- “Server Side Programming”. Figure illustrates the
Server Side Architecture in the simplest way.

Client 1
Java Server/
java Server
Page/XML

Client 2 Application
Server

Database/
Client 3 Web Services

Web Server

Server Side Programming Architecture

Fig. 4.3: Server Side Programming Architecture

Advantages of Server Side Programs


Some of the advantages of Server Side programs are as follows:

1. All programs reside in one machine called server. Any number of remote machines
(called clients) can access the server programs.
2. New functionalities to existing programs can be added at the server side which the clients
can take advantage of without having to change anything.

CU IDOL SELF LEARNING MATERIAL (SLM)


80 Advanced Internet Programming

3. Migrating to newer versions, architectures, design patterns, adding patches, switching to


new databases can be done at the server side without having to bother about client’s
hardware or software capabilities.
4. Issues relating to enterprise applications like resource management, concurrency, session
management, security and performance are managed by the server side applications.
5. They are portable and possess the capability to generate dynamic and user-based content
(e.g., displaying transaction information of credit card or debit card depending on user’s
choice).
It is the program that runs on server dealing with the generation of content of web page.

1. Querying the database


2. Operations over databases
3. Access/Write a file on server.
4. Interact with other servers.
5. Structure web applications.
6. Process user input. For example if user input is a text in search box, run a search
algorithm on data stored on server and send the results.
Examples
The Programming languages for server-side programming are:

1. PHP 2. C++ 3. Java and JSP 4. Python 5. Ruby on Rails

4.4 Web Server


Servlet Container
It provides the runtime environment for JavaEE (j2ee) applications. The client/user can
request only a static WebPages from the server. If the user wants to read the web pages as per
input then the servlet container is used in java.

The servlet container is used in java for dynamically generate the web pages on the server
side. Therefore the servlet container is the part of a web server that interacts with the servlet for
handling the dynamic web pages from the client.

CU IDOL SELF LEARNING MATERIAL (SLM)


Java Servlets - I 81

There are two Types of Servers


1. Web Server
2. Application Server

Web Server
Web server contains only web or servlet container. It can be used for servlet, jsp, struts, jsf
etc. It can’t be used for EJB.

It is a computer where the web content can be stored. In general web server can be used to
host the web sites but there also used some other web servers also such as FTP, email, storage,
gaming etc.

Examples of Web Servers are: Apache Tomcat and Resin.

Important Points
 If the requested web page at the client side is not found, then web server will sends the
HTTP response: Error 404 Not found.
 When the web server searching the requested page if requested page is found then it will
send to the client with an HTTP response.
 If the client requests some other resources then web server will contact to application
server and data is store for constructing the HTTP response.

Application Server
Application server contains Web and EJB containers. It can be used for servlet, jsp, struts, jsf,
ejb etc. It is a component based product that lies in the middle-tier of a server centric architecture.

It provides the middleware services for state maintenance and security, along with
persistence and data access. It is a type of server designed to install, operate and host associated
services and applications for the IT services, end users and organizations.

The block diagram representation of Application Server is shown below:

CU IDOL SELF LEARNING MATERIAL (SLM)


82 Advanced Internet Programming

Client Tier
Applications Browsers

APIs

Middle Tier
J2EE Platform
EJB Server Web Server

APIs APIs

EIS Tier
Applications Database
Servers

Files Databases

Fig. 4.4: Application Server


The Example of Application Servers are:

1. JBoss: Open-source server from JBoss community.


2. Glassfish: Provided by Sun Microsystem. Now acquired by Oracle.
3. Weblogic: Provided by Oracle. It more secured.
4. Websphere: Provided by IBM.

4.5 Servlet Architecture


Following diagram shows the position of Servelts in a Web Application.

HTTP Server
HTTP Protocol

Web Browser Servelets


Program

Database

Fig. 4.5: Position of Servelts in a Web Application

Servlets Tasks
Servlets perform the following major tasks:

CU IDOL SELF LEARNING MATERIAL (SLM)


Java Servlets - I 83

1. Read the explicit data sent by the clients (browsers). This includes an HTML form on a
Web page or it could also come from an applet or a custom HTTP client program.
2. Read the implicit HTTP request data sent by the clients (browsers). This includes cookies,
media types and compression schemes the browser understands, and so forth.
3. Process the data and generate the results. This process may require talking to a database,
executing an RMI or CORBA call, invoking a Web service, or computing the response
directly.
4. Send the explicit data (i.e., the document) to the clients (browsers). This document can
be sent in a variety of formats, including text (HTML or XML), binary (GIF images),
Excel, etc.
5. Send the implicit HTTP response to the clients (browsers). This includes telling the
browsers or other clients what type of document is being returned (e.g., HTML), setting
cookies and caching parameters, and other such tasks.

Servlets Packages
Java Servlets are Java classes run by a web server that has an interpreter that supports the
Java Servlet specification.

Servlets can be created using the javax.servlet and javax.servlet.http packages, which are a
standard part of the Java’s enterprise edition, an expanded version of the Java class library that
supports large-scale development projects.

These classes implement the Java Servlet and JSP specifications. At the time of writing this
tutorial, the versions are Java Servlet 2.5 and JSP 2.1.

Java servlets have been created and compiled just like any other Java class. After you install
the servlet packages and add them to your computer’s Classpath, you can compile servlets with
the JDK’s Java compiler or any other current compiler.

4.6 Web Container


Web container (also known as a Servlet container) is the component of a web server that
interacts with Java servlets. A web container is responsible for managing the lifecycle of servlets,
mapping a URL to a particular servlet and ensuring that the URL requester has the correct access
rights. A web container implements the web component contract of the Java EE architecture,
specifying a runtime environment for web components that includes security, concurrency,

CU IDOL SELF LEARNING MATERIAL (SLM)


84 Advanced Internet Programming

lifecycle management, transaction, deployment, and other services. A web container provides the
same services as a JSP container as well as a federated view of the Java EE platform APIs

A Web application runs within a Web container of a Web server. The Web container
provides the runtime environment through components that provide naming context and life cycle
management. Some Web servers may also provide additional services such as security and
concurrency control. A Web server may work with an EJB server to provide some of those
services. A Web server, however, does not need to be located on the same machine as an EJB
server.

Web applications are composed of web components and other data such as HTML pages.
Web components can be servlets, JSP pages created with the JavaServer Pages™ technology, web
filters, and web event listeners. These components typically execute in a web server and may
respond to HTTP requests from web clients. Servlets, JSP pages, and filters may be used to
generate HTML pages that are an application’s user interface. They may also be used to generate
XML or other format data that is consumed by other application components.

4.7 Servlet Life Cycle


The lifecycle of a servlet is controlled by the container in which the servlet has been
deployed. When a request is mapped to a servlet, the container performs the following steps.

1. If an instance of the servlet does not exist, the web container


(a) Loads the servlet class.
(b) Creates an instance of the servlet class.
(c) Initializes the servlet instance by calling the init method. Initialization is covered in
Creating and Initializing a Servlet.
2. Invokes the service method, passing request and response objects. Service methods are
discussed in Writing Service Methods.

1. Load servlet class. 5. Call the destroy method.

2. Create servlet instance.

3. Call the in it method. <<interface>>


Servlet

Init (servletConfig)
4. Call the service method. Service (req, resp)
Destroy ()

Fig. 4.6: Servlet Life Cycle

CU IDOL SELF LEARNING MATERIAL (SLM)


Java Servlets - I 85

1. Load the Servlet Class: The classloader is responsible to load the servlet class. The servlet class is
loaded when the first request for the servlet is received by the web container.
2. Create Servlet instance: The web container creates the instance of a servlet after
loading the servlet class. The servlet instance is created only once in the servlet life cycle.
3. Call the init method: The web container calls the init method only once after creating
the servlet instance. The init method is used to initialize the servlet. It is the life cycle
method of the javax.servlet.Servlet interface.
4. call the service method: The web container calls the service method each time when
request for the servlet is received. If servlet is not initialized, it follows the first three
steps as described above then calls the service method. If servlet is initialized, it calls the
service method. Notice that servlet is initialized only once.
5. destroy method is invoked: The web container calls the destroy method before
removing the servlet instance from the service. It gives the servlet an opportunity to clean
up any resource for example memory, thread etc

Create Initialize Available for Servicing


service requests

(Unavailable
unavailable for exception
service thrown)
(Initialization
Failed)

Destroy

Unload

Fig. 4.7: Servlet Life Cycle Diagram


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

 The servlet is initialized by calling the init () method.


 The servlet calls service() method to process a client’s request.
 The servlet is terminated by calling the destroy() method.
 Finally, servlet is garbage collected by the garbage collector of the JVM.
Now let us discuss the life cycle methods in details.

CU IDOL SELF LEARNING MATERIAL (SLM)


86 Advanced Internet Programming

The init() Method


The init method is designed to be called only once. It is called when the servlet is first
created, and not called again for each user request. So, it is used for one-time initializations, just
as with the init method of applets.

The servlet is normally created when a user first invokes a URL corresponding to the servlet,
but you can also specify that the servlet be loaded when the server is first started.

When a user invokes a servlet, a single instance of each servlet gets created, with each user
request resulting in a new thread that is handed off to doGet or doPost as appropriate. The init()
method simply creates or loads some data that will be used throughout the life of the servlet.

The init method definition looks like this:

public void init() throws ServletException {


// Initialization code...
}

The service() Method


The service() method is the main method to perform the actual task. The servlet container (i.e.
web server) calls the service() method to handle requests coming from the client( browsers) and
to write the formatted response back to the client.

Each time the server receives a request for a servlet, the server spawns a new thread and calls
service. The service() method checks the HTTP request type (GET, POST, PUT, DELETE, etc.)
and calls doGet, doPost, doPut, doDelete, etc. methods as appropriate.

Here is the signature of this method:

public void service(ServletRequest request,


ServletResponse response)
throws ServletException, IOException {
}

The service () method is called by the container and service method invokes doGe, doPost,
doPut, doDelete, etc. methods as appropriate. So you have nothing to do with service() method
but you override either doGet() or doPost() depending on what type of request you receive from
the client.

CU IDOL SELF LEARNING MATERIAL (SLM)


Java Servlets - I 87

4.8 Tomcat Interface


Interfaces in javax.servlet.http Package
There are many interfaces in javax.servlet.http package. They are as follows:

 HttpServletRequest
 HttpServletResponse
 HttpSession
 HttpSessionListener
 HttpSessionAttributeListener
 HttpSessionBindingListener
 HttpSessionActivationListener
 HttpSessionContext (deprecated now)

<<Interface>> <<Interface>> <<Interface>>


ServletRequest Servlet ServletResponse

Service(req,resp)
get Parameter (name) get Writer (): PrintWriter
get ParameterValues(name) get OutputStream
get ParameterName SetContentType (MIME)
SetContentLength (int)

<<Interface>>
HttpServletRequest Httpservlet <<Interface>>
{abstract} HttpServletRequest

getHeader (name) setHeader


getHeaders(name) Service setDateHeader
get HeaderNames ( ) :Enum. doGet setIntHeader
getIntHeader (name) dopost
getDateHeader (name)

Fig. 4.8: Tomcat Interfaces

Classes in javax.servlet.http Package


There are many classes in javax.servlet.http package. They are as follows:

 HttpServlet
 Cookie
 HttpServletRequestWrapper

CU IDOL SELF LEARNING MATERIAL (SLM)


88 Advanced Internet Programming

 HttpServletResponseWrapper
 HttpSessionEvent
 HttpSessionBindingEvent

4.9 Servlet Interface


Servlet interface is a collection of empty method signatures.

A Servlet must directly or indirectly [by subclassing the GenericServlet or HttpServlet class]
implement the Servlet interface.

This interface holds method signatures that bring the following Servlet functionalities:

 Initializing a Servlet
 Handling a client request
 Destroying a Servlet
The following are the methods available in this interface:
Table 4.1: Methods Available in this Interface
Methods Description
init() Is used for initializing the Servlet parameters provided by the ServletConfig
object.
Is called only once when the Servlet is first loaded. It is commonly used to
initialize resources to be used by a Servlet when requests are received.
For example, database or network connections, file initialization and other
environmental settings.
None of the Servlets methods can be called unless the Servlet is initialized using
init().
destroy() destroy() is also called only once immediately before the Servlet is unloaded.
Is used to clear all retained resources such as database connection, threads, file
handles and so on. This method is overridden in order to free up any resources
being used by the Servlet.
service() Is the actual heart of the HTTP Request-Response model.
Is called to handle a single client request.
A Servlet receives request information through the ServletRequest object and
sends data back to the client through the ServletResponse object.
getServletConfig() Provides the ServletConfig object for initializing the Servlet’s parameters.

CU IDOL SELF LEARNING MATERIAL (SLM)


Java Servlets - I 89

getServletInfo() Provides the Servlet metadata such as author, Servlet version and other
copyright information. This method needs to be overridden inside the Servlet for
it to return the required information.

4.10 Practical Assignment


1. Develop Java Application to demonstrate Servlet Life cycle.
2. Develop Java Application for Servlet Login.

4.11 Summary
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.

4.12 Key Words/Abbreviations


 Cookie: Cookies are text files stored on the client computer and they are kept for various
information tracking purpose.

4.13 Learning Activity


1. Explain Tomcat interface.
-----------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------

CU IDOL SELF LEARNING MATERIAL (SLM)


90 Advanced Internet Programming

2. Explain Web container.


-----------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------

4.14 Unit End Questions (MCQs and Descriptive)


A. Descriptive Types Questions
1. What is Servlet? Explain in detail.
2. Explain Web Server and Application server with its working.
3. Explain Web Container in detail
4. Explain Servlet Interface and its methods.
5. Explain Servlet Lifecycle.
6. Write a short note on Server-Side Programming.
7. Explain Java Server side components in detail.
8. Explain Servlet Architecture with neat diagram.
9. Explain Tomcat Interface with httpservlet.

B. Multiple Choice/Objective Type Questions


1. Which object of HttpSession can be used to view and manipulate information about a
session?
(a) session identifier (b) creation time
(c) last accessed time (d) All mentioned above
2. Which class provides stream to read binary data such as image etc. from the request
object?
(a) ServltInputStream (b) ServletOutputStream
(c) Both A & B (d) None of the above
3. Which of these ways used to communicate from an applet to servlet?
(a) RMI Communication (b) HTTP Communication
(c) Socket Communication (d) All mentioned above

CU IDOL SELF LEARNING MATERIAL (SLM)


Java Servlets - I 91

4. Which type of ServletEngine is a server that includes built-in support for servlets?
(a) Add-on ServletEngine (b) Embedded ServletEngine
(c) Standalone ServletEngine (d) None of the above
5. Which cookie it is valid for single session only and it is removed each time when the user
closes the browser?
(a) Persistent cookie (b) Non-persistent cookie
(c) All the above (d) None of the above

Answers
1. (d), 2. (a), 3. (d), 4. (c), 5. (b)

4.15 References
1. https://www.tutorialspoint.com/servlets/index.htm
2. https://www.baeldung.com/intro-to-servlets
3. JDBC 4.2, Servlet 3.1, and JSP 2.3 Includes JSF 2.2 and Design Patterns, Black Book,
2ed

CU IDOL SELF LEARNING MATERIAL (SLM)


UNIT 5 JAVA SERVLETS - II

Structure:
5.0 Learning Objectives
5.1 Introduction
5.2 Servicing client requests
5.3 GET and POST request methods
5.4 Retrieving data from database to servlet
5.5 Servlet config and Servlet context
5.6 Session Tracking
5.7 Practical Assignment
5.8 Summary
5.9 Key Words/Abbreviations
5.10 Learning Activity
5.11 Unit End Questions (MCQs and Descriptive)
5.12 References

5.0 Learning Objectives


After studying this unit, you will be able to:

 Explain servicing client requests and GET and POST request methods
 Discuss Retrieving data from databaseto servlet, Servlet config and Servletcontext
 Elaborate session tracking

CU IDOL SELF LEARNING MATERIAL (SLM)


Java Servlets - II 93

5.1 Introduction
Servlet technology is used to create a web application (resides at server side and generates a
dynamic web page).

Servlet technology is robust and scalable because of java language. Before Servlet, CGI
(Common Gateway Interface) scripting language was common as a server-side programming
language. However, there were many disadvantages to this technology. We have discussed these
disadvantages below.

There are many interfaces and classes in the Servlet API such as Servlet, GenericServlet,
HttpServlet, ServletRequest, ServletResponse, etc.

5.2 Servicing client requests


Servicing Client request can be performed by http protocol.

Http Protocol & Http Methods:-


HTTP (Hyper Text Transfer Protocol)
The Hypertext Transfer Protocol (HTTP) is application-level protocol for collaborative,
distributed, hypermedia information systems. It is the data communication protocol used to
establish communication between client and server.

HTTP is TCP/IP based communication protocol, which is used to deliver the data like image
files, query results, HTML files etc on the World Wide Web (WWW) with the default port is TCP
80. It provides the standardized way for computers to communicate with each other.

Http Request Server

Http Response

Client

Fig. 5.1: Http Protocol


The Basic Characteristics of HTTP (Hyper Text Transfer Protocol):

 It is the protocol that allows web servers and browsers to exchange data over the web.

CU IDOL SELF LEARNING MATERIAL (SLM)


94 Advanced Internet Programming

 It is a request response protocol.


 It uses the reliable TCP connections by default on TCP port 80.
 It is stateless means each request is considered as the new request. In other words, server
doesn’t recognize the user by default.

The Basic Features of HTTP (Hyper Text Transfer Protocol):


There are three fundamental features that make the HTTP a simple and powerful protocol
used for communication:

 HTTP is media independent: It refers to any type of media content can be sent by
HTTP as long as both the server and the client can handle the data content.
 HTTP is connectionless: It is a connectionless approach in which HTTP client i.e., a
browser initiates the HTTP request and after the request is sends the client disconnects
from server and waits for the response.
 HTTP is stateless: The client and server are aware of each other during a current request
only. Afterwards, both of them forget each other. Due to the stateless nature of protocol,
neither the client nor the server can retain the information about different request across
the web pages.

HTTP Architecture (Hyper Text Transfer Protocol)


The below diagram represents the basic architecture of web application and depicts where
HTTP stands:

Web Server

Web Client Server Side Script

Database

HTTP Protocol

Fig. 5.2: HTTP Architecture

CU IDOL SELF LEARNING MATERIAL (SLM)


Java Servlets - II 95

HTTP is request/response protocol which is based on client/server based architecture. In this


web browser, search engines, etc behaves as a HTTP clients, and the Web server like Servlet
behaves as a server.

5.3 GET and POST Request Methods


HTTP Methods
1. HTTP Requests: The request sends by the computer to a web server that contains all sorts
of potentially interesting information is known as HTTP requests.

The HTTP client sends the request to the server in the form of request message which
includes following information:

 The Request-line
 The analysis of source IP address, proxy and port
 The analysis of destination IP address, protocol, port and host
 The Requested URI (Uniform Resource Identifier)
 The Request method and Content
 The User-Agent header
 The Connection control header
 The Cache control header
The HTTP request method indicates the method to be performed on the resource identified
by the Requested URI (Uniform Resource Identifier). This method is case-sensitive and should
be used in uppercase.

The HTTP request methods are:


Table 5.1: HTTP Request Methods
HTTP Request Description
GET Asks to get the resource at the requested URL.
POST Asks the server to accept the body info attached. It is like GET request with extra
info sent with the request.
HEAD Asks for only the header part of whatever a GET would return. Just like GET but
with no body.
TRACE Asks for the loopback of the request message, for testing or troubleshooting.

CU IDOL SELF LEARNING MATERIAL (SLM)


96 Advanced Internet Programming

PUT Says to put the enclosed info (the body) at the requested URL.
DELETE Says to delete the resource at the requested URL.
OPTIONS Asks for a list of the HTTP methods to which the thing at the request URL can
respond
2. Get vs. Post: There are many differences between the Get and Post request. Let’s see
these differences:
Table 5.2: Differences Between the Get and Post Request
GET POST
1. In case of Get request, only limited amount of In case of post request, large amount of data
data can be sent because data is sent in header. can be sent because data is sent in body.
2. Get request is not secured because data is Post request is secured because data is not
exposed in URL bar. exposed in URL bar.
3. Get request can be bookmarked. Post request cannot be bookmarked.
4. Get request is idempotent . It means second Post request is non-idempotent.
request will be ignored until response of first
request is delivered
5. Get request is more efficient and used more than Post request is less efficient and used less
Post. than get.

GET and POST


Two common methods for the request-response between a server and client are:

 GET: It requests the data from a specified resource


 POST: It submits the processed data to a specified resource

Anatomy of Get Request


The query string (name/value pairs) is sent inside the URL of a GET request:

1. GET /RegisterDao.jsp?name1=value1&name2=value2
As we know that data is sent in request header in case of get request. It is the default
request type. Let’ see what information is sent to the server.

CU IDOL SELF LEARNING MATERIAL (SLM)


Java Servlets - II 97

Fig. 5.3: Anatomy of GET Request

Anatomy of Post Request


The query string (name/value pairs) is sent in HTTP message body for a POST request:

1. POST/RegisterDao.jsp HTTP/1.1
2. Host: www. javatpoint.com
3. name1=value1&name2=value2
As we know, in case of post request original data is sent in message body. Let’s see how
information is passed to the server in case of post request.

Fig. 5.4: Anatomy of Post Request

5.4 Retrieving Data from Database to Servlet


Design database for student administration. Develop servlet(s) to perform CRUD operations.

CU IDOL SELF LEARNING MATERIAL (SLM)


98 Advanced Internet Programming

HomePage.html
<!DOCTYPE html> <input type="submit" value="Insert">
<html> </form>
<head> <br>
<title>Home page</title> <form action="updateData.html">
<meta charset="UTF-8"> <input type="submit" value="Update">
<meta name="viewport" </form>
content="width=device-width, initial-scale=1.0"> <br>
</head> <form action="deleteData.html">
<body> <input type="submit" value="Delete">
<center> </form>
<h1>Student Administration</h1> <br>
<form action="createtblStud"> <form action="selectStud">
<input type="submit" value="Create <input type="submit" value="Show All
tblStudent"> Records">
</form> </form>
<br> </center> </body> </html>
<form action="insertData.html">

web.xml
<?xml version="1.0" encoding="UTF-8"?> <servlet-name>InsertStudent</servlet-
<web-app name>
xmlns="http://xmlns.jcp.org/xml/ns/javaee" <url-pattern>/InsertStudent</url-pattern>
xmlns:xsi="http://www.w3.org/2001/XMLSchema- </servlet-mapping>
instance" <servlet>
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/jav
aee <servlet-name>UpdateStudent</servlet-
name>
http://xmlns.jcp.org/xml/ns/javaee/web-
app_3_1.xsd" <servlet-class>UpdateStudent</servlet-
class>
version="3.1">
</servlet>
<session-config>
<servlet-mapping>
<session-timeout>
<servlet-name>UpdateStudent</servlet-

CU IDOL SELF LEARNING MATERIAL (SLM)


Java Servlets - II 99

30 name>
</session-timeout> <url-pattern>/UpdateStudent</url-pattern>
</session-config> </servlet-mapping>
<welcome-file-list> <servlet>
<welcome-file>HomePage.html</welcome-file> <servlet-name>DeleteStudent</servlet-
</welcome-file-list> name>

<servlet> <servlet-class>DeleteStudent</servlet-
class>
<servlet-name>createtblStud</servlet-name>
</servlet>
<servlet-class>createtblStud</servlet-class>
<servlet-mapping>
</servlet>
<servlet-name>DeleteStudent</servlet-
<servlet-mapping> name>
<servlet-name>createtblStud</servlet-name> <url-pattern>/DeleteStudent</url-pattern>
<url-pattern>/createtblStud</url-pattern> </servlet-mapping>
</servlet-mapping> <servlet>
<servlet> <servlet-
<servlet-name>selectStud</servlet-name> name>UpdateStudentDetails</servlet-
<servlet-class>selectStud</servlet-class> name>

</servlet> <servlet-
class>UpdateStudentDetails</servlet-
<servlet-mapping> class>
<servlet-name>selectStud</servlet-name> </servlet>
<url-pattern>/selectStud</url-pattern> <servlet-mapping>
</servlet-mapping> <servlet-
<servlet> name>UpdateStudentDetails</servlet-
<servlet-name>InsertStudent</servlet-name> name>

<servlet-class>InsertStudent</servlet-class> <url-pattern>/UpdateStudentDetails</url-
pattern>
</servlet>
</servlet-mapping> </web-app>
<servlet-mapping>

createtblStud.java
Import javax.servlet.*; String query="create table tblStudent(RollNo
import javax.servlet.http.*; int,StudName varchar(20),MarksSSC

import java.io.*; float,MarksHSC float);";

import java.sql.*; System.out.println(query);

public class createtblStud extends int c=st.executeUpdate(query);


HttpServlet{ if(c==0)

CU IDOL SELF LEARNING MATERIAL (SLM)


100 Advanced Internet Programming

public void service(HttpServletRequest out.println("<h1>Table created<br>");


request,HttpServletResponse response) else
throws IOException
out.println("<h1>Error in creation/already
{ exists<br>");
Connection con; out.println("<a href='HomePage.html'>Click to
Statement st; go to Home Page</a><br>");
PrintWriter out=response.getWriter(); }
response.setContentType("text/html"); catch(Exception e)
out.println("<center>"); {
try System.out.println(e);
{ out.println("<h1>Error in creation/already
Class.forName("com.mysql.jdbc.Driver"); exists<br>");

con=DriverManager.getConnection("jdbc:mys out.println("<a href='HomePage.html'>Click to


ql://localhost:9300/dbStudent","root","root"); go to Home Page</a><br>");

st=con.createStatement(); } } }

insertData.html
<!DOCTYPE html> <td><input type="text"
<html> name="txtStudName"></td>

<head> </tr>

<meta http-equiv="Content-Type" <tr>


content="text/html; charset=UTF-8"> <td>Marks in SSC</td>
<title>Insert</title> <td><input type="text"
</head> name="txtMarksSSC"></td>

<body> </tr>

<center> <tr>

<h1>Student Data Insertion</h1> <td>Marks in HSC</td>

<form action="InsertStudent"> <td><input type="text"


name="txtMarksHSC"></td>
<table>
</tr>
<tr>
<tr>
<td>Roll no</td>
<td><input type="submit" name="Insert"></td>
<td><input type="text" name="txtRollNo"></td>
</tr>
</tr>
</table>
<tr>
</form> </center> </body> </html>
<td>Student Name</td>

CU IDOL SELF LEARNING MATERIAL (SLM)


Java Servlets - II 101

InsertStudent.java
import javax.servlet.*; marksSSC=Float.parseFloat(request.getPar
import javax.servlet.http.*; ameter("txtMarksSSC"));

import java.io.*; float


marksHSC=Float.parseFloat(request.getParam
import java.sql.*; eter("txtMarksHSC"));
public class InsertStudent extends HttpServlet{ String query="insert into tblStudent
public void service(HttpServletRequest values("+no+",'"+name+"',"+marksSSC+","+mar
request,HttpServletResponse response) throws ksHSC+")";
IOException System.out.println(query);
{ int c=st.executeUpdate(query);
Connection con; if(c!=0)
Statement st; out.println("<h1>Record inserted<br>");
PrintWriter out=response.getWriter(); else
response.setContentType("text/html"); out.println("<h1>Error in insertion<br>");
out.println("<center>"); out.println("<a href='HomePage.html'>Click to
try go to Home Page</a><br>");
{ out.println("<a href='insertData.html'>Click to
Class.forName("com.mysql.jdbc.Driver");tm add one more record</a></h1>"); }
con=DriverManager.getConnection("jdbc:mysql catch(Exception e)
://localhost:9300/dbStudent","root","root"); {
st=con.createStatement(); System.out.println(e);
int out.println("<h1>Error in insertion<br>");
no=Integer.parseInt(request.getParameter("txt
RollNo")); out.println("<a href='HomePage.html'>Click to
go to Home Page</a><br>");
String
name=request.getParameter("txtStudName"); out.println("<a href='insertData.html'>Click to
add one more record</a></h1>");
float
} } }

deleteData.html
<!DOCTYPE html> <td>Roll No</td>
<html> <td><input type="text" name="txtRollNo"></td>
<head> </tr>
<meta http-equiv="Content-Type" <tr>
content="text/html; charset=UTF-8"> <td><input type="submit"
<title>Delete</title> name="Delete"></td>
</head> </tr>

CU IDOL SELF LEARNING MATERIAL (SLM)


102 Advanced Internet Programming

<body> </table>
<center> </form>
<h1>Student Data Deletion</h1> </center>
<form action="DeleteStudent"> </body>
<table> </html>
<tr>

DeleteStudent.java
import javax.servlet.*; String query="select * from tblStudent where
import javax.servlet.http.*; RollNo="+no+";";

import j ava.io.*; ResultSet rs=st.executeQuery(query);

import java.sql.*; if(rs.next())

public class DeleteStudent extends HttpServlet {


{ query="delete from tblStudent where
public void service(HttpServletRequest RollNo="+no+";";
request,HttpServletResponse response) throws int c=st.executeUpdate(query);
IOException if(c!=0)
{ out.println("<h1>Record deleted<br>");
Connection con; }
Statement st; else
PrintWriter out=response.getWriter(); out.println("<h1>No such record<br>");
response.setContentType("text/html"); out.println("<a href='HomePage.html'>Click to
out.println("<center>"); go to Home Page</a><br><br>");
try }
{ catch(Exception e)
Class.forName("com.mysql.jdbc.Driver"); {
System.out.println(e);
con=DriverManager.getConnection("jdbc:mysql: out.println("<h1>Error in deletion<br>");
//localhost:9300/dbStudent","root","root");
out.println("<a href='HomePage.html'>Click to
st=con.createStatement(); go to Home Page</a><br><br>");
int } } }
no=Integer.parseInt(request.getParameter("txtR
ollNo"));

updateData.html
<!DOCTYPE html> <td>Roll No</td>
<html> <td><input type="text" name="txtRollNo"></td>

CU IDOL SELF LEARNING MATERIAL (SLM)


Java Servlets - II 103

<head> </tr>
<meta http-equiv="Content-Type" <tr>
content="text/html; charset=UTF-8"> <td><input type="submit"
<title>Updation</title> name="Update"></td>
</head> </tr>
<body> </table>
<center> </form>
<h1>Student Data Updation</h1> </center>
<form action="UpdateStudent"> </body>
<table> </html>
<tr>

UpdateStudent.java
import javax.servlet.*; float marksSSC=rs.getFloat(3);
import javax.servlet.http.*; float marksHSC=rs.getFloat(4);
import java.io.*; out.println("<form
import java.sql.*; action='UpdateStudentDetails'><table><tr><td>
Roll No</td><td><input type='text'
public class UpdateStudent extends name='txtRollNo' value="+no+"></td></tr>");
HttpServlet{
out.println("<tr><td>Student
public void service(HttpServletRequest Name</td><td><input type='text'
request,HttpServletResponse response) throws name='txtStudName'
IOException value="+name+"></td></tr>");
{ out.println("<tr><td>Marks in
Connection con; SSC</td><td><input type='text'
Statement st; name='marksSSC'
value="+marksSSC+"></td></tr>");
PrintWriter out=response.getWriter();
out.println("<tr><td>Marks in
response.setContentType("text/html"); HSC</td><td><input type='text'
out.println("<center>"); name='marksHSC'
try value="+marksHSC+"></td></tr>");

{ out.println("<tr><td><input type='submit'
name='Update'></td></tr></table></form>");
Class.forName("com.mysql.jdbc.Driver");
}
con=DriverManager.getConnection("jdbc:mysql:
//localhost:9300/dbStudent","root","root"); else

st=con.createStatement(); out.println("<h1>No such record<br>");

int out.println("<a href='HomePage.html'>Click to


no=Integer.parseInt(request.getParameter("txtR go to Home Page</a><br><br>");
ollNo")); }

CU IDOL SELF LEARNING MATERIAL (SLM)


104 Advanced Internet Programming

String query="select * from tblStudent where catch(Exception e)


RollNo="+no+";"; {
ResultSet rs=st.executeQuery(query); System.out.println(e);
if(rs.next()) out.println("<h1>Error in updation<br>");
{ out.println("<a href='HomePage.html'>Click to
no=Integer.parseInt(rs.getString(1)); go to Home Page</a><br><br>");
String name=rs.getString(2); } } }

UpdateStudentDetails.java
import javax.servlet.*; float
marksSSC=Float.parseFloat(request.getPara
import javax.servlet.http.*;
meter("marksSSC"));
import java.io.*;
float
import java.sql.*; marksHSC=Float.parseFloat(request.getPara
public class UpdateStudentDetails extends meter("marksHSC"));
HttpServlet{ String query="update tblStudent set
public void service(HttpServletRequest StudName='"+name+"',MarksSSC="+marksS
request,HttpServletResponse response) throws SC+",MarksHSC='"+marksHSC+"' where
IOException RollNo="+no+";";

{ System.out.println(query);
int c=st.executeUpdate(query);
Connection con;
if(c!=0)
Statement st;
out.println("<h1>Record updated<br>");
PrintWriter out=response.getWriter();
else
response.setContentType("text/html");
out.println("<h1>Error in updation<br>");
out.println("<center>");
out.println("<a href='HomePage.html'>Click
try to go to Home Page</a><br>");
{ }
Class.forName("com.mysql.jdbc.Driver"); catch(Exception e)
con=DriverManager.getConnection("jdbc:mysql:// {
localhost:9300/dbStudent","root","root");
System.out.println(e);
st=con.createStatement();
out.println("<h1>Error in updation<br>");
int
out.println("<a href='HomePage.html'>Click
no=Integer.parseInt(request.getParameter("txtRo
to go to Home Page</a><br>");
llNo"));
} } }
String
name=request.getParameter("txtStudName");

CU IDOL SELF LEARNING MATERIAL (SLM)


Java Servlets - II 105

5.5 Servlet Config and Servlet Context


ServletConfig
 ServletConfig available in javax.servlet.*; package
 ServletConfig object is one per servlet class
 Object of ServletConfig will be created during initialization process of the servlet
 This Config object is public to a particular servlet only
 Scope: As long as a servlet is executing, ServletConfig object will be available, it will be
destroyed once the servlet execution is completed.
 We should give re quest explicitly, in order to create ServletConfig object for the first
time
 In web.xml – <init-param> tag will be appear under <servlet-class> tag

ServletContext
 ServletContext available in javax.servlet.*; package
 ServletContext object is global to entire web application
 Object of ServletContext will be created at the time of web application deployment
 Scope: As long as web application is executing, ServletContext object will be available,
and it will be destroyed once the application is removed from the server.
 ServletContext object will be available even before giving the first request
 In web.xml – <context-param> tag will be appear under <web-app> tag

Difference between ServletConfig and ServletContext in Java Servlet


ServletConfig and ServletContext, both are objects created at the time of servlet
initialization and used to provide some initial parameters or configuration information to the
servlet. But, the difference lies in the fact that information shared by ServletConfig is for a
specific servlet, while information shared by ServletContext is available for all servlets in the web
application.

ServletConfig:
 ServletConfig is an object containing some initial parameters or configuration
information created by Servlet Container and passed to the servlet during initialization.

CU IDOL SELF LEARNING MATERIAL (SLM)


106 Advanced Internet Programming

 ServletConfig is for a particular servlet, that means one should store servlet specific
information in web.xml and retrieve them using this object.
 Example:
Suppose, one is building a job portal and desires to share different email ids (which may
get change over time) to recruiter and job applicant.
So, he decides to write two servlets one for handling recruiter’s request and another one
for the job applicant.
Where to store email-ids?
Put email-id as a name-value pair for different servlet inside web.xml which can further
be retrieved using getServletConfig().getInitParameter(“name”) in the servlet.

ServletContext:
 ServletContext is the object created by Servlet Container to share initial parameters or
configuration information to the whole application.
 Example:
Suppose, the name of one’s job portal is “NewWebsite.tg”. Showing the website name at
the top of webpages delivered by different servlets, one needs to store the website name
in every servlet inviting redundancy. Since the information shared by ServletContext can
be accessed by every Servlet, it is better to go with ServletContext and retrieve the
website name using getServletContext.getInitParameter(“Name”) whenever required.

5.6 Session Tracking


Session Tracking With Servlet API
Session tracking is one of the important roles played by Java Servlet. To understand what
session tracking is, let’s consider a Servlet that implements HTTP sessions, receives HTTP
request from different clients. The Servlet, for each client request, must be able to determine the
HTTP session to which the client request is made. Each client request belongs to just one of the
client sessions tracked by the Servlet.

The Servlet API provides a simple, powerful, set of techniques to deal with sessions. The
Servlet API’s, HttpSession class, provides developers all that is required to track sessions using
Servlet code spec. Each user that invokes the Servlet is mapped to a specific session, represented
by an HttpSession instance.

CU IDOL SELF LEARNING MATERIAL (SLM)


Java Servlets - II 107

Methods of Session Tracking


There are several methods that facilitate exchanging SESSION IDs or state information
between a visitor’s Web browser and the Web server.

The following are the methods that allow tracking sessions:

1. Cookies
2. URLs Rewriting
3. Hidden Variables
4. Secure Socket Layer [SSL]

1. Cookies
Cookies present a convenient way to store state information on a visitor’s hard disk. A
cookie is a Web server generated container, in which the Web server can automatically store a
small amount of state information on the visitor’s hard disk, through a request to the visitor’s
browser.

After this happens, each time the visitor’s Web browser communicates with the Web server
that sets the cookie, it automatically returns the cookie content back to the Web server in its
request for data.

Advantages
1. Simplest technique of maintaining the state.
2. Cookies are maintained at client side.
3. Cookie information can be extracted from the client request using getCookies() of
HttpSevletRequest

Disadvantages
1. It will not work if cookie is disabled from the browser.
2. Only textual information can be set in Cookie object.

2. URL Rewriting
With URL rewriting approach, the client appends some additional data to the end of each
URL, which identifies the session and the Web server associates the identifier with data it has
stored about the session. In other words, URL rewriting stores session details as part of the URL
itself.

CU IDOL SELF LEARNING MATERIAL (SLM)


108 Advanced Internet Programming

For example, consider the following link in a Web page:

<a href=”/bookshop/logincheck”>

Which can be rewritten as:

<a href=”/bookshop/logincheck;jsessionid=KD327888GMP444”>

When the user clicks the link, the rewritten form of the URL is sent to server as part of the
client’s request. The Web container identifies ;jsessionid=KD327888GMP444 as the SESSION
ID and saves it for obtaining the proper HttpSession object for this client.

Advantages
1. It will always work whether cookie is disabled or not (browser independent).
2. Extra form submission is not required on each page.

Disadvantages
1. It will work only with links.
2. It can send Only textual information.

3. Hidden Form Fields


In commercial applications occasionally it is necessary to return to the Web Server some
client information, which is bound specifically to the application running in the client’s browser.
In case of

Hidden Form Field an invisible textfield is used for maintaining the state of an user. In such
case, we store the information in the hidden field and get it from another servlet. This approach is
better if we have to submit form in all the pages and we don't want to depend on the browser

Example
<form method=”post” Servlet pulls out the SESSION ID from the form
action=”/MyServlets/Books” as follows:
name=”frmBooks”> public void doPost(HttpServletRequest request,
<input type=”text” name=”txtBookName”> HttpServletResponse response) {
<input type=”hidden” name=”hidSessID” …
value=””> String mySessID =
… request.getParamter(“hidSessID”);
</form> …
When the data is submitted to the Servlet, the }

CU IDOL SELF LEARNING MATERIAL (SLM)


Java Servlets - II 109

Explanation
In the above code, the Books Servlet retrieves the SESSION ID from the hidden form field
named hidSessID.

Advantages
1. It will always work whether cookie is disabled or not.

Disadvantages
1. It is maintained at server side.
2. Extra form submission is required on each page.
3. Only textual information can be used.

4. HttpSession Interface
In such case, container creates a session id for each user. The container uses this id to
identify the particular user. An object of HttpSession can be used to perform two tasks:

1. bind objects
2. view and manipulate information about a session, such as the session identifier, creation
time, and last accessed time.
The HttpServletRequest interface provides two methods to get the object of HttpSession:

1. public HttpSession getSession():Returns the current session associated with this request,
or if the request does not have a session, creates one.
2. public HttpSession getSession(boolean create): Returns the current HttpSession
associated with this request or, if there is no current session and create are true, returns a
new session.
3. public String getId(): Returns a string containing the unique identifier value.
4. public long getCreationTime(): Returns the time when this session was created,
measured in milliseconds since midnight January 1, 1970 GMT.
5. public long getLastAccessedTime():Returns the last time the client sent a request
associated with this session, as the number of milliseconds since midnight January 1,
1970 GMT.

CU IDOL SELF LEARNING MATERIAL (SLM)


110 Advanced Internet Programming

Example of Cookies
// index.html public void doPost(HttpServletRequest request,
<form action="servlet1" method="post"> HttpServletResponse response) {

Name:<input type="text" try {


name="userName"/><br/> response.setContentType("text/html");
<input type="submit" value="go"/> PrintWriter out = response.getWriter();
</form> Cookie ck[]=request.getCookies();
// FirstServlet.java out.print("Hello "+ck[0].getValue())
import java.io.*; out.close();
import javax.servlet.*; } catch(Exception e){System.out.println(e) ; }
import javax.servlet.http.*; }}
public class FirstServlet extends HttpServlet {

// SecondServlet.java
import java.io.*; response.setContentType("text/html");
import javax.servlet.*; PrintWriter out = response.getWriter();
import javax.servlet.http.*; Cookie ck[]=request.getCookies();
public class SecondServlet extends HttpServlet out.print("Hello "+ck[0].getValue());
{ out.close();
public void doPost(HttpServletRequest request, } catch(Exception e){System.out.println(e); } } }
HttpServletResponse response) {
try {

5.7 Practical Assignment


1. Develop Java application of Session tracking using URL rewriting using annotation.
2. Develop Java application of a simple servlet program which stores a cookie in the
browser when user first requests for it and then for further requests it displays the cookies
stored.
3. Write a Program to take care of Number Format Exception if user enters values other
than integer for calculating average marks of 2 students. The name of the students and
marks in 3 subjects are taken from the user while executing the program.In the same
Program write your own Exception classes to take care of Negative values and values out
of range (i.e. other than in the range of 0-100)

CU IDOL SELF LEARNING MATERIAL (SLM)


Java Servlets - II 111

5.8 Summary
A servlet is a Java Programming language class that is used to extend the capabilities of
servers that host applications accessed by means of a request-response programming model.
Although servlets can respond to any type of request, they are commonly used to extend the
applications hosted by web servers. It is also a web component that is deployed on the server to
create a dynamic web page.

5.9 Key Words/Abbreviations


 Collaborative: Servlet Collaboration means how one servlet can communicate with
other. Sometimes servlets are to pass the common information that is to be shared
directly by one servlet to another through various invocations of the methods.
 Distributed: Give a share or a unit of (something) to each of a number of recipients.
 Get request: The HTTP GET method requests a representation of the specified resource.
Requests using GET should only retrieve data.
 Post request: The HTTP POST method sends data to the server. It is often used when
uploading a file or when submitting a completed web form.
 Session: Session simply means a particular interval of time. Session Tracking is a way to
maintain state (data) of an user. It is also known as session management in servlet

5.10 Learning Activity


1. Explain Hidden Form Fields
-----------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------
2. Give difference between Get and Post.
-----------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------

CU IDOL SELF LEARNING MATERIAL (SLM)


112 Advanced Internet Programming

5.11 Unit End Questions (MCQs and Descriptive)


A. Descriptive Types Questions
1. Explain how with the help of http protocol client requests are processed.
2. Explain GET and POST request methods of Http protocol using servlet.
3. Explain with example how data can be retrieving from database to servlet.
4. Explain with example how CRUD operation is to be performed with database in servlet.
5. Explain difference between Servlet config and Servlet context.
6. Write a short note on Session Tracking.
7. Explain different methods of Session Tracking.

B. Multiple Choice/Objective Type Questions


1. Which methods are used to bind the objects on HttpSession instance and get the objects?
(a) setAttribute (b) getAttribute
(c) Both A & B (d) None of the above
2. What type of servlets use these methods doGet(), doPost(),doHead, doDelete(),
doTrace()?
(a) Genereic Servlets (b) HttpServlets
(c) All of the above (d) None of the above
3. What are the functions of Servlet container?
(a) Lifecycle management (b) Communication support
(c) Multithreading support (d) All of the above
4. Which object of HttpSession can be used to view and manipulate information about a
session?
(a) session identifier (b) creation time
(c) last accessed time (d) All mentioned above

CU IDOL SELF LEARNING MATERIAL (SLM)


Java Servlets - II 113

5. Which method is used to specify before any lines that uses the PintWriter?
(a) setPageType() (b) setContextType()
(c) setContentType() (d) setResponseType()

Answers
1. (c), 2. (b), 3. (d), 4. (d), 5. (c)

5.12 References
1. https://www.edureka.co/blog/java-servlets
2. https://www.geeksforgeeks.org/introduction-java-servlets/
3. JDBC 4.2, Servlet 3.1, and JSP 2.3 Includes JSF 2.2 and Design Patterns, Black Book,
2ed

CU IDOL SELF LEARNING MATERIAL (SLM)


UNIT 6 AJAX - I

Structure:
6.0 Learning Objectives

6.1 Introduction

6.2 AJAX Architecture

6.3 AJAX Request and Response Objects

6.4 AJAX Technologies

6.5 XML Http Request

6.6 AJAX with Database

6.7 Practical Assignment

6.8 Summary

6.9 Key Words/Abbreviations

6.10 Learning Activity

6.11 Unit End Questions (MCQs and Descriptive)

6.12 References

6.0 Learning Objectives


After studying this unit, you will be able to:

 Explain AJAX architecture


 Define AJAX request & response objects
 Elaborate AJAX technologies

CU IDOL SELF LEARNING MATERIAL (SLM)


AJAX - I 115

 Describe XMLHttpRequest
 AJAX with Database

6.1 Introduction
Ajax is an acronym for Asynchronous Javascript and XML. AJAX is a web development
technique for creating interactive web applications. If you know JavaScript, HTML, CSS, and
XML, then Understanding the AJAX is easy.

6.2 AJAX architecture


 AJAX is AsynchronousJavaScriptAndXML.
 AJAX is not a programming language.
 AJAX just uses a combination of:
 A browser built-in XMLHttpRequest object (to request data from a web server)
 JavaScript and HTML DOM (to display or use the data)
 Ajax is based on HTML, CSS, JavaScript, DOM, and XML.
 HTML/CSS
HTML/CSS is website markup language for defining web page layout, such as fonts
style and colors.
 JavaScript
JavaScript is a web scripting language. JavaScript special object XMLHttpRequest that
was designed by Microsoft. XMLHttpRequest provides an easy way to retrieve data from
web server without having to do full page refresh. Web page can update just part of the
page without interrupting what the users are doing.
 Document Object Model
Document Object Model (DOM) method provides a tree structure as a logical view of
web page.
 XML
XML is a format for retrieve any type of data, not just XML data from the web server.
However you can use other formats such as Plain text, HTML or JSON (JavaScript
Object Notation). and it supports protocols HTTP and FTP. XMLHttpRequest is used
heavily in AJAX programming.

CU IDOL SELF LEARNING MATERIAL (SLM)


116 Advanced Internet Programming

1. Java Script Call Client Browser

Client side User


interface
5. Rander with
HTML/CSS
4. XML Data Plain 2. HTTP
Text/JSON data Request

3. Data Exchange Business Logic for


Database storing, retrieving data

3. Data Exchange Web Server

Fig. 6.1: AJAX Technologies


Above figure (visual diagram) illustrates how AJAX technologies work together to handle
user action. User action are triggers an AJAX response.

 Client side user perform action to generate event that event call to a JavaScript function.
 JavaScript function create XMLHttpRequest object, XMLHttpRequest object specify the
JavaScript callback function.
 JavaScript XMLHttpRequest object call as a asynchronous HTTP request to the Server.
 Web Server process the request and return XML contain data.
 XMLHttpRequest object calls to a callback function along with response from the web
server.
 Client browser updates the HTML DOM representing the web page along with new data.

6.3 AJAX Request and Response Objects


Send a Request To a Server
To send a request to a server, we use the open() and send() methods of the XMLHttpRequest
object:

xhttp.open("GET","ajax_info.txt",true);
xhttp.send();

CU IDOL SELF LEARNING MATERIAL (SLM)


AJAX - I 117

Table 6.1: GET Request


Method Description
Open (method, url, async) Specifies the type of request
method: the type of request: GET or POST url: the server (file) location
async: true (asynchronous) or false (synchronous)
send() Sends the request to the server (used for GET)
send(string) Sends the request to the server (used for POST)

GET or POST?
GET is simpler and faster than POST, and can be used in most cases.

However, always use POST requests when:

 A cached file is not an option (update a file or database on the server).


 Sending a large amount of data to the server (POST has no size limitations).
 Sending user input (which can contain unknown characters), POST is more robust and
secure than GET.

GET Requests
A simple GET request:

Example:
xhttp.open("GET","demo_get.asp",true);
xhttp.send();

In the example above, you may get a cached result. To avoid this, add a unique ID to the
URL:

Example:
xhttp.open("GET","demo_get.asp?t="+ Math.random(),true);
xhttp.send();

If you want to send information with the GET method, add the information to the URL:

Example:
xhttp.open("GET","demo_get2.asp?fname=Henry&lname=Ford",true);
xhttp.send();

CU IDOL SELF LEARNING MATERIAL (SLM)


118 Advanced Internet Programming

POST Requests
A simple POST request:

Example:
xhttp.open("POST","demo_post.asp",true);
xhttp.send();

To POST data like an HTML form, add an HTTP header with setRequestHeader(). Specify
the data you want to send in the send() method:

Example:
xhttp.open("POST","demo_post2.asp",true);
xhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xhttp.send("fname=Henry&lname=Ford");

Table 6.2: POST Request


Method Description
setRequestHeader (header, value) Adds HTTP headers to the request
header: specifies the header name
value: specifies the header value
The url - A File On a Server

The url parameter of the open() method, is an address to a file on a server:

xhttp.open("GET","ajax_test.asp",true);

The file can be any kind of file, like .txt and .xml, or server scripting files like .asp and .php
(which can perform actions on the server before sending the response back).

Asynchronous - True or False?

Server requests should be sent asynchronously.

The async parameter of the open() method should be set to true:

xhttp.open("GET","ajax_test.asp",true);
By sending asynchronously, the JavaScript does not have to wait for the server response, but
can instead:

CU IDOL SELF LEARNING MATERIAL (SLM)


AJAX - I 119

 execute other scripts while waiting for server response


 deal with the response after the response is ready
The onreadystatechange Property

 With the XMLHttpRequest object you can define a function to be executed when the
request receives an answer.
 The function is defined in the onreadystatechange property of the XMLHttpResponse
object:

Example:
xhttp.onreadystatechange=function() {
if(this.readyState==4&&this.status==200) {
document.getElementById("demo").innerHTML=this.responseText;
} };
xhttp.open("GET","ajax_info.txt",true);
xhttp.send();

Synchronous Request

To execute a synchronous request, change the third parameter in the open() method to false:

xhttp.open("GET","ajax_info.txt",false);

Sometimes async = false are used for quick testing. You will also find synchronous requests
in older JavaScript code.

Since the code will wait for server completion, there is no need for an onreadystatechange
function:

Example:
xhttp.open("GET","ajax_info.txt",false);
xhttp.send();
document.getElementById("demo").innerHTML= xhttp.responseText;

AJAX Response Objects


Ajax.Responseis the object passed as the first argument of all Ajax requests callbacks.

This is a wrapper around the native xmlHttpRequest object. It normalizes cross-browser


issues while adding support for JSON via the responseJSON and headerJSON properties.

CU IDOL SELF LEARNING MATERIAL (SLM)


120 Advanced Internet Programming

Properties of the Ajax.Response Object


Table 6.3: AJAX Response Objects
Property Type Description
status Number The HTTP status code sent by the server.
statusText String The HTTP status text sent by the server.
readyState Number The request’s current state. 0 corresponds to “Uninitialized”, 1
to “Loading”, 2 to “Loaded”, 3 to “Interactive” and 4 to
“Complete”.
responseText String The text body of the response.
responseXML document Object The XML body of the response if the content-type of the
or null request is set to application/xml. null otherwise

responseJSON Object, Array The JSON body of the response if the content-type of the
or null request is set to application/json. null otherwise.

headerJSON Object, Array Auto-evaluated content of the X-JSON header if present. null
or null otherwise. This is useful to transfer small amounts of data.

request Object The request object itself (an instance of Ajax.Request or


Ajax.Updater).
transport Object The native xmlHttpRequest object itself.

Example
Following is the example to show the usage of statusand response Text properties –

<html> var container = $('notice');


<head> var content = response.responseText;
<title>Prototype examples</title> container.update(content); }
<script type = "text/javascript" src = function failureFunc(response) {
"/javascript/prototype.js"></script> alert("Call is failed" ); }
<script> </script>
function SubmitRequest() { </head>
new Ajax.Request('/cgi-bin/ajax.cgi', { <body>
method: 'get', <p>Click submit button to see how current
onSuccess: successFunc, notice changes.</p>
onFailure: failureFunc <br />
}); <div id = "notice">Current Notice</div>

CU IDOL SELF LEARNING MATERIAL (SLM)


AJAX - I 121

} <br />
function successFunc(response) { <br />
if (200 == response.status) { <input type = "button" value = "Submit" onclick
alert("Call is success"); = "SubmitRequest();"/>

} </body> </html>

Here is the content of ajax.cgi.

#!/usr/bin/perl
print "Content-type: text/html\n\n";
print "This content is returned by AJAX cgi ";
print "Current Time " . localtime

Methods of the Ajax.Response Object


Table 6.4: Methods of the Ajax.Response Object
Method Type Description
getHeader(name) String or null Returns the value of the requested header if present. null
otherwise.
getAllHeaders() String or null Returns a string containing all headers separated by a
line break.
getResponseHeader(name) String Returns the value of the requested header if present.
Throws an error otherwise. This is just a wrapper
around the xmlHttpRequest object.s native method.
Prefer it’s shorter counterpart getHeader.
getAllResponseHeaders() String Returns a string containing all headers separated by a
line break. Throws an error otherwise. This is just a
wrapper around the xmlHttpRequest object’s native
method. Prefer it.s shorter counterpart getAllHeaders.

Example
Following is the example to show the usage of getAllHeaders() and
getResponseHeader(name) methods –

<html> var content =


<head> response.getResponseHeader('Content-Type');

<title>Prototype examples</title> var container = $(header2);

<script type = "text/javascript" src = container.update(content);


"/javascript/prototype.js"></script> }

CU IDOL SELF LEARNING MATERIAL (SLM)


122 Advanced Internet Programming

<script> </script> </head>


function SubmitRequest() { <body>
new Ajax.Request('/cgi-bin/ajax.cgi', { <p>Click submit button to see the result:</p>
method: 'get', <br />
onSuccess: successFunc <div id = "header1">All Headers</div>
}); <div id = "header2">Content Type</div>
} <br />
function successFunc(response) { <br />
var content = response.getAllHeaders(); <input type = "button" value = "Submit" onclick
var container = $(header1); = "SubmitRequest();"/>

container.update(content); </body> </html>

6.4 AJAX Technologies


AJAX cannot work independently. It is used in combination with other technologies to create
interactive webpages.

DOM
 API for accessing and manipulating structured documents.
 Represents the structure of XML and HTML documents.
 It is used for dynamic display and interaction with data.

CSS
 Allows for a clear separation of the presentation style from the content and may be
changed programmatically by JavaScript

XMLHttpRequest
 JavaScript object that performs asynchronous interaction with the server. For
more visit next page.

XML or JSON
 For carrying data to and from server. JSON (Javascript Object Notation) is like XML but
short and faster than XML.

ASP or JSP
 Server side

CU IDOL SELF LEARNING MATERIAL (SLM)


AJAX - I 123

JavaScript
 Loosely typed scripting language.
 JavaScript function is called when an event occurs in a page.
 Glue for the whole AJAX operation.
 It is used to bring above technologies together.
 It used for Client-side validation and validate user input in an HTML form before
sending the data to a server.

6.5 XMLHttpRequest
The XMLHttpRequest object can be used to exchange data with a server behind the scenes.
This means that it is possible to update parts of a web page, without reloading the whole page.

The XMLHttpRequest object is the key to AJAX. It has been available ever since Internet
Explorer 5.5 was released in July 2000, but was not fully discovered until AJAX and Web 2.0 in
2005 became popular.

XMLHttpRequest (XHR) is an API that can be used by JavaScript, JScript, VBScript, and
other web browser scripting languages to transfer and manipulate XML data to and from a
webserver using HTTP, establishing an independent connection channel between a webpage’s
Client-Side and Server-Side.

The data returned from XMLHttpRequest calls will often be provided by back-end databases.
Besides XML, XMLHttpRequest can be used to fetch data in other formats, e.g. JSON or even
plain text.

Using Ajax XMLHttpRequest object you can make many things easier. So many new
things can’t possible using HEAD request.

This object allows you to making HTTP requests and receives responses from the server
in the background, without requiring the user to submit the page to the server (without round
trip process).

Using DOM to manipulate received data from the server and make responsive contents are
added into live page without user/visual interruptions.

Using this object you can make very user interactive web application.

Following are sequence ofstepfor working with XMLHttpRequest object:

CU IDOL SELF LEARNING MATERIAL (SLM)


124 Advanced Internet Programming

 Define instance of this XMLHttpRequest.


 Create a asynchronous call to a server page, also defining a callback function that will
automatically execute when the server response is received.
 Callback function getting server response.
 DOM manipulate received data and added into live page.
 Create an XMLHttpRequest Object
 All modern browsers (Chrome, Firefox, IE7+, Edge, Safari Opera) have a built-in
XMLHttpRequest object.
Syntax for creating an XMLHttpRequest object:

variable=newXMLHttpRequest();

Example
varxhttp =newXMLHttpRequest();
XMLHttpRequest Methods

 abort()
Cancels the current request.
 getAllResponseHeaders()
Returns the complete set of HTTP headers as a string.
 getResponseHeader(headerName)
Returns the value of the specified HTTP header.
 open(method, URL)
 open(method, URL, async)
 open(method, URL, async, userName)
 open(method, URL, async, userName, password)
Specifies the method, URL, and other optional attributes of a request.

The method parameter can have a value of “GET”, “POST”, or “HEAD”. Other HTTP
methods such as “PUT” and “DELETE” (primarily used in REST applications) may be possible.

The “async” parameter specifies whether the request should be handled asynchronously or
not. “true” means that the script processing carries on after the send() method without waiting for

CU IDOL SELF LEARNING MATERIAL (SLM)


AJAX - I 125

a response, and “false” means that the script waits for a response before continuing script
processing.

 send(content)
Sends the request.
 setRequestHeader(label, value)
Adds a label/value pair to the HTTP header to be sent.

XMLHttpRequest Properties
 onreadystatechange
An event handler for an event that fires at every state change.
 readyState
The readyState property defines the current state of the XMLHttpRequest object.
The following table provides a list of the possible values for the readyState property −
Table 6.5: List of the Possible Values for the Readystate Property
State Description
0 The request is not initialized.
1 The request has been set up.
2 The request has been sent.
3 The request is in process.
4 The request is completed.
 readyState = 0After you have created the XMLHttpRequest object, but before you have
called the open() method.
 readyState = 1 After you have called the open() method, but before you have called
send().
 readyState = 2 After you have called send().
readyState = 3 After the browser has established a communication with the server, but
before the server has completed the response.
 readyState = 4 After the request has been completed, and the response data has been
completely received from the server.
 responseText
Returns the response as a string.

CU IDOL SELF LEARNING MATERIAL (SLM)


126 Advanced Internet Programming

 responseXML
Returns the response as XML. This property returns an XML document object,
which can be examined and parsed using the W3C DOM node tree methods and
properties.
 status
Returns the status as a number (e.g., 404 for “Not Found” and 200 for “OK”).
 statusText
Returns the status as a string (e.g., “Not Found” or “OK”).

6.6 AJAX with Database


AJAX can be used for interactive communication with a database.

Fetching data from MYSQL database in JSP and Servlet with JSON and JQuery.

Fig. 6.2: AJAX with Database


Steps to create ajax example with database through jsp

You need to follow following steps:

1. load the org.json.jar file


2. create input page to receive any text or number
3. create server side page to process the request

Load the org.json.jar file


Include the org.json.jar file inside the WEB-INF/lib directory.

CU IDOL SELF LEARNING MATERIAL (SLM)


AJAX - I 127

create input page to receive any text or number

In this page, we have created a form that gets input from the user. When user press any key
sendInfo() function is called. We have written all theajaxcode inside this function.

We have called the getInfo() function whenever ready state changes. It writes the returned
data in the web page dynamically by the help of innerHTML property.

Ajax Java Example with Database


In this example, we are interacting with the database. You don’t have to make any extra
effort. Only write the database logic in you server side page.

In this example, we have written the server side code inside the index.jsp file.

Steps to create ajax example with database through jsp

You need to follow following steps:

1. load the org.json.jar file


2. create input page to receive any text or number
3. create server side page to process the request
Output
table1.html <formname="vinform">
<html> Enterid:<inputtype="text"name="t1"onkeyup="send
<head> Info()">

<script> </form>

varrequest; <spanid="amit"></span>

functionsendInfo() </body>

{ </html>

varv=document.vinform.t1.value;
varurl="index.jsp?val="+v; index.jsp

if(window.XMLHttpRequest){ <%@pageimport="java.sql.*"%>

request=newXMLHttpRequest(); <%

} Strings=request.getParameter("val");

elseif(window.ActiveXObject){ if(s==null||s.trim().equals("")){

request=newActiveXObject("Microsoft.XML out.print("Pleaseenterid");
HTTP"); }else{
} intid=Integer.parseInt(s);

CU IDOL SELF LEARNING MATERIAL (SLM)


128 Advanced Internet Programming

try{ out.print(id);
request.onreadystatechange=getInfo; try{
request.open("GET",url,true); Class.forName("com.mysql.jdbc.Driver");
request.send(); Connectioncon=DriverManager.getConnection("jd
}catch(e){alert("Unabletoconnecttoserver");} bc:mysql://localhost:3306/mdb","root","root");

} PreparedStatementps=con.prepareStatement("sel
ect*fromempwhereid=?");
functiongetInfo(){
ps.setInt(1,id);
if(request.readyState==4){
ResultSetrs=ps.executeQuery();
varval=request.responseText;
while(rs.next()){
document.getElementById('amit').innerHTM
L=val; out.print(rs.getInt(1)+""+rs.getString(2));

} }

} con.close();

</script> </head> }catch(Exceptione){e.printStackTrace();}

<body> }
%>

This is an example of ajax with database

Fig. 6.3: Example of AJAX with Database

6.7 Practical Assignment


1. Develop a Java application with AJAX to print table of number which is to be accepted
by user through textfield.
2. Develop HelloWorld ajax web application to demonstrate basics of Java with Ajax.

6.8 Summary
AJAX is a developer’s dream, because you can:

 Update a web page without reloading the page


 Request data from a server - after the page has loaded

CU IDOL SELF LEARNING MATERIAL (SLM)


AJAX - I 129

 Receive data from a server - after the page has loaded


 Send data to a server - in the background

6.9 Key Words/Abbreviations


 HTML: Hyper Text Markup Language
 CSS: Cascading Style Sheets
 XML: Extensible Markup Language
 JSP: JavaServer Pages
 JSON: JavaScript Object Notation

6.10 Learning Activity


1. List and explain XMLHttpRequest Properties.
-----------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------
2. List and explain Methods of the Ajax.Response Object
-----------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------

6.11 Unit End Questions (MCQs and Descriptive)


A. Descriptive Types Questions
1. Explain AJAX architecture
2. Write note on AJAX request & response objects
3. Explain AJAX Technologies
4. Explain XMLHttpRequest
5. Explain AJAX with Database

CU IDOL SELF LEARNING MATERIAL (SLM)


130 Advanced Internet Programming

B. Multiple Choice/Objective Type Questions


1. AJAX Stands for:
(a) Asynchronous Javascript and XML
(b) Abstract JSON and XML
(c) Another Java Abstraction for X-Windows
(d) Another Java and XML Library
2. What is AJAX ?
(a) is a programe (b) is a country name
(c) is a football club name (d) is a Language
3. What makes Ajax unique?
(a) It works as a stand-alone Web-development tool.
(b) It works the same with all Web browsers.
(c) It uses C++ as its programming language.
(d) It makes data requests asynchronously.
4. What sever support AJAX ?
(a) SMTP (b) WWW
(c) HTTP (d) FTP
5. __________ Of the following technologies, which one provides the ability to
dynamically interact with Web page layout?
(a) JavaScript. (b) XML.
(c) Document Object Model. (d) HTML.

Answers
1. (a), 2. (a), 3. (d), 4. (c), 5. (c)

6.12 References
1. https://www.w3schools.com/php/php_ajax_intro.asp
2. https://www.geeksforgeeks.org/ajax-introduction/
3. Thomas Powell, 20 March 2008, “Ajax: The Complete Reference Paperback”.

CU IDOL SELF LEARNING MATERIAL (SLM)


UNIT 7 AJAX - II

Structure:
7.0 Learning Objectives

7.1 Introduction

7.2 AJAX -PHP Framework,

7.3 Comment form using AJAX in Java

7.4 Handling XML data using PHP and AJAX, AJAX JSON

7.5 Practical Assignment

7.6 Summary

7.7 Key Words/Abbreviations

7.8 Learning Activity

7.9 Unit End Questions (MCQs and Descriptive)

7.10 References

7.0 Learning Objectives


After studying this unit, you will be able to:

 Describe AJAX -PHP framework


 Comment form using AJAX in Java
 Explain Handling XML data using PHP and AJAX, AJAX JSON

CU IDOL SELF LEARNING MATERIAL (SLM)


132 Advanced Internet Programming

7.1 Introduction
Ajax is an acronym for Asynchronous Javascript and XML. It is used to communicate with
the server without refreshing the web page and thus increasing the user experience and better
performance.

7.2 AJAX -PHP framework


A PHP Ajax framework is able to deal with database, search data, and build pages or parts of

 Page and publish the page or return data to the XMLHttpRequest object.
 Quicknet is an Ajax framework that provides secure data transmission, uses PHP on the
server side. It is designed to develop web applications or websites that use passwords to
identify correct users.
 Using this framework, no cleartext password would be sent over the network or stored in
the server.
 Quicknet supports multi-language, AJAX call, session and password management, +
34 A tmodular structure, XML content and Javascript animation where PHP is used on
the server side. AjaxAC :
 It is an open source framework written in PHP, used to develop/create/generate AJAX
applications.
 The fundamental idea behind AJAX (Asynchronous Javascript and XML) is to use the
XMLHttpRequest object to change a web page state using background HTTP
subrequests without reloading the entire page.

Features:
1. All application code is self contained in a single class (also additional Javascript libraries)
2. Calling PHP file/HTML page is very clean. All that is required is creating the application
classes, then referencing the application Javascript and attaching any required elements
to the application.
3. Built in functionality for easy handling Javascript events.
4. Easy to hook in to existing PHP Classes or MySQL database for returning data from
subrequests.

CU IDOL SELF LEARNING MATERIAL (SLM)


AJAX - II 133

How to Create an PHP Ajax application


We will create a simple application that allows users to search for popular PHP MVC
frameworks.

Our application will have a text box that users will type in the names of the framework.

We will then use mvc AJAX to search for a match then display the framework’s complete
name just below the search form.

Step 1: Creating the index page


Index.php

<html> MVC Framework</b></p>


<head> <form method="POST"
<title>PHP MVC Frameworks - Search action="index.php">
Engine</title> <p><input type="text" size="40"
<script type="text/javascript" id="txtHint" onkeyup="showName(this.value)">
src="/auto_complete.js"></script> </p>

</head> </form>

<body> <p>Matches: <span


id="txtName"></span></p>
<h2>PHP MVC Frameworks - Search
Engine</h2> </body>

<p><b>Type the first letter of the PHP </html>

HERE,
 “onkeyup="showName(this.value)"” executes the JavaScript function show Name
everytime a key is typed in the textbox.
This feature is called auto complete
Step 2: Creating the frameworks page
frameworks.php

<?php strlen($name)))) {
$frameworks = array("CodeIgniter","Zend if ($match == "")
Framework","Cake PHP","Kohana") ; {
$name = $_GET["name"]; $match = $frameworks[$i]; }
if (strlen($name) > 0) else {
{ $match = $match . " , " .
$match = ""; $frameworks[$i]; }
for ($i = 0; $i < count($frameworks); $i++) }
{ } }

CU IDOL SELF LEARNING MATERIAL (SLM)


134 Advanced Internet Programming

if (strtolower($name) == echo ($match == "") ? 'no match found' :


strtolower(substr($frameworks[$i], 0, $match;
?>
Step 3: Creating the JS script
auto_complete.js

function showName(str) { xmlhttp.onreadystatechange=function() {


if (str.length == 0){ //exit function if nothing if (xmlhttp.readyState == 4 && xmlhttp.status
has been typed in the textbox == 200){
document.getElementById("txtName").in document.getElementById("txtName").inn
nerHTML=""; //clear previous results erHTML=xmlhttp.responseText;
return; } }
if (window.XMLHttpRequest) {// code for }
IE7+, Firefox, Chrome, Opera, Safari xmlhttp.open("GET","frameworks.php?name="+st
xmlhttp=new XMLHttpRequest(); r,true);
} else {// code for IE6, IE5 xmlhttp.send();
xmlhttp=new }
ActiveXObject("Microsoft.XMLHTTP"); }
HERE,

 “if (str.length == 0)” check the length of the string. If it is 0, then the rest of the script is
not executed.
 “ if (window.XMLHttpRequest) … ” Internet Explorer versions 5 and 6 use
ActiveXObject for AJAX implementation. Other versions and browsers such as Chrome,
FireFox use XMLHttpRequest. This code will ensure that our application works in both
IE 5 & 6 and other high versions of IE and browsers.
 “ xmlhttp.onreadystatechange=function … ” checks if the AJAX interaction is complete
and the status is 200 then updates the txtName span with the returned results.

Step 4: Testing our PHP Ajax application

Fig. 7.1: PHP Ajax - 1

CU IDOL SELF LEARNING MATERIAL (SLM)


AJAX - II 135

Assuming you have saved the file index.php In phututs/ajax, browse to the
URL http://localhost/phptuts/ajax/index.php

Type the letter C in the text box you will get the following results.

Fig. 7.2: PHP Ajax - 2


The above example demonstrates the concept of AJAX and how it can help us create rich
interaction applications.

7.3 Comment form using AJAX in Java


The form data is saved in the database and a list of all posted comments are shown below
the comment form.

Steps to create comment form example using AJAX in Java

You need to follow following steps:

1. Create table in database


2. load the org.json.jar file
3. Create comment form
4. Create server side page to save the form data and print all posted comments

Create Table in Database


In this example, we are using oracle 10g database. The table structure is given below:

Load the org.json.jar file


Download this example, we have included the org.json.jar file inside the WEB-INF/lib
directory.

CU IDOL SELF LEARNING MATERIAL (SLM)


136 Advanced Internet Programming

Create comment form

In this page, we have created a form that gets input from the user. When user clicks on the
Post Comment button, postComment() function is called. We have written all the ajax code inside
this function.

index.html
<!DOCTYPE html> }//end of function
<html> request.open("GET",url,true);
<head> request.send();
<script> }catch(e){alert("Unable to connect to server");}
var request; }
function postComment() { </script> </head>
var comment=document.commentform.com <body>
ment.value; document.getElementById('mylocation').innerHTM
var email=document.commentform.email.val L=val; }
ue; <h1>Comment Form</h1>
var url="index.jsp?comment="+comment+" <form name="commentform">
&email="+email;
Enter Comment:<br/>
if(window.XMLHttpRequest) {
<textarea name="comment" style="width:300px;he
request=new XMLHttpRequest(); ight:100px" required>
} </textarea> <br/>
else if(window.ActiveXObject) { Enter Email:<br/>
request=new ActiveXObject("Microsoft.XML <input type="text" name="email" required/><br/><b
HTTP"); r/>
} <input type="button" value="Post Comment" oncli
try { ck="postComment()">
request.onreadystatechange=function() { </form>
if(request.readyState==4) { <span id="mylocation"></span>
var val=request.responseText; </body> </html>
Create server side page to process the request

In this jsp page, we are writing the database code to save the comment and print all
comments.

CU IDOL SELF LEARNING MATERIAL (SLM)


AJAX - II 137

index.jsp
<!DOCTYPE html> PreparedStatement ps=con.prepareStatemen
<html> t("insert into usercomment(comment1,email)
values(?,?)"); ps.setString(1,comment);
<head>
ps.setString(2,email);
<style>
int i=ps.executeUpdate();
div.box{margin:2px;border:1px solid pink;padding:
10px;background-color:#e3e3e3} PreparedStatement ps2=con.prepareStateme
nt("select * from usercomment order by id de
</style> sc");
</head> ResultSet rs=ps2.executeQuery();
<body> out.print("<hr/><h2>Comments:</h2>");
<%@ page import="java.sql.*" %> while(rs.next()){
<% out.print("<div class='box'>");
String comment=request.getParameter("comment out.print("<p>"+rs.getString(2)+"</p>");
");
out.print("<p><strong>By: "+rs.getString(3)+"
String email=request.getParameter("email"); </strong></p>");
if(comment==null||email==null||comment.trim().eq out.print("</div>");
uals("")||email.trim().equals("")){
} con.close();
out.print("<p>Please write comment</p>");
}catch(Exception e){out.print(e);}
}else{
}//end of else
try{
%>
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("j </body> </html>
dbc:oracle:thin:@localhost:1521:xe","system""ora
cle");

7.4 Handling XML Data using PHP and AJAX, AJAX JSON
Files and various databases are useful for storing data, but as they get bigger, they might as
well become easier to get lost in them. Finding information that you have to use in some
particular moment, manually might take ages. The problem is that when you need something, you
usually need it fast.

Making PHP read XML file can help you retrieve data quickly. XML is one of the most
common formats for keeping data strings. If you prefer it as well, you can use AJAX to read
XML files. In other words, AJAX can help you connect with the XML document that holds
information and quickly find the exact data.

CU IDOL SELF LEARNING MATERIAL (SLM)


138 Advanced Internet Programming

Ajax XML Example


Using with Ajax we can parser xml from local directory as well as servers, Below example
demonstrate how to parser xml with web browser.

<html> document.getElementById("txtHint").innerHTM
<head> L = xmlhttp.responseText;

<script> } }

function showCD(str) { xmlhttp.open("GET","getcourse.php?q="+str,tr


ue);
if (str == "") {
xmlhttp.send(); }
document.getElementById("txtHint").innerHTML
= ""; </script> </head> <body>

return; <form>

} Select a Course:

if (window.XMLHttpRequest) { <select name = "cds" onchange =


"showCD(this.value)">
// code for IE7+, Firefox, Chrome, Opera, Safari
<option value = "">Select a course:</option>
xmlhttp = new XMLHttpRequest();
<option value = "Android">Android </option>
} else {
<option value = "Html">HTML</option>
// code for IE6, IE5
<option value = "Java">Java</option>
xmlhttp = new
ActiveXObject("Microsoft.XMLHTTP"); <option value = "Microsoft">MS
technologies</option>
}
</select> </form>
xmlhttp.onreadystatechange = function() {
<div id = "txtHint"><b>Course info will be
if (xmlhttp.readyState == 4 && xmlhttp.status == listed here...</b></div>
200) {
</body> </html>
The above example will call getcourse.php using with GET method. getcourse.php file
loads catalog.xml. getcourse.php is as shown below –

<?php } } }
$q = $_GET["q"]; $cd = ($y->childNodes);
$xmlDoc = new DOMDocument(); for ($i = 0;$i<$cd->length;$i++) {
$xmlDoc->load("catalog.xml"); if ($cd->item($i)->nodeType == 1) {
$x = $xmlDoc- echo("<b>" . $cd->item($i)->nodeName . ":</b>
>getElementsByTagName('COURSE'); ");
for ($i = 0; $i<=$x->length-1; $i++) { echo($cd->item($i)->childNodes->item(0)-
if ($x->item($i)->nodeType == 1) { >nodeValue);

if ($x->item($i)->childNodes->item(0)- echo("<br>");

CU IDOL SELF LEARNING MATERIAL (SLM)


AJAX - II 139

>nodeValue == $q) { } } ?>


$y = ($x->item($i)->parentNode);
Catalog.xml

XML file having list of courses and details. This file is accessed by getcourse.php

<CATALOG> <SUBJECT>
<SUBJECT> <COURSE>Java</COURSE>
<COURSE>Android</COURSE> <COUNTRY>India</COUNTRY>
<COUNTRY>India</COUNTRY> <COMPANY>TutorialsPoint</COMPANY>
<COMPANY>TutorialsPoint</COMPANY> <PRICE>$20</PRICE>
<PRICE>$10</PRICE> <YEAR>2015</YEAR>
<YEAR>2015</YEAR> </SUBJECT>
</SUBJECT> <SUBJECT>
<SUBJECT> <COURSE>Microsoft</COURSE>
<COURSE>Html</COURSE> <COUNTRY>India</COUNTRY>
<COUNTRY>India</COUNTRY> <COMPANY>TutorialsPoint</COMPANY>
<COMPANY>TutorialsPoint</COMPANY> <PRICE>$25</PRICE>
<PRICE>$15</PRICE> <YEAR>2015</YEAR>
<YEAR>2015</YEAR> </SUBJECT>
</SUBJECT> </CATALOG>
It will produce the following result −

7.5 Practical Assignment


1. Design a application to Retrieve the content of an ASP file.
2. Design a application to Retrieve the content from database.

7.6 Summary
AJAX allows web pages to be updated asynchronously by exchanging small amounts of data
with the server behind the scenes. This means that it is possible to update parts of a web page,
without reloading the whole page.

CU IDOL SELF LEARNING MATERIAL (SLM)


140 Advanced Internet Programming

Classic web pages, (which do not use AJAX) must reload the entire page if the content
should change.

7.7 Key Words/Abbreviations


 Quicknet: Quicknet is an Ajax framework (using XMLHttpRequest in JavaScript)
designed to develop web applications or websites that use passwords to identify correct
users. It uses PHP on the server side, and JavaScript on the client side.
 PHP: Hypertext Preprocessor

7.8 Learning Activity


1. List and explain the steps for email finder.
-----------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------
2. Explain features of AJAX –PHP framework.
-----------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------

7.9 Unit End Questions (MCQs and Descriptive)


A. Descriptive Types Questions
1. Explain AJAX architecture.
2. Write note on AJAX request & response objects.
3. Explain AJAX Technologies.
4. Explain XMLHttpRequest.
5. Explain AJAX with Database.

B. Multiple Choice/Objective Type Questions


1. AJAX based on__________.
(a) JavaScript and XML (b) JavaScript and Java
(c) VBScript and XML (d) JavaScript and HTTP requests

CU IDOL SELF LEARNING MATERIAL (SLM)


AJAX - II 141

2. What combination of technologies gives AJAX its name?


(a) ASP and XAML
(b) Asynchronous JavaScript and XML
(c) Autonomic Computing and DHTML
(d) Atlas and XML
3. What does the tag do?
(a) Enclose text to be displayed by non-JavaScript browsers.
(b) Prevents scripts on the page from executing.
(c) Describes certain low-budget movies.
(d) None of the above
4. __________ JavaScript is also called client-side JavaScript.
(a) Microsoft (b) Navigator
(c) LiveWire (d) Native
5. __________ JavaScript is also called server-side JavaScript
(a) Microsoft (b) Navigator
(c) LiveWire (d) Native

Answers
1. (a), 2. (b), 3. (a), 4. (b), 5. (c)

7.10 References
1. https://www.tutorialspoint.com/ajax/index.htm
2. https://www.enotes.com/topics/ajax
3. Rebecca M..Riordan,” Head First Ajax OREILLY”.

CU IDOL SELF LEARNING MATERIAL (SLM)


UNIT 8 JAVA SERVER PAGES

Structure:
8.0 Learning Objectives

8.1 Introduction

8.2 What is JSP?

8.3 Architecture of JSP

8.4 Elements of JSP

8.5 Scripting Elements

8.6 Directives and Actions

8.7 Session Management

8.8 JSP Configuration

8.9 Implicit Objects

8.10 Filter

8.11 JSP in XML and Custom Tag Libraries

8.12 Practical Assignment

8.13 Summary

8.14 Key Words/Abbreviations

8.15 Learning Activity

8.16 Unit End Questions (MCQs and Descriptive)

8.17 References

CU IDOL SELF LEARNING MATERIAL (SLM)


Java Server Pages 143

8.0 Learning Objectives


After studying this unit, you will be able to:

 Describe architecture of JSP andelements of JSP


 Discuss Scripting elements,Directives & actions, and JSPconfiguration
 Explain white space preservation,implicit objects, and Filter
 Elaborate JSP in XML and customtag libraries.

8.1 Introduction
JSP technology is used to create dynamic web applications. JSP pages are easier to maintain
then a Servlet. JSP pages are opposite of Servlets as a servlet adds HTML code inside Java code,
while JSP adds Java code inside HTML using JSP tags. Everything a Servlet can do, a JSP page
can also do it.

JSP enables us to write HTML pages containing tags, inside which we can include powerful
Java programs. Using JSP, one can easily separate Presentation and Business logic as a web
designer can design and update JSP pages creating the presentation layer and java developer can
write server side complex computational code without concerning the web design. And both the
layers can easily interact over HTTP requests.

8.2 What is JSP?


Definition: Java Server Pages (JSP) is a Java technology that allows software developers to
dynamically generate HTML, XML or other types of documents in response to a Web client
request. The technology allows Java code and certain pre-defined actions to be embedded into
static content. Java Server Pages or JSP for short is Sun's solution for developing dynamic
websites.

JSP Pages Typically Comprise of


1. Static HTML/XML components.
2. Special JSP tags
3. Optionally, snippets of code written in the Java programming language called
“scriptlets.”

CU IDOL SELF LEARNING MATERIAL (SLM)


144 Advanced Internet Programming

Java Server Pages (JSP) is a Java-based technology that simplifies the process of developing
dynamic websites using JSP, web designers and developer can quickly incorporate dynamic
elements into web pages using embedded Java and markup tags. The tags allow the user to
present data and java object (Applet/JDBC/Java bean/servlet etc.) allow storing business logic.

Problems with Servlets


1. Detailed java programming knowledge is needed to develop and maintain all aspects of
applets, since the processing code and HTML elements are combined together.
2. Changing the look and feel of the applet or adding support for a new type of client, the
server code need to be updated and recompiled.
3. For writing servlets, HTML must be embedded into the servlet code, which is time
consuming and error prone.

Advantage of JSP Technology


1. Portability: Since it is based on Java, JSP technology is platform independent. To
run .jsp files, we need a JSP engine (programs used to run .jsp files). This engine can be
built for different type of web-servers to make them execute jsp files.
2. Reuse of Components & Tag Libraries: JSP technology emphasizes the use of
reusable component such as Java Bean Components, Enterprise Java Bean Components
etc. Data is the main reason of dynamic contents. The components may contain the code
to obtain the data from databases or text files thus offering different contents to JSP files.
It supports different types of markup languages such as HTML/DHTML/XML. JSP also
supports user-defined tags. For user-defined tags, the control is transferred to classes that
contain the code, which should be executed. Any type of code such as JDBC, File
Handling etc. can be included in these classes. Thus a JSP page developer need not have
considerable knowledge of Java.
3. Separation of Static & Dynamic Content: Using HTML pages, we can send only static
contents to web clients. If we use servlets, then the entire HTML code is required to be
written in println statement, which is tedious. It also makes the entire page to be dynamic.
JSP allows you to include dynamic content into the static contents separating the two
from each other. The static contents are provided using HTML tags and dynamic
contents are generated using scriptlets, user-defined tags etc. It also follows popular
MVC (Model-View-Control) Design Pattern.
4. Suitable for N-Tier Architecture: Because of features such as, platform-independence,
support for different types of servers (web servers, database servers etc.), markup

CU IDOL SELF LEARNING MATERIAL (SLM)


Java Server Pages 145

languages, reuse of objects in the form of components etc. it is best suited for N-Tier
architecture.
5. Performance: JSP pages are automatically compiled before execution. So it frees the job
of programmer to explicitly compile the program. After compilation, the page is kept in
memory for certain duration to serve for next requests. Thus the compilation activity is
not done for every request (unless there are modifications in the page).

Features of JSP
(a) Separation of static from dynamic content: In JSP, the logic to generate the dynamic
content is kept separate from the static presentation templates by encapsulating it within
external JavaBeans components. These are then used by the ISP page using special tags
and scriptlets. When a page designer makes any changes to the presentation template, the
JSP page is automatically recompiled and reloaded into the web server by the JSP engine.
(b) Write Once Run Anywhere: JSP pages can be moved easily across platforms, and
across web servers, without any changes.
(c) Web Server Support: With Apache, many other popular web servers like Netscape, and
Microsoft IIS can also be easily enabled with JSP.
(d) Platform Independent: Runs on all Java-enabled platforms.
(e) Scripting: Uses the Java programming language or JavaScript.
(f) Database Access: Uses JDBC for data access.
(g) Customizable Tags: JSP is extensible with custom tag libraries.

8.3 Architecture of JSP


JSPs are HTML page with special JSP tags embedded. These JSP tags can contain Java code.
The JSP file extension is .jsp rather than .html. The JSP engine parses the .jsp and creates a Java
servlet source file. It then compiles the source file into a class file, this is done the first time and
this is why the JSP is probably slower when first time it is accessed. Any time after this the
special compiled servlet is executed and is therefore returns faster.

CU IDOL SELF LEARNING MATERIAL (SLM)


146 Advanced Internet Programming

Web Server

Web Browser JSP


1. Web browser Request
2. JSP request sent to Web File
server
3. Send to JSP Servlet Engine

9. HTML sent to browser


JSP Servlet Engine

4. Parse JSP file

INTERNET 5. Generate Servlet


source code

6. Compile Servlet source


code into class.

7. Instantiate Servlet

8. HTML (Servlet output)

Fig. 8.1: Architecture of JSP

Steps Required for a JSP Request


1. The user goes to a web site made using JSP. The user goes to a JSP page (ending
with .jsp).
2. The web browser makes the request via the Internet.
3. The JSP request gets sent to the Web server.
4. The Web server recognizes that the file required is special (.jsp), therefore passes the JSP
file to the JSP Servlet Engine.
5. If the JSP file has been called the first time, the JSP file is parsed, otherwise go to step 7.
6. The next step is to generate a special Servlet from the JSP file. The entire HTML code is
converted to println statements.
7. The Servlet source code is compiled into a .class file.
8. The Servlet is instantiated, calling the init and service methods.
9. HTML from the Servlet output is sent via the Internet.
10. HTML results are displayed on the user's web browser.

8.4 Elements of JSP


There are three types of JSP elements you can use: directive, action, and scripting. A new
construct added in JSP 2.0 is an Expression Language (EL) expression

 JSP Scriptlet
 JSP Declaration

CU IDOL SELF LEARNING MATERIAL (SLM)


Java Server Pages 147

 JSP Expression
 JSP Comments

JSP Scripting Elements


JSP Scripting Elements are used for writing the Java Code inside the JSP page. There are
different types of scripting elements these elements are used for various purposes. Following are
the scripting elements :

 JSP Scriptlet element/tag: A scriptlet tag is denoted by the special characters <% %>.
The special characters '<%' specifies the starting of the scriptlet tag and '%>' specifies
end of scriptlet. On the JSP page Java Code is written inside it.

Syntax:

<% java code %>

Example: implements JSP scriptlet tag

<html>
<head> <title>
My First JSP Page
</title> </head>
<body>
<% out.print("Welcome to JSP world"); %>
</body> </html>

Output:
Welcome to JSP world

JSP Declaration element/tag: The declaration tag is denoted by the special characters
<%! %>. The special character '<%!' specifies the start of the declaration and '%>' specifies the
end of the declaration. Declaration element is used to declare the fields, methods to use inside the
JSP page. These declaration element helps developer to declare fields, methods like in Servlet
how they can declare.

Syntax of Declaration Tag


<%! Declaration %>

CU IDOL SELF LEARNING MATERIAL (SLM)


148 Advanced Internet Programming

Example: Declaring a method inside Declaration Tag

<html>
<head>
<title>JSP Declaration Tag</title> </head>
<body>
<%! int square(int a)
{
return a * a;
} %>
<% = "Square of 5 is: "+square(5) %>
</body> </html>

Output:
Square of 5 is: 25

JSP
Expression element/tag: Then expression tag is denoted by the special characters
<%= %>. The special character '<%= specifies the starting of the expression and '%>' specifies
the end of the expression. The expression tag is used to set the output. The expression is used like
the 'out' implicit object in JSP.

JSP Expression Tag


 JSP expression tag is used to write the client response to the output stream.
 Expression tag keeps the expression that can be used as an argument to the output stream
method.

Syntax:

<%= Java Expression %>

Example: Displays current date using Expression tag

<%@page contentType="text/html" import="java.util.*" %>


<html>
<head>
<title>JSP Expression Tag</title> </head>
<body>
<h2>Current Date</h2>
<p>
Today's Date: <%= (new java.util.Date()).toLocalString() %>

CU IDOL SELF LEARNING MATERIAL (SLM)


Java Server Pages 149

</p>
</body> </html>

Output:
Today’s Date: 03-Aug-2016 10:52:21

JSP Directive Elements


Directive elements in JSP provides the special information to the JSP engine. It gives the
information about the JSP page. Each JSP page goes through the two phases i.e. translation phase
and request time phase. At the translation phase JSP page is translated into a Servlet. The JSP
engine translates the JSP page into a Servlet, directive elements are handled at the translation time.
These directives are translated to the Servlet only for once, until there is no changes made to the
directive elements in the Servlet.

JSP Directive Elements can be declared within the following special characters '<%@ %>'.
Syntax for using directive in the JSP page is as follows :

<%@ directiveName attr1="value1" attr2="value2" %>

JSP Standard Action Elements


JSP Action Elements are used to take action on the basis of some information. These action
elements can create, modify or use the other objects. Action elements are coded with the strict
syntax they are used to apply the built-in functionality. Action elements are represented as
<jsp:tagName> </jsp:tagName>. Code is written inside these tags, the <jsp:tagName> specifies
the starting of the action tag where as the action tag is ends with </jsp:tagName>. When you are
not required to defined the body of the tag you may end up the action tag by <jsp:tagName/>

JSP Comment Elements


JSP comment elements are used to hide your code from the “view page source”. However,
you can use HTML comment tags in JSP page but, when user of your website will choose the
“view page source” then they can see your commented code. The JSP comment is denoted by the
special character <%-- --%>. The special character '<%--' specifies the opening comment element
and the special character '--%>' specifies the end of the comment tag.

HTML comment tag is denoted by the special characters '<!-- -->' where, '<!--' specifies the
start tag and '-->' specifies the end tag.

CU IDOL SELF LEARNING MATERIAL (SLM)


150 Advanced Internet Programming

Syntax:

<%-- JSP comment --%>

Example: JSP comment tag

<html>
<head>
<title>JSP Comments</title> </head>
<body>
<%-- this will hide on JSP page --%>
</body> </html>

8.5 Scripting Elements


JSP Scriptlet
 Scriptlet tag allows to write Java code into JSP file.
 JSP container moves statements in _jspservice() method while generating servlet from
jsp.
 For each request of the client, service method of the JSP gets invoked hence the code
inside the Scriptlet executes for every request.
 A Scriptlet contains java code that is executed every time JSP is invoked.

Syntax of Scriptlet Tag

<% java code %>

Here <%%> tags are scriplets tag and within it, we can place java code.

Example:

<html>
<head>
<title>My First JSP Page</title>
</head>
<%
int count = 0;
%> </head>
<body>

CU IDOL SELF LEARNING MATERIAL (SLM)


Java Server Pages 151

Page Count is <% out.println(++count); %>


</body> </html>

In a scripting element, if the characters %> needs to be used, escape the greater than sign
with a backslash:

<% String message = “This is the %\>”; %>

The backslash before the expression acts as an escape character, informing the JSP engine to
deliver the expression verbatim instead of evaluating it.

There are a number of special constructs used in various cases to insert characters that would
otherwise be treated specially, they are as follows:
Table 8.1: Escape Characters
Escape Characters Description
\’ A single quote in an attribute that uses single quotes.
\” A double quotes in an attribute that uses double quotes.
\\ A backslash in an attribute that uses backslash.
%\> Escaping the scripting end tag with a backslash.
<\% Escaping the scripting start tag with a backslash.
\$ Escaping the dollar sign [dollar sign is used to start an EL expression] with a
backslash

Example
Solutions:

<% String message = ‘Escaping \’ single quote’;%>


<% String message = “Escaping \” double quote”;%>
<% String message = “Escaping \\ backslash”;%>
<% String message = “Escaping %\> scripting end tag”;%>
<% String message = “Escaping <\% scripting start tag”;%>
<% String message = “Escaping \$ dollar sign”;%>

As an alternative to escaping quote characters, the character entities &apos; and &quot; can
also be used.

CU IDOL SELF LEARNING MATERIAL (SLM)


152 Advanced Internet Programming

8.6 Directives and Actions Directives in JSP


 Directives are instructions to the JSP container that describe what code should be
generated.
 They have the general form <%@ directive-name [attribute= ” value ” attribute= ”
value” ….] %>
 Zero or more spaces, tabs, and newline characters can appear after the opening <%@ and
before the ending %>, and one or more whitespace characters can appear after the
directive name and between the attributes / value pairs. The only restriction is that the
opening <%@ tag must be in the same physical file as the ending %> file.
 Three standard directives:
– page
– include
– taglib

Page Directive
Page directive is used to specify attribute for the JSP page as a whole.

The page directive lets you control the structure of the servlet by importing classes,
customizing the servlet superclass, setting the content type and the like

The page directive can be placed anywhere within the document.

Syntax

<% @ page [ attribute1=”value1”.. attributen=’valuen”] %>

Include Directive
Include directives includes an external document in the page.

The include directive must be placed in the document at the point at which you want the file
to be appended.

The <%@ include %> directive inserts a file of text or code in a JSP file at translation time,
when the JSP file is compiled. When you use the <%@ include %> directive, the include process
is static. A static include means that the text of the included file is added to the JSP file. The
included file can be a JSP file, HTML file, or text file. If the included file is a JSP file, its JSP
elements are parsed and their results included (along with any other text) in the JSP file.

CU IDOL SELF LEARNING MATERIAL (SLM)


Java Server Pages 153

Syntax:

<%@ include file=“file _name” %>

Taglib Directive
The taglib directive has been introduced in JSP 1.1, which can be used to define custom
markup tags.

This directive requires that a prefix be specified (much like a namespace in C++) and the
URI for the tag library description.

Example :-<%@ taglib prefix="myprefix" uri="taglib/mytag.tld" %>


Example:-<%@ taglib uri="http://www.jspcentral.com/tags" prefix="public" %> <public:loop>
. </public:loop>

Description
The <%@ taglib %> directive declares that the JSP file uses custom tags, names the tag
library that defines them, and specifies their tag prefix. Here, the term custom tag refers to both
tags and elements.

Attributes
1. uri= “URIToTagLibrary”: The Uniform Resource Identifier (URI) that uniquely names
the set of custom tags associated with the named tag prefix.
2. prefix= “tagPrefix”: The prefix that precedes the custom tag name, for example, public
in <public:loop>. Empty prefixes are illegal.

Action in JSP
 Actions allow you to perform server-side resources like JSP pages and servlets without
the Java coding. Although the same can be achieved using Java code within scriptiets,
but using action tags help reusability of your components and enhances the
maintainability of your application.
 The JSP Actions are XML tags that can be used in the JSP page.
 Action tag is used to transfer the control between pages and is also used to enable the use
of server side JavaBeans.

CU IDOL SELF LEARNING MATERIAL (SLM)


154 Advanced Internet Programming

List of JSP Actions


 jsp:include
The jsp:include action works as a subroutine that temporarily passes the request and
responses to the specified SPIServlet. Control is then returned back to the current JSP
page.
The jsp:include action can be used to redirect the request to any static or dynamic
resource that is in the same context as the calling JSP page.

Syntax:- <jsp:include page=”relativeURL”/>

 jsp:param:
The jsp:param action is used to add the specific parameter to current request. The
jsp:param tag can be used inside a jsp:include, jsp:forward or jsp:params block.
Syntax:

<jsp:inctude page=.”relativeURL”>
<jsp:param name=”parameterName” vatue=” parameterValue” />
</jsp:include>

 jsp:forward:
With the <jsp:forward> tag, you can redirect the request to any JSP, servlet, or static
HTML page within the same context as the invoking page. This effectively halts
processing of the current page at the point where the redirection occurs, although all
processing up to that point still takes place.
The jsp:forward tag is used to hand off the request and response to another JSP or serviet.
In this case the request never returns to the calling JSP page.
Syntax:

<jsp:forward page=”somePage.jsp” />

A <jsp:forward> tag may also have jsp:param subelements that can provide values for
some elements in the request used in the forwarding
Syntax:

<jsp:forward page=”Some Page”>


<jsp:param name=”name1” value=”value1”>
</ jsp:forward page >

CU IDOL SELF LEARNING MATERIAL (SLM)


Java Server Pages 155

 jsp:plugin
In older versions of Netscape Navigator and Internet Explorer, different tags were used
to embed applet. The jsp:plugin tag actually generates the appropriate HTML code to
embed the Applets correctly
 jsp:fallback
The jsp:fallback tag is used to specify the message to be shown on the browser is not
supported by browser.
Example:

<jsp:fallback> Unable to load applet </jsp:fallback>

 jsp:getProperty
Gets the value of a Bean property so that you can display it in a result page.
Syntax

<jsp:getProperty name="beanInstanceName" property="propertyName" />

The <jsp:getProperty> element gets a Bean property value using the property's getter
methods and displays the property value in a JSP page. You must create or locate a Bean
with <jsp:useBean> before you use <jsp:getProperty>.
 jsp:setProperty
Sets a property value or values in a Bean.
Syntax:

<jsp:setProperty
name="beanInstanceName"
{
property= "*" |
property="propertyName" [ param="parameterName" ] |
property="propertyName" value="{string | <%= expression %>}"
} />

The <jsp:setProperty> element sets the value of one or more properties in a Bean, using
the Bean's setter methods. You must declare the Bean with <jsp:useBean> before you set
a property value with <jsp:setProperty>. Because <jsp:useBean> and <jsp:setProperty>
work together, the Bean instance names they use must match (that is, the value of name
in <jsp:setProperty> and the value of id in <jsp:useBean> must be the same).

CU IDOL SELF LEARNING MATERIAL (SLM)


156 Advanced Internet Programming

jsp:useBean
The component model for JSP technology is based on JavaBeans component architecture.

JavaBeans components are Java objects which follow a well-defined pattern: the bean
encapsulates its properties by declaring them private provides public accessor (getter/setter)
methods for reading and modifying values.

Before you can access a bean within a JSP page, it is necessary to identify bean and obtain a
reference to it. The <jsp:useBean> tag tries to reference to an existing instance using the specified
id and scope.

The jsp:useBean tag is used either to instantiate an object of Java Beanre-use existing java
bean object.

Syntax:

<jsp:use8ean id=”beanlnstanceName” scope=”page/request/session/appLication”


class=’package.class”type=package.ctass”/beanName”package.cLass” type=”package.class”
</jsp:useBean>

8.7 Session Management


In session management whenever a request comes for any resource, a unique token is
generated by the server and transmitted to the client by the response object and stored on the
client machine as a cookie. We can also say that the process of managing the state of a web based
client is through the use of session IDs. Session IDs are used to uniquely identify a client browser,
while the server side processes are used to associate the session ID with a level of access. Thus,
once a client has successfully authenticated to the web applicatiion, the session ID can be used as
a stored authentication voucher so that the client does not have to retype their login information
with each page request. Now whenever a request goes from this client again the ID or token will
also be passed through the request object so that the server can understand from where the request
is coming. Session management can be achieved by using the following thing.

1. Cookies: cookies are small bits of textual information that a web server sends to a
browser and that browsers returns the cookie when it visits the same site again. In cookie
the information is stored in the form of a name, value pair. By default the cookie is
generated. If the user doesn't want to use cookies then it can disable them.
2. URL rewriting: In URL rewriting we append some extra information on the end of each
URL that identifies the session. This URL rewriting can be used where a cookie is

CU IDOL SELF LEARNING MATERIAL (SLM)


Java Server Pages 157

disabled. It is a good practice to use URL rewriting. In this session ID information is


embedded in the URL, which is recieved by the application through Http GET requests
when the client clicks on the links embedded with a page.
3. Hidden form fields: In hidden form fields the html entry will be like this : <input type
="hidden" name = "name" value="">. This means that when you submit the form, the
specified name and value will be get included in get or post method. In this session ID
information would be embedded within the form as a hidden field and submitted with the
Http POST command.
In JSP we have been provided a implicit object session so we don't need to create a
object of session explicitly as we do in Servlets. In Jsp the session is by default true. The
session is defined inside the directive <%@ page session = "true/false" %>. If we don't
declare it inside the jsp page then session will be available to the page, as it is default by
true.
Following program illustrate the concept of session management

The code of the program is given below:

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


<head> "submit" >

<title>Welcome to the first program of jsp </form> </body> </html>


</title> <%
</head> String name = request.getParameter("name");
<body> String password = request.getParameter("pwd");
<form method = "post" action = if(name.equals("Williams") &&
"FirstPageOfSession.jsp"> password.equals("abcde")) {
<font size = 6>Enter your name<input type session.setAttribute("username",name);
= "text" name = "name"></font><br><br> response.sendRedirect("NextPageAfterFirst.jsp");
<font size = 6>Enter your password<input }
type="password" name = "pwd" > else {
</font><br><br> response.sendRedirect("SessionManagement.html
"); } %>

<html>
<head>
<title>Welcome in In the program of URL rewriting</title> </head> <body>
<font size = 6>Hello</font> <%= session.getAttribute("username") %>
</body> </html>

CU IDOL SELF LEARNING MATERIAL (SLM)


158 Advanced Internet Programming

The output of the program is given below:

Fig. 8.2: Session Management Program - 1


When the values entered is correct.

Fig. 8.3: Session Management Program - 2


When the entered values are incorrect, the SessionManagement.html will be displayed again
to you.

Fig. 8.4: Session Management

CU IDOL SELF LEARNING MATERIAL (SLM)


Java Server Pages 159

You can Enter new values again.

8.8 JSP Configuration


Configuring Java Server Pages (JSPs)
JSP config object is used to send the configuration information to JSP page. Here, config is
an instance of servlet’s ServletConfig interface.

In order to deploy Java Server Pages (JSP) files, you must place them in the root (or in a
subdirectory below the root) of a Web application. You define JSP configuration parameters in
subelements of the jsp-descriptor element in the WebLogic-specific deployment descriptor,
weblogic.xml. These parameters define the following functionality:

 Options for the JSP compiler


 Debugging
 How often WebLogic Server checks for updated JSPs that need to be recompiled
 Character encoding

Configuration of a JSP file in web.xml


Declare the following tags in web.xml against your jsp

<servlet>
<servlet-name>myjsp</servlet-name>
<jsp-file>/myjsp.jsp</jsp-file>
<init-param>
<param-name>hello</param-name>
<param-value>test</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>myjsp</servlet-name>
<url-pattern>/myjsp</url-pattern>
</servlet-mapping>

You need a servlet mapping, When you're dealing with a JSP as a Servlet.In order to be able
to access servlet init params, you will need to create a mapping and call the JSP with the url-
pattern in the mapping. JSP provides the "config" implicit object variable that eliminates the need
to call getServletConfig(). You can get the init parameters from the implicit "config" object by
calling getInitParameter() method or getInitParameters() method. For example,

CU IDOL SELF LEARNING MATERIAL (SLM)


160 Advanced Internet Programming

<%= config.getInitParameter("hello");%>

If you make the url-pattern match the name of the JSP, people won't be able to skirt the
web.xml configurations by typing the url of the JSP in the browser's address window.

If you want to add init-params to a JSP via web.xml, you need to create a servlet mapping for
your JSP and use the url defined in that mapping when making the request.

Context init params, on the other hand are bound to the Context object (which is available to
all components of the app) will be available, regardless of how your JSP was invoked.

Example of JSP Config


In this example, web.xml file contains the information. The config object in index.jsp file
fetches that information.

index.jsp

<html>
<head>
<title>Tutorial and Example</title>
</head>
<body>
<% String name=config.getServletName();
out.print("<h2 align=center>Welcome to "+name+"</h2>"); %>
</body> </html>

web.xml

<web-app>
<servlet>
<servlet-name>Tutorial and Example</servlet-name>
<jsp-file>/index.jsp</jsp-file>
</servlet>
<servlet-mapping>
<servlet-name>Tutorial and Example</servlet-name>
<url-pattern>/index</url-pattern>
</servlet-mapping>
</web-app>

CU IDOL SELF LEARNING MATERIAL (SLM)


Java Server Pages 161

Output:

8.9 Implicit Objects


Delivering dynamic website content to a client browser requires interacting with Java objects
on the Web server. Java scripting elements provide a great deal of power and flexibility to the
developer to achieve this. In addition tom permitting such intercommunication the JSP engine
exposes a number of internal Java objects to the developer. These objects do not need to be
declared or instantiated by the developer, but are provided by the JSP engine in its
implementation and execution.

Scripting elements can access predefined variables assigned by the JSP engine and using
their content reference implicit objects to access request and application data. These objects are
instances of class defined by the Servlet and JSP specifications.

Request
JSP pages are web components that respond to and process HTTP requests. The implicit
Request object represents the HTTP request. The Request object provides access to all
information associated with a request including its source, the requested URL and any headers,
cookies or parameters associated with the request.

The request object has a request scope. It encapsulates the request coming from the client and
being processed by the JSP. It is passed to the JSP by the JSP engine, as a parameter to the
_jspService() method. In other words, the request object is in scope unless the response to the
client is complete.

The request object is an instance of javax.Servlet.HttpServletRequest. If the protocol in the


request is something other than HTTP, request object is allowed to be a subclass of
ServletRequest other than HttpServletRequest, which is almost never done in practice as there are
few, if any, JSP servers currently supporting non-HTTP Servlets.

Response
The implicit Response object represents the response sent back to the user browser as a result
of processing the JSP page. Some of the tasks done using response object are setting headers,
cookies for the client and sending a redirect response to the client.

CU IDOL SELF LEARNING MATERIAL (SLM)


162 Advanced Internet Programming

The response object has page scope. It encapsulates the response generated by the JSP. This
is the response being sent back to a client browser in response to its request. The response is
generated by the Web server and passed to the JSP as a parameter to _jspService(). Here the
response generated can be modified by the JSP.

The response object is an instance of javax.servlet.http.HttpServletResponse.

The following table summarizes, most often used methods, available to the Response object:
Table 8.2: Summarizes, Most often used Methods, Available to the Response Object
Method Description
addCookie() Adds the specified cookie to the response. It can be called multiple times to set more
than one cookie
sendRedirect() Sends a temporary redirect response to the client using the specified redirect
location URL

Out
The Out object is a reference to an output stream that can be used within scriptlets. In actual
fact, the Out object represents the output stream of the JSP page, the contents of which are being
sent to a client browser.

The out object in the PrintWriter, which is used to send output to the client. However, in
order to make the response object useful, this is a buffered versions of PrintWriter called
JspWriter.

The out object has page scope and is an instance of javax.servlet.jsp.JspWrite:


Table 8.3: The Out Object in the PrintWriter
Method Description
clear() Clears the contents of the buffer and throws an exception if some data has already been
written to the output stream
close() Flushes and then closes the output stream
flush() Flushes the output buffer and sends any bytes contained in the buffer to their intended
destination. It will also flush all the buffers in a chain of Writers and OutputStream
print() Prints the specified primitive data type such as Object or String to the client
println() Prints the specified primitive data type such as Object or String to the client followed by a
new line character at the end

CU IDOL SELF LEARNING MATERIAL (SLM)


Java Server Pages 163

Session
HTTP is a stateless protocol. As far as Web server is concerned, each client’s request is a
new request, with nothing to connect it to previous requests. However, n Web applications, a
client’s interaction with the application will often span man requests and responses. To join all
these separate interactions into one coherent conversation between the client and application,
Wen applications use the concept of a session.

A session refers to the entire conversation between a client and a server. The JSP
components in a Web application automatically participate in a given client’s session, without
needing to do anything special. The session object allows accessing the client’s session data,
managed by the server. Sessions are created automatically. Hence, this variable is present even if
there are no incoming session references.

The following table lists the most commonly used Session object’s methods:
Table 8.4: Lists the Most Commonly used Session Object’s Methods
Method Description
isNew() A session is considered to be new if it is been created by the server, but the client
has not yet acknowledged joining the session
invalidate() Discards the session, releasing any objects stored as attributes
getAttribute() Retrieves the object associated with the named attribute
setAttribute() Sets the object to the named attribute. Attribute is created if it does not exist
removeAttribute() Removes the object bound with the specified name from this session

Application
The application object represents the application to which the JSP page belongs. It represents
the context within which the JSP is executing [the Servlet context]. In other words, this object
represents the application to which the JSP belongs.

The application object holds references to other objects that more than one user may require
access to such as a database connection pool shared by all application users.

JSP pages are grouped into applications according to their URLs where the first directory
name in a URL defines the application. The application object contains methods that provide
information about the JSP engine, support for logging plus utility methods. For example:
translating a relative URL to an absolute path.

CU IDOL SELF LEARNING MATERIAL (SLM)


164 Advanced Internet Programming

It is an instance of the javax.servlet.ServletContext. The application object has application


scope.

This table lists the most commonly used methods of the Application object:
Table 8.5: Lists of the Most Commonly used Methods of the Application Object
Method Description
getAttribute() Returns the object named name
getAttribute() Stores the object with the given object name in the application
removeAttribute() Removes the name object from the application
log() Writes a message to the Servlet engine’s log file

Config
The configuration information contains initialization parameters, defined in the deployment
descriptor and the ServletContext object representing the Web application the Servlet or JSP page
belongs to.

The config object has page scope and is an instance of javax.servlet.ServletConfig. A Web
server uses a ServletConfig instances to pass information to a Servlet or JSP page during
initialization.

This table lists the most commonly used methods of the Config object:
Table 8.6: Lists of the most Commonly used Methods of the Config. Object
Method Description
getInitParameter() Returns the value of the specified initialization parameter
getInitParaamterNames() Returns an Enumeration of String objects containing the names of all the
Servlet’s initialization parameters
getServerContext() Returns the ServletContext object [contains information about the
environment in which the Servlet is running] associated with the invoking
Servlet

PageContext
The PageContext object encapsulates the page context of a JSP page. The PageContext
object implements methods for transferring control from the current page to another page either
temporarily i.e. to generate output to be included in the output of the current page or permanently
i.e. to transfer control altogether.

CU IDOL SELF LEARNING MATERIAL (SLM)


Java Server Pages 165

PageContext encapsulates access to Web server specific features such as high performance.
The reason being that if the JSP accesses these features through a standard class, rather than
directly, then JSP can execute in any JSP engine irrespective of where the JSP engine is
implemented due to this layer of abstraction.

The pageContext object has page scope and is an instance of javax.servlet.jsp.PageContext.


Page
The Page object represents the JSP page itself and can be accessed using this reference. In
other words, the Page object is simply a synonym for this. It was created as a placeholder for the
time when the scripting language could be something other than java.
The Page object has page scope and is an instance of the class java.lang.Object.

In practice, the Page object is rarely used when JSP’s are scripted using Java. This is because
the JSP scripting elements will ultimately be incorporated as method code of the constructed
Servlet class. Hence, the scripting elements will automatically have access to all the Servlet class
methods.

Exception
The Exception object refers to the runtime exception that results in an error page being
invoked. The Exception object is available only in an error page [i.e. a JSP that has the attribute is
ErrorPage=true in the page directive].

The Exception object has a page scope. It is an instance of java.lang.Throwable. The


Throwable class is the superclass of all the errors and exception classes in the Java language.
Only instances of these classes are thrown by the JVM or can be thrown by an application using
the Java throw statement.

This table lists the most commonly used methods of the Exception object:
Table 8.7: Lists of the most Commonly used Methods of the Exception Object
Method Description
getMessage() Returns the error message string of the Throwable object
toString() Returns a short description of the Throwable object

CU IDOL SELF LEARNING MATERIAL (SLM)


166 Advanced Internet Programming

8.10 Filter
JSP Filters
 Filters are used for filtering functionality of the Java web application.
 They intercept the requests from client before they try to access the resource
 They manipulate the responses from the server and sent to the client.

Types of Filters in JSP


 Authentication filters
 Data compression filters
 Encryption filters
 MIME chain filters
 Logging Filters
 Tokenizing filters
Filters are defined in web.xml, and they are a map to servlet or JSP.When JSP container
starts with the web application, it creates the instance of each filter that have been declared in the
deployment descriptor.

Following are the filter methods:

 Public void doFilter(ServletRequest,ServletResponse, FilterChain)


This is called everytime when a request/response is passed from every client when it is
requested from a resource.
 Public void init(FilterConfig)
This is to indicate that filter is placed into service
 Public void destroy()
This to indicate the filter has been taken out from service.
flow between JSP /Servlets and filters. There can be ‘n’ numbers of filters configured for a
JSP or servlet and all filters execute in a chain. Filter 2 will be executed only if Filter 1 passes the
request and so on . Once request passes all the filters ,it reaches destination resource.

Once JSP or servlet completes its logic , request goes back to filter N and then Filter N-1..
and so on.

CU IDOL SELF LEARNING MATERIAL (SLM)


Java Server Pages 167

JSP Filter Interface


JSP Filter class has to implement javax.servlet.Filter interface. Filter interface defines three
methods which means classes implements filter interface has to implement these methods.

 void init(FilterConfig)
 doFilter (ServletRequest, ServletResponse, FilterChain)
 public void destroy()

Request Response

Filter1 Filter1

Filter2 Filter2

Filter3 Filter3

JSP

Fig. 8.5: JSP Filter Life cycle

JSP Filter Life cycle


The life cycle of a JSP filter is managed by a container and consists of implementing the
following methods: init() This method is called only once after instantiation to perform any
initialization task.We can define a initialization parameters in wex,xml for filters similar to init-
params of servlets.

doFilter() This method is called after the init() method and is called each time a
filter needs to perform any function. This method performs the actual work of a filter, either
modifying the request or the response.

destroy() This method is used to perform any cleanup operation before the container removes
a filter instance.

8.11 JSP in XML and Custom Tag Libraries


Custom Tags in JSP
Let’s say we want to show a number with formatting with commas and spaces. This can be
very useful for user when the number is really long. So we want some custom tags like below:

CU IDOL SELF LEARNING MATERIAL (SLM)


168 Advanced Internet Programming

<mytags:formatNumber number="100050.574" format="#,###.00"/>

Based on the number and format passed, it should write the formatted number in JSP page,
for above example it should print 100,050.57

We know that JSTL doesn’t provide any inbuilt tags to achieve this, so we will create our
own custom tag implementation and use it in the JSP page. Below will be the final structure of
our example project.

JSP Custom Tag Handler


This is the first step in creating custom tags in JSP. All we need to do is extend
javax.servlet.jsp.tagext.SimpleTagSupport class and override doTag() method.

The important point to note is that we should have setter methods for the attributes we need
for the tag. So we will define two setter methods – setFormat (String format) and
setNumber(String number).

SimpleTagSupport provide methods through which we can get JspWriter object and write
data to the response. We will use DecimalFormat class to generate the formatted string and then
write it to response.

We are going to create a custom tag that prints the current date and time. We are performing
action at the start of tag.

For creating any custom tag, we need to follow following steps:

1. Create the Tag handler class and perform action at the start or at the end of the tag.
2. Create the Tag Library Descriptor (TLD) file and define tags
3. Create the JSP file that uses the Custom tag defined in the TLD file

Understanding Flow of Custom Tag in jsp

TLD File
JSP File Tag Handler class
Defining tag
Using tag name and Tag Business logic to be
Handler class performed on tag

Fig. 8.6: Flow of Custom Tag in JSP

CU IDOL SELF LEARNING MATERIAL (SLM)


Java Server Pages 169

8.12 Practical Assignment


1. Develop sample programs with JSP by creating Registration Form and Login Form. In
Registration form, we will have a form to fill all the details which will contain name,
username, password, address, contact number, etc.
This form will help us to register with the application. They take all our details and store
it in a database or cache.
Like registration form we will have a login and logout form. In Login form where we
have two fields “username” and “password” with a submit button. When we click on
submit button then we get welcome message with a logout button. When we click on
logout button then we get back to login form.
2. Develop a JSP application to upload any files using JSP. It can be a text file, binary file,
image file or any other document. Here in case of file uploading, only POST method will
be used and not the GET method.
3. Create a servlet that forwards the request to one of three different JSP pages, depending
on the value of the operation request parameter. Say if input is <10 then page 1 or greater
than 10 and less than 99 then page 2 otherwise error page

8.13 Summary
JSP is a server side technology that does all the processing at server. It is used for creating
dynamic web applications, using java as programming language.

Basically, any html file can be converted to JSP file by just changing the file extension from
“.html” to “.jsp”, it would run just fine. What differentiates JSP from HTML is the ability to use
java code inside HTML. In JSP, you can embed Java code in HTML using JSP tags. for e.g. run
the code below, every time you run this, it would display the current time. That is what makes this
code dynamic.

8.14 Key Words/Abbreviations


 N-Tier Architecture: The n-tier architecture is an industry-proven software architecture
model. It is suitable to support enterprise level client-server applications by providing
solutions to scalability, security, fault tolerance, reusability, and maintainability. It helps
developers to create flexible and reusable applications
 Scriptlet: A scriptlet is a piece of Java-code embedded in the HTML-like JSP code.

CU IDOL SELF LEARNING MATERIAL (SLM)


170 Advanced Internet Programming

 JSP: JavaServer Pages


 HTML: Hyper Text Markup Language
 XML: eXtensible Markup Language

8.15 Learning Activity


1. Which methods are used for JSP Filter Interface.
-----------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------
2. Explain Custom tags in JSP.
-----------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------

8.16 Unit End Questions (MCQs and Descriptive)


A. Descriptive Types Questions
1. What is JSP? Explain its advantage and disadvantage.
2. Explain Architecture of JSP.
3. Explain different Elements of JSP.
4. Explain Scripting elements.
5. What are Directives in JSP? Explain its types?
6. List and Explain any 5 JSP implicit objects?
7. Explain Directives and actions of JSP in short.
8. Explain JSP configuration.
9. Explain White space preservation in JSP.
10 Explain implicit objects used in JSP.
11. Explain Filter in JSP.
12. Explain Usuage of JSP in XML and custom tag libraries.

CU IDOL SELF LEARNING MATERIAL (SLM)


Java Server Pages 171

B. Multiple Choice/Objective Type Questions


1. What technique is used for the authentication mechanism in the servlet specification?
(a) Role Based Authentication (b) Form Based Authentication
(c) Both A & B (d) None of the above
2. In JSP Action tags which tags are used for bean development?
(a) jsp:useBean (b) jsp:setPoperty
(c) jsp:getProperty (d) All mentioned above
3. Which two interfaces does the javax.servlet.jsp package have?
(a) JspPage (b) HttpJspPage
(c) JspWriter (d) Both A & B
4. How many jsp implicit objects are there and these objects are created by the web
container that are available to all the jsp pages?
(a) 8 (b) 9
(c) 10 (d) 7
5. Which of the following is an advantage of the statement – Separation of business logic
from JSP ?
(a) Custom Tags in JSP (b) JSP Standard Tag Library
(c) All the above (d) None of the above

Answers
1. (a), 2. (d), 3. (d), 4. (b), 5. (a)

8.17 References
1. https://beginnersbook.com/2013/05/jsp-tutorial-introduction/
2. https://www.javatpoint.com/jsp-tutorial
3. Karl Avedal, “PRO JSP”.
4. Andrea Steelman and Joel Murach, “Murach’s Java Servlets and JSP: Training &
Reference”.
5. Head first Servlet and JSP, O’REILLY Publication.

CU IDOL SELF LEARNING MATERIAL (SLM)


UNIT 9 JAVA HIBERNATE

Structure:
9.0 Learning Objectives

9.1 Introduction to Hibernate

9.2 Hibernate Architecture

9.3 Hibernate Configuration

9.4 Sessions

9.5 Persistent Class

9.6 Mapping

9.7 O/R mapping in Hibernate

9.8 Annotation Mapping

9.9 Hibernate Query Language

9.10 Hibernate Criteria Queries

9.11 Hibernate Native SQL

9.12 Hibernate Caching and Interceptor

9.13 Practical Assignment

9.14 Summary

9.15 Key Words/Abbreviations

9.16 Learning Activity

CU IDOL SELF LEARNING MATERIAL (SLM)


Java Hibernate 173

9.17 Unit End Questions (MCQs and Descriptive)

9.18 References

9.0 Learning Objectives


After studying this unit, you will be able to:

 Describe Java hibernate architectureconfigurations


 Define sessions, persistent class andmapping
 Explain criteria queries, and NativeSQL
 Elaborate caching and interceptor

9.1 Introduction
Hibernate is a framework which provides some abstraction layer, meaning that the
programmer does not have to worry about the implementations, Hibernate does the
implementations for you internally like establishing a connection with the database, writing query
to perform CRUD operations etc.

It is a java framework which is used to develop persistence logic. Persistence logic means to
store and process the data for long use. More precisely Hibernate is an open-source, non-invasive,
light-weight java ORM(Object-relational mapping) framework to develop objects which are
independent of the database software and make independent persistence logic in all JAVA, JEE.

9.1 Introduction to Hibernate


Hibernate is a high-performance Object/Relational persistence and query service which is
licensed under the open source GNU Lesser General Public License (LGPL) and is free to
download.

Hibernate not only takes care of the mapping from Java classes to database tables (and from
Java data types to SQL data types), but also provides data query and retrieval facilities.

CU IDOL SELF LEARNING MATERIAL (SLM)


174 Advanced Internet Programming

Hibernate Overview
(Object Relational Mapping)

Directly maps Relational


Java Objects
Database Tablets

Mapping

Object Relational

Fig. 9.1: Hibernet (Object Relational Mapping)

Fig. 9.2: Hibernet Overview


 Hibernate is a solution to map database tables to java class
 Copying of tables to objects & vice versa is ORM
 Saving objects to storage medium (Persistence)
Hibernate is an Object-Relational Mapping(ORM) solution for JAVA and it raised as an
open source persistent framework created by Gavin King in 2001. It is a powerful, high
performance Object-Relational Persistence and Query service for any Java Application.

Hibernate maps Java classes to database tables and from Java data types to SQL data
types and relieve the developer from 95% of common data persistence related programming tasks.

Hibernate sits between traditional Java objects and database server to handle all the work in
persisting those objects based on the appropriate O/R mechanisms and patterns.

CU IDOL SELF LEARNING MATERIAL (SLM)


Java Hibernate 175

Mapping
1. Java classes  Database Tables
2. Java Data type  SQL Data type

Hibernate Advantages
1. HibernateDaoSupport: superclass, easy HibernateTemplate access.
2. Database independence: sits between the database and your java code, easy database
switch without changing any code.
3. Object/Relational Mapping (ORM): Hibernate takes care of mapping Java classes to
database tables using XML files and without writing any line of code. Allows a
developer to treat a database like a collection of Java objects.
4. Object oriented query language (HQL) - *Portable* query language, supports
polymorphic queries etc.
5. You can also still issue native SQL, and also queries by “Criteria” (specified using “parse
tree” of Java objects).
6. Hibernate Mapping: Uses HBM XML files to map value objects (POJOs) to database
tables.
7. Transparent persistence: Allows easy saves/delete/retrieve for simple value Objects.
8. Provides simple APIs for storing and retrieving Java objects directly to and from the
database.
9. If there is change in Database or in any table then the only need to change XML file
properties.
10. Abstract away the unfamiliar SQL types and provide us to work around familiar Java
Objects.
11. Hibernate does not require an application server to operate.
12. Manipulates Complex associations of objects of your database.
13. Minimize database access with smart fetching strategies.
14. Provides Simple querying of data.
15. It eliminates need for repetitive SQL
16. Handles all Create, Read, Update, Delete ( CRUD) operations

CU IDOL SELF LEARNING MATERIAL (SLM)


176 Advanced Internet Programming

Supported Databases
Hibernate supports almost all the major RDBMS. Following is list of few of the database
engines supported by Hibernate.

 HSQL Database Engine Applications can be


JSP, Servlets, Swings
 DB2/NT
MySQL PO  Java Beans

( POJO, DAO)
 PostgreSQL
 FrontBase Hibernate.cfg.xml
& properties
 Oracle
 Microsoft SQL Server Database JDBCAPIs from Hibernate to
database
 Sybase SQL Server
 Informix Dynamic Server

9.2 Hibernate Architecture


Hibernate Architecture
The Hibernate architecture is layered to keep you isolated from having to know the
underlying APIs. Hibernate makes use of the database and configuration data to provide
persistence services (and persistent objects) to the application.

Following is a very high level view of the Hibernate Application Architecture.

Java Application

Persistent Object

Hibernet

Hibernate. XML Mapping


Properties

Database

Fig. 9.3: Hibernate Architecture

CU IDOL SELF LEARNING MATERIAL (SLM)


Java Hibernate 177

 Hibernate basically sits between the DB and your code


 Can map persistent objects to tables
 Hibernate 2-tier web architecture
 Can send data to JDBC or XML files
Following is a detailed view of the Hibernate Application Architecture with few important
core classes.

Java Application

Persistent Object

Hibernet

Configuration Session Factory Session


Hibernate. Properties XML Mapping
Transaction Query Criteria

JTA JDBC JNDI

Database

Database

Fig. 9.4: Application Architecture with few Important Core Classes


Explain Architecture of Hibernate framework in detail.

APPLICATION

Persistent

HIBERNATE
Objects

Configuration Session Hibernate.


Transaction Query Criteria
Factory Session
Properties

Java Transaction API JNBC JNDI

DATABASE

Fig. 9.5: Architecture of Hibernate Framework


Hibernate uses various existing Java APIs, like JDBC, Java Transaction API(JTA), and Java

CU IDOL SELF LEARNING MATERIAL (SLM)


178 Advanced Internet Programming

Naming and Directory Interface (JNDI). JDBC provides a rudimentary level of abstraction of
functionality common to relational databases, allowing almost any database with a JDBC driver
to be supported by Hibernate. JNDI and JTA allow Hibernate to be integrated with J2EE
application servers.

Hibernate is made up to three components


1. Connection Management: Hibernate Connection management service provide well-
organized management of the database connections. Database connection is the most
expensive part of interacting with the database as it requires a lot of resources of open
and close the database connection.
2. Transaction management: Transaction management service of hibernate provides the
ability to the user to execute more than one database statements at a time.
3. Object relational mapping: Object relational mapping is technique of mapping the data
representation from an object odel to a relational data model. This part of hibernate is
used to select, insert, update and delete the records form the underlying table. When we
pass an object to a Session.save() method, Hibernate reads the state of the variables of
that object and executes the necessary query.
Following section gives brief description of each of the class objects involved in Hibernate
Application Architecture.

Configuration Object
The Configuration object is the first Hibernate object you create in any Hibernate application
and usually created only once during application initialization. It represents a configuration or
properties file required by the Hibernate. The Configuration object provides two keys components:

1. Database Connection: This is handled through one or more configuration files supported
by Hibernate. These files are hibernate.properties and hibernate.cfg.xml.
2. Class Mapping Setup This component creates the connection between the Java classes
and database tables.

Session Factory Object


Configuration object is used to create a Session Factory object which in turn configures
Hibernate for the application using the supplied configuration file and allows for a Session object
to instantiated. The Session Factory is a thread safe object and used by all the threads of an
application. The Session Factory is is heavyweight object so usually it is created during
application start up and kept for later use. You would need one Session Factory object per

CU IDOL SELF LEARNING MATERIAL (SLM)


Java Hibernate 179

database using a separate configuration file. So if you are using multiple databases then you
would have to create multiple Session Factory objects.

Hence, the session factory is created with the help of a configuration object during the
application start up.it serves as as factory for spawning session objects when required.

Session Object
A Session is used to get a physical connection with a database. The Session object is
lightweight and designed to be instantiated each time an interaction is needed with the database.
Persistent objects are saved and retrieved through a Session object.

The session objects should not be kept open for a long time because they are not usually
thread safe and they should be created and destroyed them as needed.

Session objects are light weight and inexpensive to create.

They provide the main interface to perform actual database operation.

Transaction Object
A Transaction represents a unit of work with the database and most of the RDBMS supports
transaction functionality. Transactions in Hibernate are handled by an underlying transaction
manager and transaction (from JDBC or JTA).

This is an optional object and Hibernate applications may choose not to use this interface,
instead managing transactions in their own application code.

Query Object:
Query objects use SQL or Hibernate Query Language (HQL) string to retrieve data from the
database and create objects. A Query instance is used to bind query parameters, limit the number
of results returned by the query, and finally to execute the query.

Hence Persistent objects are retrieved using a query object.

Criteria Object
Criteria object are used to create and execute object oriented criteria queries to retrieve
objects. Persistent object can also be retrieved using a criteria object.

CU IDOL SELF LEARNING MATERIAL (SLM)


180 Advanced Internet Programming

9.3 Hibernate Configuration


Hibernate Environment Setup
This chapter will explain how to install Hibernate and other associated packages to prepare a
develop environment for the Hibernate applications. We will work with MySQL database to
experiment with Hibernate examples, so make sure you already have setup for MySQL database.

Downloading Hibernate
It is assumed that you already have latest version of Java is installed on your machine.

Following are the simple steps to download and install Hibernate on your machine.

Make a choice whether you want to install Hibernate on Windows, or Unix and then proceed
to the next step to download. zip file for windows and .tz file for Unix.

At the time of writing this tutorial I downloaded hibernate-distribution-3.6.4.Final and


when you unzip the downloaded file it will give you directory structure as follows.

Fig. 9.6: Directory Structure of Downloaded Hibernate

Installing Hibernate
Once you downloaded and unzipped the latest version of the Hibernate Installation file, you
need to perform following two simple steps. Make sure you are setting your CLASSPATH
variable properly otherwise you will face problem while compiling your application.

 Now copy all the library files from /lib into your CLASSPATH, and change your
classpath variable to include all the JARs:
 Finally copy hibernate3.jar file into your CLASSPATH. This file lies in the root
directory of the installation and is the primary JAR that Hibernate needs to do its work.

CU IDOL SELF LEARNING MATERIAL (SLM)


Java Hibernate 181

Hibernate Prerequisites
Following is the list of the packages/libraries required by Hibernate and you should install
them before starting with Hibernate. To install these packages you would have to copy library
files from /lib into your CLASSPATH, and change your CLASSPATH variable accordingly.

Hibernate Configuration
Hibernate requires to know in advance where to find the mapping information that defines
how your Java classes relate to the database tables. Hibernate also requires a set of configuration
settings related to database and other related parameters. All such information is usually supplied
as a standard Java properties file called hibernate.properties, or as an XML file named
hibernate.cfg.xml.

Struture of hibernate.cfg.xml file


Hibernate uses the “ hibernate.cfg.xml ” file to create the connection & setup the required
environment.

Ans:

This file contains information such as…..

1. Database Connection
2. Resource mapping

hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration
DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration> <session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url"> jdbc:mysql://localhost:3306/Feedback
</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
</session-factory> </hibernate-configuration>

Explaination:
1. hibernate.connection.driver_class: It is the JDBC connection class for the specific
database.

CU IDOL SELF LEARNING MATERIAL (SLM)


182 Advanced Internet Programming

2. hibernate.connection.url: It is the full JDBC URL to the database.


3. hibernate.connection.username: It is the username used to connection the database.
4. hibernate.connection.password: It is the password used to authenticate the username.
5. hibernate.dialect: It is the name of SQL dialect for the database.

Detailed Explaination
I will consider XML formatted file hibernate.cfg.xml to specify required Hibernate
properties in my examples. Most of the properties take their default values and it is not required to
specify them in the property file unless it is really required. This file is kept in the root directory
of your application’s classpath.

Hibernate Properties
Following is the list of important properties you would require to configure for a databases in
a standalone situation:

Properties and Description


1. hibernate.dialect 4. hibernate.connection.username
This property makes Hibernate generate the The database username.
appropriate SQL for the chosen database.
2. hibernate.connection.driver_class 5. hibernate.connection.password
The JDBC driver class. The database password.
3. hibernate.connection.url 6. hibernate.connection.pool_size
The JDBC URL to the database instance. Limits the number of connections waiting in
the Hibernate database connection pool.
7. hibernate.connection.autocommit
Allows autocommit mode to be used for the
JDBC connection.
If you are using a database along with an application server and JNDI then you would have
to configure the following properties:

Properties and Description


1. hibernate.connection.datasource 4. hibernate.jndi.url
The JNDI name defined in the application Provides the URL for JNDI.
server context you’re using for the application.

2. hibernate.jndi.class 5. hibernate.connection.username
The InitialContext class for JNDI. The database username.

CU IDOL SELF LEARNING MATERIAL (SLM)


Java Hibernate 183

3. hibernate.jndi.<JNDIpropertyname> 6. hibernate.connection.password
Passes any JNDI property you like to the JNDI The database password.
InitialContext.

9.4 Hibernate Sessions class


the Session object will be created on demand. Session is a lightweight object. Session
provides a physical connectivity between your application and database. The Session will be
established each time your application wants do something with database. Session object will be
provided by SessionFactory object. All the persistent objects will be saved and retrieved through
Session object. The session object must be destroyed after using it.

The lifecycle of a Session is bounded by the beginning and end of a logical transaction. The
main function of the Session is to offer create, read and delete operations for instances of mapped
entity classes. Instances may exist in one of three states:

 transient: never persistent, not associated with any Session.


 persistent: associated with a unique Session.
 detached: previously persistent, not associated with any Session.
Here is the sample implementation for getting Session object from SessionFactory:

HibernateUtil configuration.configure("/j2n-hibernate.cfg.xml");
package com.java2novice.hibernate; configuration.addAnnotatedClass(Employee.clas
import org.hibernate.HibernateException; s);
import org.hibernate.Session; ServiceRegistry srvcReg = new
import org.hibernate.SessionFactory; StandardServiceRegistryBuilder().applySettings(
configuration.getProperties()).build();
import
org.hibernate.boot.registry.StandardServiceR sessionFactory =
egistryBuilder; configuration.buildSessionFactory(srvcReg);
import org.hibernate.cfg.Configuration; }
import org.hibernate.service.ServiceRegistry; public static Session getSession() throws
HibernateException {
import com.java2novice.model.Employee;
Session retSession=null;
public class HibernateUtil {
try {
private static SessionFactory
sessionFactory = null; retSession = sessionFactory.openSession();
static { }catch(Throwable t){
try{ System.err.println("Exception while getting
session.. ");
loadSessionFactory();

CU IDOL SELF LEARNING MATERIAL (SLM)


184 Advanced Internet Programming

} catch(Exception e) { t.printStackTrace();
System.err.println("Exception while initializing }
hibernate util.. "); if(retSession == null) {
e.printStackTrace(); System.err.println("session is discovered null");
} } }
public static void loadSessionFactory() { return retSession;
Configuration configuration = new } }
Configuration();

List of methods which will be used very often in Hibernate implementations:


beginTransaction()
Begin a unit of work and return the associated Transaction object. This method needs to be
called if you want to enable transaction, and once your DB interactions are done, call commit()
method on the returned transaction object. Incase of any issues, call rollback() error on the
transaction object.

save()
Persist the given transient instance, first assigning a generated identifier. This method stores
the given object in the database. Before storing, it checks for generated identifier declaration and
process it first, then it will store into DB.

update()
Update the persistent instance with the identifier of the given detached instance. It updates
the database record.

saveOrUpdate()
Either save(Object) or update(Object) the given instance, depending upon resolution of the
unsaved-value checks. This operation cascades to associated instances if the association is
mapped with cascade="save-update".

createQuery()
Create a new instance of Query for the given HQL query string.

createSQLQuery()
Create a new instance of SQLQuery for the given SQL query string.

CU IDOL SELF LEARNING MATERIAL (SLM)


Java Hibernate 185

merge()
Copy the state of the given object onto the persistent object with the same identifier. If there
is no persistent instance currently associated with the session, it will be loaded. Return the
persistent instance. If the given instance is unsaved, save a copy of and return it as a newly
persistent instance. The given instance does not become associated with the session. This
operation cascades to associated instances if the association is mapped with cascade="merge".

persist()
Make a transient instance persistent. This operation cascades to associated instances if the
association is mapped with cascade="persist".

flush()
Force this session to flush. Must be called at the end of a unit of work, before committing the
transaction and closing the session. Flushing is the process of synchronizing the underlying
persistent store with persistable state held in memory.

delete()
Remove a persistent instance from the datastore. The argument may be an instance
associated with the receiving Session or a transient instance with an identifier associated with
existing persistent state. This operation cascades to associated instances if the association is
mapped with cascade="delete".

9.5 Hibernate Persistent Class


Persistent classes are those java classes whose objects have to be stored in the database tables.
They should follow some simple rules of Plain Old Java Object programming model (POJO).

Some rules that should be, not must be followed by a persistence class.

1. A persistence class should have a default constructor.


2. A persistence class should have an id to uniquely identify the class objects.
3. All attributes should be declared private.
4. Public getter and setter methods should be defined to access the class attributes
Java classes whose objects or instances will be stored in database tables are called persistent
classes in Hibernate. Hibernate works best if these classes follow some simple rules, also known
as the Plain Old Java Object (POJO) programming model.

CU IDOL SELF LEARNING MATERIAL (SLM)


186 Advanced Internet Programming

There are following main rules of persistent classes, however, none of these rules are hard
requirements −

1. All Java classes that will be persisted need a default constructor.


2. All classes should contain an ID in order to allow easy identification of your objects
within Hibernate and the database. This property maps to the primary key column of a
database table.
3. All attributes that will be persisted should be declared private and have getXXX and
setXXX methods defined in the JavaBean style.
4. A central feature of Hibernate, proxies, depends upon the persistent class being either
non-final, or the implementation of an interface that declares all public methods.
5. All classes that do not extend or implement some specialized classes and interfaces
required by the EJB framework.
6. The POJO name is used to emphasize that a given object is an ordinary Java Object, not
a special object, and in particular not an Enterprise JavaBean.

Simple POJO Example


Based on the few rules mentioned above, we can define a POJO class as follows –

public class Employee { public String getFirstName() {


private int id; return firstName;
private String firstName; }
private String lastName; public void setFirstName( String first_name ) {
private int salary; this.firstName = first_name;
public Employee() { } }
public Employee(String fname, String lname, public String getLastName() {
int salary) { return lastName;
this.firstName = fname; }
this.lastName = lname; public void setLastName( String last_name ) {
this.salary = salary; this.lastName = last_name;
} }
public int getId() { public int getSalary() {
return id; return salary;
} }
public void setId( int id ) { public void setSalary( int salary ) {
this.id = id; this.salary = salary;
} } }

CU IDOL SELF LEARNING MATERIAL (SLM)


Java Hibernate 187

9.6 Hibernate Mapping


Hibernate mapping file is used by hibernate framework to get the information about the
mapping of a POJO class and a database table.

It mainly contains the following mapping information:


1. Mapping information of a POJO class name to a database table name.
2. Mapping information of POJO class properties to database table columns.
Elements of the Hibernate mapping file:

1. hibernate-mapping: It is the root element.


2. Class: It defines the mapping of a POJO class to a database table.
3. Id: It defines the unique key attribute or primary key of the table.
4. Generator: It is the sub element of the id element. It is used to automatically generate
the id.
5. Property: It is used to define the mapping of a POJO class property to database table
column.

Syntax

<hibernate-mapping>
<class name="POJO class name" table="table name in database">
<id name="propertyName" column="columnName" type="propertyType" >
<generator class="generatorClass"/>
</id>
<property name="propertyName1" column="colName1" type="propertyType " />
<property name="propertyName2" column="colName2" type="propertyType " />
….
</class>
</hibernate-mapping>

List of mapping elements used in the mapping file −


 The mapping document is an XML document having <hibernate-mapping> as the root
element, which contains all the <class> elements.

CU IDOL SELF LEARNING MATERIAL (SLM)


188 Advanced Internet Programming

 The <class> elements are used to define specific mappings from a Java classes to the
database tables. The Java class name is specified using the name attribute of the class
element and the database table name is specified using the table attribute.
 The <meta> element is optional element and can be used to create the class description.
 The <id> element maps the unique ID attribute in class to the primary key of the
database table. The name attribute of the id element refers to the property in the class
and the column attribute refers to the column in the database table. The type attribute
holds the hibernate mapping type, this mapping types will convert from Java to SQL data
type.
 The <generator> element within the id element is used to generate the primary key
values automatically. The class attribute of the generator element is set to native to let
hibernate pick up either identity, sequence, or hilo algorithm to create primary key
depending upon the capabilities of the underlying database.
 The <property> element is used to map a Java class property to a column in the database
table. The name attribute of the element refers to the property in the class and the
column attribute refers to the column in the database table. The type attribute holds the
hibernate mapping type, this mapping types will convert from Java to SQL data type.

9.7 O/R Mapping


Hibernate O/RM (Object/Relational Mapping).
O/RM itself can be defined as a software or product that represents and/or convert the data
between the application (written in Object-Oriented Language) and the database. In other words
we can say O/RM maps an object to the relational database table. Hibernate is also an O/RM and
is available as open source project. To use Hibernate with Java you will be required to create a
file with .hbm.xml extension into which the mapping information will be provided. This file
contains the mapping of Object with the relational table that provides the information to the
Hibernate at the time of persisting the data. ORM abstracts the application from the process
related to database such as saving, updating, deleting of objects from the relational database table.

We will understand the above concept with the help of an example

CU IDOL SELF LEARNING MATERIAL (SLM)


Java Hibernate 189

Example
Employee.java

package roseindia; public void setEmpId(long empId) {


public class Employee this.empId = empId;
{ }
private long empId; public String getEmpName() {
private String empName; return this.empName;
public Employee() { }
} public void setEmpName(String empName) {
public long getEmpId() { this.empName = empName;
return this.empId; } }
}

employee.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="roseindia.Employee" table="employee">
<id name="empId" type="long" column="Id" >
<generator class="assigned"/>
</id>
<property name="empName">
<column name="Name" />
</property>
</class> </hibernate-mapping>

The figure given below demonstrates you how ORM abstracts the application to the database
related process and vice-versa:

CU IDOL SELF LEARNING MATERIAL (SLM)


190 Advanced Internet Programming

ORM
JDBC Relational
Java Middlewate
Database
Application

Fig. 9.7: ORM Abstracts


The above figure demonstrates that an ORM abstracts the both in respect to database how an
application tries to persist the data and in respect to an application that how objects are stored in
database.

9.8 Annotation Mapping


Hibernate uses XML mapping file for the transformation of data from POJO to database
tables and vice versa. Hibernate annotations are the newest way to define mappings without the
use of XML file. You can use annotations in addition to or as a replacement of XML mapping
metadata.

Hibernate Annotations is the powerful way to provide the metadata for the Object and
Relational Table mapping. All the metadata is clubbed into the POJO java file along with the
code, this helps the user to understand the table structure and POJO simultaneously during the
development.

If you going to make your application portable to other EJB 3 compliant ORM applications,
you must use annotations to represent the mapping information, but still if you want greater
flexibility, then you should go with XML-based mappings.

Environment Setup for Hibernate Annotation


First of all you would have to make sure that you are using JDK 5.0 otherwise you need to
upgrade your JDK to JDK 5.0 to take advantage of the native support for annotations.

Second, you will need to install the Hibernate 3.x annotations distribution package, available
from the sourceforge: (Download Hibernate Annotation) and copy hibernate-annotations.jar,
lib/hibernate-comons-annotations.jar and lib/ejb3-persistence.jar from the Hibernate
Annotations distribution to your CLASSPATH.

CU IDOL SELF LEARNING MATERIAL (SLM)


Java Hibernate 191

Annotated Class Example


As I mentioned above while working with Hibernate Annotation, all the metadata is clubbed
into the POJO java file along with the code, this helps the user to understand the table structure
and POJO simultaneously during the development.

Consider we are going to use the following EMPLOYEE table to store our objects −

create table EMPLOYEE (


id INT NOT NULL auto_increment,
first_name VARCHAR(20) default NULL,
last_name VARCHAR(20) default NULL,
salary INT default NULL,
PRIMARY KEY (id));

Following is the mapping of Employee class with annotations to map objects with the
defined EMPLOYEE table −

import javax.persistence.*; public void setId( int id ) {


@Entity@Table(name = "EMPLOYEE")public this.id = id;
class Employee { }
@Id @GeneratedValue public String getFirstName() {
@Column(name = "id") return firstName;
private int id; }
@Column(name = "first_name") public void setFirstName( String first_name ) {
this.firstName = first_name;
private String firstName; }
@Column(name = "last_name") public String getLastName() {
return lastName;
private String lastName; }
@Column(name = "salary") public void setLastName( String last_name ) {
private int salary; this.lastName = last_name;
}
public Employee() {} public int getSalary() {
return salary; }
public int getId() { public void setSalary( int salary ) {
return id; this.salary = salary; } }
}

CU IDOL SELF LEARNING MATERIAL (SLM)


192 Advanced Internet Programming

Hibernate detects that the @Id annotation is on a field and assumes that it should access
properties of an object directly through fields at runtime. If you placed the @Id annotation on the
getId() method, you would enable access to properties through getter and setter methods by
default. Hence, all other annotations are also placed on either fields or getter methods, following
the selected strategy.

Following section will explain the annotations used in the above class.

@Entity Annotation
The EJB 3 standard annotations are contained in the javax.persistence package, so we
import this package as the first step. Second, we used the @Entity annotation to the Employee
class, which marks this class as an entity bean, so it must have a no-argument constructor that is
visible with at least protected scope.

@Table Annotation
The @Table annotation allows you to specify the details of the table that will be used to
persist the entity in the database.

The @Table annotation provides four attributes, allowing you to override the name of the
table, its catalogue, and its schema, and enforce unique constraints on columns in the table. For
now, we are using just table name, which is EMPLOYEE.

@Id and @GeneratedValue Annotations


Each entity bean will have a primary key, which you annotate on the class with the @Id
annotation. The primary key can be a single field or a combination of multiple fields depending
on your table structure.

By default, the @Id annotation will automatically determine the most appropriate primary
key generation strategy to be used but you can override this by applying the @GeneratedValue
annotation, which takes two parameters strategy and generator that I’m not going to discuss here,
so let us use only the default key generation strategy. Letting Hibernate determine which
generator type to use makes your code portable between different databases.

@Column Annotation
The @Column annotation is used to specify the details of the column to which a field or
property will be mapped. You can use column annotation with the following most commonly
used attributes −

 name attribute permits the name of the column to be explicitly specified.

CU IDOL SELF LEARNING MATERIAL (SLM)


Java Hibernate 193

 length attribute permits the size of the column used to map a value particularly for a
String value.
 nullable attribute permits the column to be marked NOT NULL when the schema is
generated.
 unique attribute permits the column to be marked as containing only unique values.

Create Application Class


Finally, we will create our application class with the main() method to run the application.
We will use this application to save few Employee’s records and then we will apply CRUD
operations on those records.

Import java.util.List; return employeeID; }


import java.util.Date;import java.util.Iterator; /* Method to READ all the employees */
import org.hibernate.HibernateException; public void listEmployees( ){
import org.hibernate.Session; import Session session = factory.openSession();
org.hibernate.Transaction;import Transaction tx = null;
org.hibernate.cfg.AnnotationConfiguration;impo
rt try {

org.hibernate.SessionFactory;import tx = session.beginTransaction();
org.hibernate.cfg.Configuration; List employees = session.createQuery("FROM
public class ManageEmployee { Employee").list();

private static SessionFactory factory; for (Iterator iterator = employees.iterator();


iterator.hasNext();){
public static void main(String[] args) {
Employee employee = (Employee)
try { iterator.next();
factory = new AnnotationConfiguration(). System.out.print("First Name: " +
configure(). employee.getFirstName());
//addPackage("com.xyz") //add package if System.out.print(" Last Name: " +
used. employee.getLastName());
addAnnotatedClass(Employee.class). System.out.println(" Salary: " +
buildSessionFactory(); employee.getSalary());

} catch (Throwable ex) { }

System.err.println("Failed to create tx.commit();


sessionFactory object." + ex); } catch (HibernateException e) {
throw new ExceptionInInitializerError(ex); if (tx!=null) tx.rollback();
} e.printStackTrace();
ManageEmployee ME = new } finally {
ManageEmployee(); session.close();

CU IDOL SELF LEARNING MATERIAL (SLM)


194 Advanced Internet Programming

/* Add few employee records in database */ } }


Integer empID1 = ME.addEmployee("Zara", /* Method to UPDATE salary for an employee
"Ali", 1000); */
Integer empID2 = ME.addEmployee("Daisy", public void updateEmployee(Integer
"Das", 5000); EmployeeID, int salary ){
Integer empID3 = ME.addEmployee("John", Session session = factory.openSession();
"Paul", 10000); Transaction tx = null;
try {
/* List down all the employees */ tx = session.beginTransaction();
ME.listEmployees(); Employee employee =
(Employee)session.get(Employee.class,
/* Update employee's records */ EmployeeID);

ME.updateEmployee(empID1, 5000); employee.setSalary( salary );


session.update(employee);

/* Delete an employee from the database */ tx.commit();

ME.deleteEmployee(empID2); } catch (HibernateException e) {


if (tx!=null) tx.rollback();

/* List down new list of the employees */ e.printStackTrace();

ME.listEmployees(); } finally {

} session.close();

/* Method to CREATE an employee in the } }


database */ /* Method to DELETE an employee from the
public Integer addEmployee(String fname, records */
String lname, int salary){ public void deleteEmployee(Integer
Session session = factory.openSession(); EmployeeID){

Transaction tx = null; Session session = factory.openSession();

Integer employeeID = null; Transaction tx = null;

try { try {

tx = session.beginTransaction(); tx = session.beginTransaction();

Employee employee = new Employee(); Employee employee =


(Employee)session.get(Employee.class,
employee.setFirstName(fname); EmployeeID);
employee.setLastName(lname); session.delete(employee);
employee.setSalary(salary); tx.commit();
employeeID = (Integer) } catch (HibernateException e) {
session.save(employee);
if (tx!=null) tx.rollback();
tx.commit();
e.printStackTrace();

CU IDOL SELF LEARNING MATERIAL (SLM)


Java Hibernate 195

} catch (HibernateException e) { } finally {


if (tx!=null) tx.rollback(); session.close();
e.printStackTrace(); }
} finally { } }
session.close(); }

Database Configuration
Now let us create hibernate.cfg.xml configuration file to define database related parameters.

<?xml version = "1.0" encoding = "utf- <!-- Assume students is the database name -->
8"?><!DOCTYPE hibernate-configuration <property name = "hibernate.connection.url">
SYSTEM
jdbc:mysql://localhost/test
"http://www.hibernate.org/dtd/hibernate-
configuration-3.0.dtd"> </property>

<hibernate-configuration> <property name =


"hibernate.connection.username">
<session-factory>
root
<property name = "hibernate.dialect">
</property>
org.hibernate.dialect.MySQLDialect
<property name =
</property> "hibernate.connection.password">
<property name = cohondob
"hibernate.connection.driver_class">
</property>
com.mysql.jdbc.Driver
</session-factory></hibernate-configuration>
</property>

Compilation and Execution


Here are the steps to compile and run the above mentioned application. Make sure, you have
set PATH and CLASSPATH appropriately before proceeding for the compilation and execution.

 Delete Employee.hbm.xml mapping file from the path.


 Create Employee.java source file as shown above and compile it.
 Create ManageEmployee.java source file as shown above and compile it.
 Execute ManageEmployee binary to run the program.
You would get the following result, and records would be created in EMPLOYEE table.

$java ManageEmployee.......VARIOUS LOG MESSAGES WILL DISPLAY HERE........

CU IDOL SELF LEARNING MATERIAL (SLM)


196 Advanced Internet Programming

First Name: Zara Last Name: Ali Salary: 1000First Name: Daisy Last Name: Das Salary: 5000First Name:
John Last Name: Paul Salary: 10000First Name: Zara Last Name: Ali Salary: 5000First Name: John Last
Name: Paul Salary: 10000

If you check your EMPLOYEE table, it should have the following records −

mysql> select * from EMPLOYEE;+----+------------+-----------+--------+| id | first_name | last_name | salary


|+----+------------+-----------+--------+| 29 | Zara | Ali | 5000 || 31 | John | Paul | 10000 |+----+------------+--------
---+--------+2 rows in set (0.00 sec

mysql>

9.9 Hibernate Query languages


 Hibernate Query Language
 Advantage of HQL
 Query Interface
Hibernate Query Language (HQL) is same as SQL (Structured Query Language) but it
doesn’t depends on the table of the database. Instead of table name, we use class name in HQL.
So it is database independent query language.

Advantage of HQL
There are many advantages of HQL. They are as follows:

 database independent
 supports polymorphic queries
 easy to learn for Java Programmer

Query Interface
It is an object oriented representation of Hibernate Query. The object of Query can be
obtained by calling the createQuery() method Session interface.

The query interface provides many methods. There is given commonly used methods:

1. public int executeUpdate() is used to execute the update or delete query.


2. public List list() returns the result of the relation as a list.
3. public Query setFirstResult(int rowno) specifies the row number from where record
will be retrieved.

CU IDOL SELF LEARNING MATERIAL (SLM)


Java Hibernate 197

4. public Query setMaxResult(int rowno) specifies the no. of records to be retrieved from
the relation (table).
5. public Query setParameter(int position, Object value) it sets the value to the JDBC
style query parameter.
6. public Query setParameter(String name, Object value) it sets the value to a named
query parameter.

Example of HQL to get all the records


1. Query query=session.createQuery("from Emp");//here persistent class name is Emp
2. List list=query.list();

Example of HQL to get records with pagination


1. Query query=session.createQuery("from Emp");
2. query.setFirstResult(5);
3. query.setMaxResult(10);
4. List list=query.list();//will return the records from 5 to 10th number

FROM Clause
You will use FROM clause if you want to load a complete persistent objects into memory.
Following is the simple syntax of using FROM clause −

String hql = "FROM Employee";Query query = session.createQuery(hql);List results = query.list();

If you need to fully qualify a class name in HQL, just specify the package and class name as
follows

String hql = "FROM com.hibernatebook.criteria.Employee";Query query = session.createQuery(hql);List


results = query.list();

AS Clause
The AS clause can be used to assign aliases to the classes in your HQL queries, especially
when you have the long queries. For instance, our previous simple example would be the
following −

String hql = "FROM Employee AS E";Query query = session.createQuery(hql);List results = query.list();

The AS keyword is optional and you can also specify the alias directly after the class name,
as follows −

CU IDOL SELF LEARNING MATERIAL (SLM)


198 Advanced Internet Programming

String hql = "FROM Employee E";Query query = session.createQuery(hql);List results = query.list();

SELECT Clause
The SELECT clause provides more control over the result set then the from clause. If you
want to obtain few properties of objects instead of the complete object, use the SELECT clause.
Following is the simple syntax of using SELECT clause to get just first_name field of the
Employee object −

String hql = "SELECT E.firstName FROM Employee E";Query query = session.createQuery(hql);List


results = query.list();

It is notable here that Employee.firstName is a property of Employee object rather than a


field of the EMPLOYEE table.

WHERE Clause
If you want to narrow the specific objects that are returned from storage, you use the
WHERE clause. Following is the simple syntax of using WHERE clause −

String hql = "FROM Employee E WHERE E.id = 10";Query query = session.createQuery(hql);List results
= query.list();

ORDER BY Clause
To sort your HQL query’s results, you will need to use the ORDER BY clause. You can
order the results by any property on the objects in the result set either ascending (ASC) or
descending (DESC). Following is the simple syntax of using ORDER BY clause −

String hql = "FROM Employee E WHERE E.id > 10 ORDER BY E.salary DESC";Query query =
session.createQuery(hql);List results = query.list();

If you wanted to sort by more than one property, you would just add the additional properties
to the end of the order by clause, separated by commas as follows −

String hql = "FROM Employee E WHERE E.id > 10 " +


"ORDER BY E.firstName DESC, E.salary DESC ";Query query = session.createQuery(hql);List results =
query.list();

GROUP BY Clause
This clause lets Hibernate pull information from the database and group it based on a value
of an attribute and, typically, use the result to include an aggregate value. Following is the simple
syntax of using GROUP BY clause −

CU IDOL SELF LEARNING MATERIAL (SLM)


Java Hibernate 199

String hql = "SELECT SUM(E.salary), E.firtName FROM Employee E " +


"GROUP BY E.firstName";Query query = session.createQuery(hql);List results = query.list();

Using Named Parameters


Hibernate supports named parameters in its HQL queries. This makes writing HQL queries
that accept input from the user easy and you do not have to defend against SQL injection attacks.
Following is the simple syntax of using named parameters −

String hql = "FROM Employee E WHERE E.id = :employee_id";Query query = session.createQuery(hql);


query.setParameter("employee_id",10);List results = query.list();

UPDATE Clause
Bulk updates are new to HQL with Hibernate 3, and delete work differently in Hibernate 3
than they did in Hibernate 2. The Query interface now contains a method called executeUpdate()
for executing HQL UPDATE or DELETE statements.

The UPDATE clause can be used to update one or more properties of an one or more objects.
Following is the simple syntax of using UPDATE clause −

String hql = "UPDATE Employee set salary = :salary " +


"WHERE id = :employee_id";Query query = session.createQuery(hql);
query.setParameter("salary", 1000);
query.setParameter("employee_id", 10);int result = query.executeUpdate();System.out.println("Rows
affected: " + result);

DELETE Clause
The DELETE clause can be used to delete one or more objects. Following is the simple
syntax of using DELETE clause −

String hql = "DELETE FROM Employee " +


"WHERE id = :employee_id";Query query = session.createQuery(hql);
query.setParameter("employee_id", 10);int result = query.executeUpdate();System.out.println("Rows
affected: " + result);

INSERT Clause
HQL supports INSERT INTO clause only where records can be inserted from one object to
another object. Following is the simple syntax of using INSERT INTO clause −

CU IDOL SELF LEARNING MATERIAL (SLM)


200 Advanced Internet Programming

String hql = "INSERT INTO Employee(firstName, lastName, salary)" +


"SELECT firstName, lastName, salary FROM old_employee";Query query =
session.createQuery(hql);int result = query.executeUpdate();System.out.println("Rows affected: " +
result);

Aggregate Methods
HQL supports a range of aggregate methods, similar to SQL. They work the same way in
HQL as in SQL and following is the list of the available functions −

You may call avg(), min(), max() etc. aggregate functions by HQL. Let’s see some common
examples:

The distinct keyword only counts the unique values in the row set. The following query will
return only unique count −

String hql = "SELECT count(distinct E.firstName) FROM Employee E";Query query =


session.createQuery(hql);List results = query.list();

9.10 Hibernate Criteria Query Language


The Hibernate Criteria Query Language (HCQL) is used to fetch the records based on the
specific criteria. The Criteria interface provides methods to apply criteria such as retrieving all the
records of table whose salary is greater than 50000 etc.

Advantage of HCQL
The HCQL provides methods to add criteria, so it is easy for the java programmer to add
criteria. The java programmer is able to add many criteria on a query.

Criteria Interface
The Criteria interface provides many methods to specify criteria. The object of Criteria can
be obtained by calling the createCriteria() method of Session interface.

Syntax of createCriteria() method of Session interface


public Criteria createCriteria(Class c)

The commonly used methods of Criteria interface are as follows:

1. public Criteria add(Criterion c) is used to add restrictions.


2. public Criteria addOrder(Order o) specifies ordering.

CU IDOL SELF LEARNING MATERIAL (SLM)


Java Hibernate 201

3. public Criteria setFirstResult(int firstResult) specifies the first number of record to be


retreived.
4. public Criteria setMaxResult(int totalResult) specifies the total number of records to
be retrieved.
5. public List list() returns list containing object.
6. public Criteria setProjection(Projection projection) specifies the projection.

Restrictions class
Restrictions class provides methods that can be used as Criterion. The commonly used
methods of Restrictions class are as follows:

1. public static SimpleExpression lt(String propertyName,Object value) sets the less


than constraint to the given property.
2. public static SimpleExpression le(String propertyName,Object value) sets the less
than or equal constraint to the given property.
3. public static SimpleExpression gt(String propertyName,Object value) sets the
greater than constraint to the given property.
4. public static SimpleExpression ge(String propertyName,Object value) sets the
greater than or equal than constraint to the given property.
5. public static SimpleExpression ne(String propertyName,Object value) sets the not
equal constraint to the given property.
6. public static SimpleExpression eq(String propertyName,Object value) sets the equal
constraint to the given property.
7. public static Criterion between(String propertyName, Object low, Object high) sets
the between constraint.
8. public static SimpleExpression like(String propertyName, Object value) sets the like
constraint to the given property.

Order class
The Order class represents an order. The commonly used methods of Restrictions class are as
follows:

1. public static Order asc(String propertyName) applies the ascending order on the basis
of given property.

CU IDOL SELF LEARNING MATERIAL (SLM)


202 Advanced Internet Programming

2. public static Order desc(String propertyName) applies the descending order on the
basis of given property.

Examples of Hibernate Criteria Query Language


There are given a lot of examples of HCQL.

Example of HCQL to get all the records


1. Crietria c=session.createCriteria(Emp.class);//passing Class class argument
2. List list=c.list();

Example of HCQL to get the 10th to 20th record


1. Crietria c=session.createCriteria(Emp.class);
2. c.setFirstResult(10);
3. c.setMaxResult(20);
4 List list=c.list();

Example of HCQL to get the records whose salary is greater than 10000
1. Crietria c=session.createCriteria(Emp.class);
2. c.add(Restrictions.gt("salary",10000));//salary is the propertyname
3. List list=c.list();

Example of HCQL to get the records in ascending order on the basis of salary
1. Crietria c=session.createCriteria(Emp.class);
2. c.addOrder(Order.asc("salary"));
3. List list=c.list();

HCQL with Projection


We can fetch data of a particular column by projection such as name etc. Let’s see the simple
example of projection that prints data of NAME column of the table only.

1.Criteria c=session.createCriteria(Emp.class);
2. c.setProjection(Projections.property("name"));
3. List list=c.list();

CU IDOL SELF LEARNING MATERIAL (SLM)


Java Hibernate 203

9.11 Native SQL


Native SQL is another technique of performing bulk operations on the data using hibernate

 By using Native SQL, we can perform both select, non-select operations on the data
 In face Native SQL means using the direct SQL command specific to the particular
(current using) database and executing it with using hibernate

Advantages and Disadvantages of Native SQL


 We can use the database specific keywords (commands), to get the data from the
database
 While migrating a JDBC program into hibernate, the task becomes very simple because
JDBC uses direct SQL commands and hibernate also supports the same commands by
using this Native SQL
 The main draw back of Native SQL is, some times it makes the hibernate application as
database dependent one
If we want to execute Native SQL Queries on the database then, we need to construct an
object of SQLQuery, actually this SQLQuery is an interface extended from Query and it is given
in ” org.hibernate package ”

In order to get an object of SQLQuery, we need to use a method createSQLQuery() given by


session interface.

While executing native sql queries on the database, we use directly tables, column names
directly in our command.

Remember, while executing Native SQL Queries, even though we are selecting complete
objects from teh database we need to type cast into object array only, not into our pojo class type,
because we are giving direct table, column names in the Native SQL Querie so it does’nt know
our class name

If we execute the command, always first it will put’s data in ResultSet and from there List

Usage:
SQLQuery qry = session.createSQLQuery("select * from PRODUCTS");
// Here PRODUCTS is the table in the database...
List l = qry.list();
Iterator it = l.iterator();

CU IDOL SELF LEARNING MATERIAL (SLM)


204 Advanced Internet Programming

while(it.hasNext())
{
Object row[] = (Object[])it.next();
--- -------}

 while selecting data from the table, even though you are selecting the complete object
from the table, in while loop still we type cast into object array only right
 See the above code, we typecast into the object[] arrays right.., in case if we want to type
cast into our POJO class (i mean to get POJO class obj), then we need to go with
entityQuery concept
 In order to inform the hibernate that convert each row of ResultSet into an object of the
POJO class back, we need to make the query as an entityQuery
 to make the query as an entityQuery, we need to call addEntity() method

//We are letting hibernate to know our pojo class too


SQLQuery qry = session.createSQLQuery("select * from PRODUCTs").addEntity(Product.class);
List l = qry.list();
Iterator it = l.iterator();
while(it.hasNext())
{
Product p = (Product)it.next();
--- -------}

9.12 Hibernate Caching and Interceptor


Caching
Caching is a mechanism to enhance the performance of a system. It is a buffer memory that
lies between the application and the database. Cache memory stores recently used data items in
order to reduce the number of database hits as much as possible.

Caching is important to Hibernate as well. It utilizes a multilevel caching scheme as


explained below

First-level Cache
The first-level cache is the Session cache and is a mandatory cache through which all
requests must pass. The Session object keeps an object under its own power before
committing it to the database.

CU IDOL SELF LEARNING MATERIAL (SLM)


Java Hibernate 205

If you issue multiple updates to an object, Hibernate tries to delay doing the update as long as
possible to reduce the number of update SQL statements issued. If you close the session, all the
objects being cached are lost and either persisted or updated in the database.

Database

First-level Cache

Hibernate
Session Object Client

Second-level Cache

Optional

Fig. 9.8: Hibernate Cache

Second-level Cache
Second level cache is an optional cache and first-level cache will always be consulted
before any attempt is made to locate an object in the second-level cache. The second level
cache can be configured on a per-class and per-collection basis and mainly responsible for
caching objects across sessions.

Any third-party cache can be used with Hibernate. An org.hibernate.cache.CacheProvider


interface is provided, which must be implemented to provide Hibernate with a handle to the cache
implementation.

Query-level Cache
Hibernate also implements a cache for query resultsets that integrates closely with the
second-level cache.

This is an optional feature and requires two additional physical cache regions that hold the
cached query results and the timestamps when a table was last updated. This is only useful for
queries that are run frequently with the same parameters.

The Second Level Cache


Hibernate uses first-level cache by default and you have nothing to do to use first-level cache.
Let's go straight to the optional second-level cache. Not all classes benefit from caching, so it's
important to be able to disable the second-level cache.

CU IDOL SELF LEARNING MATERIAL (SLM)


206 Advanced Internet Programming

The Hibernate second-level cache is set up in two steps. First, you have to decide which
concurrency strategy to use. After that, you configure cache expiration and physical cache
attributes using the cache provider.

Concurrency Strategies
A concurrency strategy is a mediator, which is responsible for storing items of data in
the cache and retrieving them from the cache. If you are going to enable a second-level
cache, you will have to decide, for each persistent class and collection, which cache
concurrency strategy to use.

 Transactional: Use this strategy for read-mostly data where it is critical to prevent stale
data in concurrent transactions, in the rare case of an update.
 Read-write: Again use this strategy for read-mostly data where it is critical to prevent
stale data in concurrent transactions, in the rare case of an update.
 Nonstrict-read-write: This strategy makes no guarantee of consistency between the
cache and the database. Use this strategy if data hardly ever changes and a small
likelihood of stale data is not of critical concern.
 Read-only: A concurrency strategy suitable for data, which never changes. Use it for
reference data only.

Interceptor
In Hibernate, an object will be created and persisted. Once the object has been changed, it
must be saved back to the database. This process continues until the next time the object is needed,
and it will be loaded from the persistent store.

Thus an object passes through different stages in its life cycle and Interceptor Interface
provides methods, which can be called at different stages to perform some required tasks. These
methods are callbacks from the session to the application, allowing the application to inspect
and/or manipulate properties of a persistent object before it is saved, updated, deleted or loaded.
Following is the list of all the methods available within the Interceptor interface −

Sr.No. Method & Description


1 findDirty()
This method is be called when the flush() method is called on a Session object.
2 instantiate()
This method is called when a persisted class is instantiated.

CU IDOL SELF LEARNING MATERIAL (SLM)


Java Hibernate 207

3 isUnsaved()
This method is called when an object is passed to the saveOrUpdate() method/
4 onDelete()
This method is called before an object is deleted.
5 onFlushDirty()
This method is called when Hibernate detects that an object is dirty (i.e. have been changed)
during a flush i.e. update operation.
6 onLoad()
This method is called before an object is initialized.
7 onSave()
This method is called before an object is saved.
8 postFlush()
This method is called after a flush has occurred and an object has been updated in memory.
9 preFlush()
This method is called before a flush.
Hibernate Interceptor gives us total control over how an object will look to both the
application and the database.

9.13 Practical Assignment


1. Design Hibernate application to store employee object to the database.
2. Create a maven based hibernate application using annotation in eclipse IDE.

9.14 Summary
Hibernate is a high-performance Object/Relational persistence and query service, which is
licensed under the open source GNU Lesser General Public License (LGPL) and is free to
download. Hibernate not only takes care of the mapping from Java classes to database tables (and
from Java data types to SQL data types), but also provides data query and retrieval facilities. This
tutorial will teach you how to use Hibernate to develop your database based web applications in
simple and easy steps.

CU IDOL SELF LEARNING MATERIAL (SLM)


208 Advanced Internet Programming

9.15 Key Words/Abbreviations


 Object-Relational Persistence: Hibernate is an Object-Relational Mapping (ORM)
solution for JAVA. It is an open source persistent framework created by Gavin King in
2001. It is a powerful, high performance Object-Relational Persistence and Query service
for any Java Application.
 EJB: Enterprise Java Bean
 HQL: Hibernate Query Language

9.16 Learning Activity


1. What is HCQL?
-----------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------
2. Explain different Interceptor?
-----------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------

9.17 Unit End Questions (MCQs and Descriptive)


A. Descriptive Types Questions
1. Explain what is Hibernate.
2. Explain Hibernate Architecture with neat diagram.
3. Explain Hibernate Configuration in detail.
4. Explain Session class in Hibernate.
5. Explain Persistent class in Hibernate
6. Explain Hibernate Mapping.
7. Explain O/R mapping in Hibernate
8. Explain Annotation mapping
9. Explain Hibernate Query language.
10. Explain Hibernate Criteria Queries.

CU IDOL SELF LEARNING MATERIAL (SLM)


Java Hibernate 209

11. Explain Hibernate Native SQL.


12. Explain Hibernate Caching and Interceptor.

B. Multiple Choice/Objective Type Questions


1. Which of the following is true about ORM?
(a) ORM stands for Object-Relational Mapping.
(b) ORM is a programming technique for converting data between relational databases.
(c) Both of the above.
(d) None of the above.
2. Which of the following is true about configuration component of Hibernate?
(a) The Configuration object is the first Hibernate object you create in any Hibernate
application.
(b) The Configuration object is usually created only once during application
initialization.
(c) The Configuration object represents a configuration or properties file required by
the Hibernate.
(d) All of the above.
3. Which method is used to get a persistent instance from the datastore?
(a) Session.read() (b) Session.get()
(c) Session.retrieve() (d) Session.fetch()
4. Which of the following element is used to represent one-to-one relationship in hibernate?
(a) <many-to-one> (b) <many-one>
(c) <ManyToOne> (d) None of the above.
5. What HQL stands for?
(a) Hibernate Query Language (b) High Query Language
(c) Hybrid Query Language (d) None of the above.

Answers
1. (c), 2. (d), 3. (b), 4. (a), 5. (a)

CU IDOL SELF LEARNING MATERIAL (SLM)


210 Advanced Internet Programming

9.18 References
1. https://java2blog.com/introduction-to-hibernate-framework/
2. https://www.geeksforgeeks.org/introduction-to-hibernate-framework/
3. Java Persistence with Hibernate by Christian Bauer, Gavin King

CU IDOL SELF LEARNING MATERIAL (SLM)


UNIT 10 JAVA STRUTS - I

Structure:
10.0 Learning Objectives

10.1 Introduction

10.2 Basic MVC Architecture

10.3 Model 1 and Model 2(MCV) Architecture

10.4 Struts 2 Framework Features

10.5 Environment Setup

10.6 Configuration

10.7 Actions

10.8 Interceptors

10.9 Value Stack

10.10 Result Types

10.11 File Uploads

10.12 Practical Assignment

10.13 Database Access

10.14 Summary

10.15 Key Words/Abbreviations

10.16 Learning Activity

CU IDOL SELF LEARNING MATERIAL (SLM)


212 Advanced Internet Programming

10.17 Unit End Questions (MCQs and Descriptive)

10.18 References

10.0 Learning Objectives


After studying this unit, you will be able to:

 Describe environment setupconfiguration


 Discuss actions, interceptors, resulttypes
 Elaborate File uploads, databaseaccess

10.1 Introduction
Struts is a popular and mature web application framework based on the MVC design pattern.
Struts2 is not just a new version of Struts 1, but it is a complete rewrite of the Struts architecture.

The Webwork framework initially started with Struts framework as the basis and its goal was
to offer an enhanced and improved framework built on Struts to make web development easier for
the developers.

After a while, the Webwork framework and the Struts community joined hands to create the
famous Struts2 framework.

10.2 MVC Architecture


Model–view–controller (MVC) is a software architectural patternfor implementing user
interfaces on computers. It divides a given application into three interconnected parts. This is
done to separate internal representations of information from the ways information is presented to,
and accepted from, the user.

Let me put it this way: Entire web development goes in distinct way where we have entire
process categorized to different developers working on it such as Database, Back-end
programming and front-end programming.

“Model” consist of database operations(CRUD operations; Create, Read, Update, Delete


queries), “View” consist of Front end development (HTML, CSS, JavaScript etc) and
“Controller” consist of the main business logic (Backend programming through server side

CU IDOL SELF LEARNING MATERIAL (SLM)


Java Struts - I 213

languages such as PHP, JAVA etc). ‘Controller” controls the interaction/transactions between the
“Model” and “Viewer”.

VIEWER
MODEL

CONTROLLER

Fig. 10.1: MVC Architecture


Struts 2 MVC is released by three core framework components: actions, results, and the
ServletFilter. The diagram below shows how these three components interact with each other.

request Invoke action Model

Controller Action

Servlet Filter
Interceptor

Web Browser Client Select result

View

Result
Render result

Fig. 10.2: Struts 2 MVC

Servlet Filter
The servlet filter acts as a controller in Struts 2. It inspects each incoming request to
determine which Struts 2 action should handle the request. The framework handles all of the
controller work for the application. All request URLs need to be mapped to actions with XML-
based configuration files or Java annotations.

Interceptors
Interceptors execute before and after the request processing. They provide cross-cutting tasks
so that they can be easily reused as well as separated from other architectural concerns. For
example, validation parameters before invoking login action.

CU IDOL SELF LEARNING MATERIAL (SLM)


214 Advanced Internet Programming

Action
Action handles the client requests in two different ways. First, the action plays an important
role in the transfer of data from the request through to the view, whether its a JSP or other type of
result. Second, the action must assist the framework in determining which result should render the
view that will be returned in the response to the request.

Result
Result is a JSP or HTML page to create a view for client response. Struts 2 provides their
own tags that we can use in JSP pages to create a response. Struts tags are great example of JSP
Custom Tags.

10.4 Features of Struts 2


Java struts is an open source framework that extends Java Servlet API (Application Program
Interface) and employs a Model, Viewer and controller (MVC) architecture. It enables you to
create maintainable, extensible, and flexible web applications based on standard technologies,
such as JSP pages, JavaBeans, resource bundles, and XML.

The struts framework was initially created byCraig McClanahanand donated to Apache
Foundation in May, 2000 and Struts 1.0 was released in June 2001. The current stable release of
Struts is Struts 2.3.16.1 in March 2, 2014. Struts 2 will also supports POJO ( plain old java
objects) based actions, AJAX support, validation support and several other frameworks
integrations such as Hibernate, Spring etc. We have also shown the demo of the same.

Here are formal Struts2 Framework Features:

1. Configurable MVC components


2. POJO based actions
3. AJAX support
4. Integration support
5. Various Result Types
6. Various Tag support
7. Theme and Template support
1. Configurable MVC components: Struts2 framework, provides all the components
(view components and action) information in struts.xml file. We simply need to change
strut.xml file for changing any information.

CU IDOL SELF LEARNING MATERIAL (SLM)


Java Struts - I 215

2. POJO based actions: Struts2, action class is POJO (Plain Old Java Object) i.e. a simple
java class.
3. AJAX support: Struts2 provides support to AJAX technology. Using AJAX one can
make webpage load only the desired content on request, hence reduces page load. One
glitch we must know that; AJAX is not suitable for slow internet options.
4. Integration Support: Integration struts2 application with hibernate, spring, tiles etc.
Frameworks is possible.
5. Various Result Types: Use of JSP, velocity etc. Technologies in the result type in
Struts2 is possible.
6. Various Tag support: Struts 2 provides various types of tags such as UI tags, Data tags,
control tags etc to ease the development of struts2 application.
7. Theme and Template support: Struts2 provides 3 types of theme support: Simple,
XHTML and CSS_XHTML. The XHTML is default theme of struts2. Themes and
templates can be used for common look and feel especially when look and feel doesn’t
matter much. Also it saves time for design.

10.5 Environment Setup


Step 1 - Setup Java Development Kit (JDK)
You can download the latest version of SDK from Oracle's Java site −Java SE Downloads.
You will find instructions for installing JDK in downloaded files, follow the given instructions to
install and configure the setup. Finally, set PATH and JAVA_HOME environment variables to
refer to the directory that contains java and javac, typically java_install_dir/bin and
java_install_dir respectively.

If you are running Windows and installed the SDK in C:\jdk1.5.0_20, you should be
inputting the following line in your C:\autoexec.bat file.

set PATH = C:\jdk1.5.0_20\bin;%PATH%set JAVA_HOME = C:\jdk1.5.0_20

Alternatively, on Windows NT/2000/XP −

 You can right-click on My Computer, Select Properties, then Advanced, then


Environment Variables. Then, you would update the PATH value and press the OK
button.

CU IDOL SELF LEARNING MATERIAL (SLM)


216 Advanced Internet Programming

 On Unix (Solaris, Linux, etc.), if the SDK is installed in /usr/local/jdk1.5.0_20 and you
use the C shell, you would put the following into your .cshrc file.
 On Unix (Solaris, Linux, etc.), if the SDK is installed in /usr/local/jdk1.5.0_20 and you
use the C shell, you would put the following into your .cshrc file.

setenv PATH /usr/local/jdk1.5.0_20/bin:$PATH


setenv JAVA_HOME /usr/local/jdk1.5.0_20

Alternatively, if you use an Integrated Development Environment (IDE) like Borland


JBuilder, Eclipse, IntelliJ IDEA, or Sun ONE Studio, compile and run a simple program to
confirm that the IDE knows where you installed Java, otherwise do proper setup as per the given
document of IDE.

Step 2 - Setup Apache Tomcat


You can download the latest version of Tomcat fromhttps://tomcat.apache.org/. Once you
downloaded the installation, unpack the binary distribution into a convenient location.

For example in C:\apache-tomcat-6.0.33 on windows, or /usr/local/apachetomcat-6.0.33 on


Linux/Unix and create CATALINA_HOME environment variable pointing to these locations.

You can start Tomcat by executing the following commands on windows machine, or you
can simply double click on startup.bat

%CATALINA_HOME%\bin\startup.bat
Or C:\apache-tomcat-6.0.33\bin\startup.bat

Tomcat can be started by executing the following commands on Unix (Solaris, Linux, etc.)
machine −

$CATALINA_HOME/bin/startup.sh
Or /usr/local/apache-tomcat-6.0.33/bin/startup.sh

After a successful startup, the default web applications included with Tomcat will be
available by visitinghttp://localhost:8080/. If everything is fine, then it should display the
following result −

CU IDOL SELF LEARNING MATERIAL (SLM)


Java Struts - I 217

Fig. 10.3: Apache Tomcat


Further information about configuring and running Tomcat can be found in the
documentation included here, as well as on the Tomcat website:https://tomcat.apache.org/

Tomcat can be stopped by executing the following commands on windows machine −

%CATALINA_HOME%\bin\shutdown
Or C:\apache-tomcat-5.5.29\bin\shutdown

Tomcat can be stopped by executing the following commands on Unix (Solaris, Linux, etc.)
machine −

$CATALINA_HOME/bin/shutdown.sh
Or /usr/local/apache-tomcat-5.5.29/bin/shutdown.sh

Step 3 - Setup Eclipse (IDE)


All the examples in this tutorial are written using Eclipse IDE. I suggest that, you have the
latest version of Eclipse installed in your machine.

To install Eclipse Download the latest Eclipse binaries from


https://www.eclipse.org/downloads/. Once you download the installation, unpack the binary
distribution into a convenient location.

CU IDOL SELF LEARNING MATERIAL (SLM)


218 Advanced Internet Programming

For example in C:\eclipse on windows, or /usr/local/eclipse on Linux/Unix and finally set


PATH variable appropriately. Eclipse can be started by executing the following commands on
windows machine, or you can simply double click on eclipse.exe

%C:\eclipse\eclipse.exe

Eclipse can be started by executing the following commands on Unix (Solaris, Linux, etc.)
machine −

$/usr/local/eclipse/eclipse

After a successful startup, if everything is fine, it should display the following result −

Fig. 10.4: Eclipse (IDE)

Step 4 - Setup Struts2 Libraries


Now if everything is fine, then you can proceed to setup your Struts2 framemwork.
Following are the simple steps to download and install Struts2 on your machine.

 Make a choice whether you want to install Struts2 on Windows, or Unix and then
proceed to the next step to download .zip file for windows and .tz file for Unix.
 Download the latest version of Struts2 binaries from
https://struts.apache.org/download.cgi.

CU IDOL SELF LEARNING MATERIAL (SLM)


Java Struts - I 219

 I downloaded struts-2.3.4.1-all.zip. Unzip this zip file to any location. for example
E:/struts-2.3.4.1.
 E:/struts-2.3.4.1/lib folder contains all required jar files for struts 2 framework.
 AndE:/struts-2.3.4.1/appsfolder contains some sample webapplication war files
includingstruts2-blank.war file.
 struts2-blank.war file contains all configuration required for running sample Struts 2 web
application.
you can run this sample using Eclipse like this:

 import war file: File ->import->choosestruts2-blank.war file (in Eclipse).It should look
like this:

Fig. 10.5: Struts2 Blank War File


After importing struts2-blank.war file,struts2-blank application directory structure look like
this:

CU IDOL SELF LEARNING MATERIAL (SLM)


220 Advanced Internet Programming

Fig. 10.6: Struts2 Application Structure


Now run this struts2-blank application, result on browser should be look like this:

Fig. 10.7: Struts 2 Blank Application

10.6 Configuration
The Model-View-Controller Framework in Struts2 has five core components for
configuration:

CU IDOL SELF LEARNING MATERIAL (SLM)


Java Struts - I 221

 Actions
 Interceptors
 Value Stack / OGNL
 Results / Result types
 View technologies
Struts 2 is slightly different from a traditional MVC framework in that the action takes the
role of the model rather than the controller, although there is some overlap.

Browser
Results/Result Types

Controller View
Dispatcher Filter
JSP

Interceptors
Free
marker
Execute() setXxx()

Model Value
Stack/OGN
Action
getXxx()

Fig. 10.8: Image Courtesy : tutorialspoint.com


The above diagram depicts theModel,View andController to the Struts2 high level
architecture. The controller is implemented with a Struts2 dispatch servlet filter as well as
interceptors, the model is implemented with actions, and the view as a combination of result types
and results. The value stack and OGNL provide common thread, linking and enabling integration
between the other components. Object-Graph Navigation Language(OGNL) is an open-source
Expression Language (EL) for Java, which, while using simpler expressions than thefullrange of
those supported by the Java language, allows getting and setting properties (through defined
setProperty and getProperty methods, found in JavaBeans), and execution of methods of Java
classes. It also allows for simpler array manipulation.

CU IDOL SELF LEARNING MATERIAL (SLM)


222 Advanced Internet Programming

Apart from the above components, there will be a lot of information that relates to
configuration. Configuration for the web application, as well as configuration for actions,
interceptors, results, etc.

This is the architectural overview of the Struts 2 MVC pattern. We will go through each
component in more detail in the subsequent chapters.

10.7 Struts 2 Action


In struts 2, action class isPOJO(Plain Old Java Object).

POJO means you are not forced to implement any interface or extend any class.

Generally,executemethod should be specified that represents the business logic. The simple
action class may look like:

Welcome.java
package com.javatpoint;
public class Welcome {
publicStringexecute() {
return"success";
} }

Action Interface
A convenient approach is to implement thecom.opensymphony.xwork2.Actioninterface that
defines 5 constants and one execute method.

Constants of Action Interface


Action interface provides 5 constants that can be returned from the action class. They are:

1. SUCCESS indicates that action execution is successful and a success result should be
shown to the user.
2. ERROR indicates that action execution is failed and a error result should be shown to the
user.
3. LOGIN indicates that user is not logged-in and a login result should be shown to the user.
4. INPUT indicates that validation is failed and a input result should be shown to the user
again.

CU IDOL SELF LEARNING MATERIAL (SLM)


Java Struts - I 223

5. NONE indicates that action execution is successful but no result should be shown to the
user.
Let's see what values are assigned to these constants:

1. publicstaticfinalStringSUCCESS="success";
2. publicstaticfinalStringERROR="error";
3. publicstaticfinalStringLOGIN="login";
4. publicstaticfinalStringINPUT="input";
5. publicstaticfinalStringNONE="none";

Method of Action Interface


Action interface contains only one method execute that should be implemented overridden
by the action class even if you are not forced.

1. publicStringexecute();

Example of Struts Action that implements Action interface


If we implement the Action interface, we can directly use the constants instead of values.

Welcome.java
Package com.javatpoint;
import com.opensymphony.xwork2.Action;
public class Welcome implements Action{
public Stringexecute() {
returnSUCCESS;
} }

ActionSupport Class
It is a convenient class that implements many interfaces such as Action, Validateable,
ValidationAware, TextProvider, LocaleProvider and Serializable. So it is mostly used instead of
Action.

Example of Struts Action that extends ActionSupport class


Let's see the example of Action class that extends the ActionSupport class.

Welcome.java
package com.javatpoint;

CU IDOL SELF LEARNING MATERIAL (SLM)


224 Advanced Internet Programming

import com.opensymphony.xwork2.ActionSupport;
public class Welcome extends ActionSupport {
public Stringexecute() {
return SUCCESS;
} }

Role of Action
1. Performs as a model: Action performs as a Model by encapsulating the actual work to
be done for a given request based on the input parameters. Encapsulation is done using
the execute() method. The code spec inside this method should only hold the business
logic to serve a Request.

Example:
public String execute()
{
setWelcomeMessage(msg+getUserName());
return “SUCCESS”;
}

In above code, a welcome message is shown to the user along with the name using String
Concatenation

2. Serves as a data Carrier: Action server as a data carrier from the Request to the View.
Action being the Model component of the framework carries the data around. The data it requires
is held locally which makes it is easy to access using JavaBeans properties during the actual
execution of the business logic. The execute() method simply references the data using JavaBeans
properties.

Example:
private String uname;
public String getUName()
{ return uname; }
public void setUName(String uname)
{ this.uname=uname; }
private String msg;
public String getWelcomeMsg()
{ this.msg=msg; }

CU IDOL SELF LEARNING MATERIAL (SLM)


Java Struts - I 225

In above code, Action implements JavaBeans properties for all the data being carried. The
framework automatically maps the FORM Request parameters to the JavaBeans properties that
have matching names.

3. Helps Determine Results: Action determines the Result that will render the View that
will be returned in the request’s response. This is achieved by returning a control string that
selects the result that should be rendered. The value of return string must be identical to the result
name as configured.

Example:

public String execute()


{
setWelcomeMsg(MSG+getUName());
return “SUCCESS”;
}

In above code, Action returns the SUCCESS. We have to modify struts.xml configuration
file as follows:

<action name=”WelcomeStruts” class=”test. WelcomeStruts”>


<result name=”SUCCESS”>/ welcome.jsp</result>
</action>

Here SUCCESS is the name of the one of the result components that is identical to the return
String.

4. Single or Multiple Results: For returning single action result we have to code like follows:

class MyAction {
{ public void String execute()throws Exception
public void String execute () throws Exception {
{ If(LogicIsSOK())
setWelcomeMsg(MSG+getUName()); {
return “SUCCESS”; setWelcomeMsg(MSG+getUName());
} } return “SUCCESS”;
An action can also return multiple results }
depending on the complexity of the business else
logic, {
In such cases, we have code like follows: return “ERROR”;
Class MyMultipleAction }}}

CU IDOL SELF LEARNING MATERIAL (SLM)


226 Advanced Internet Programming

In above code, there are two different results that can be returned depending upon the
business logic flow. Since Action returns more than one kind of results, we need make
appropriate configuration in the struts.xml configuration file as follows.

<action name=”WelcomeStruts” class=”test.WelcomeStruts”>


<result name=”SUCCESS”>/ Welcome.jsp</result>
<result name=”ERROR”>/ Error.jsp</result> </action>

10.8 Interceptors
Interceptors allow developing code that can be run before and / or after the execution of an
action. A request is usually processed as follows:

 A user requests a resource that maps to an action.


 The Struts 3 framework invokes the appropriate action to serve the request.
If interceptors are written, available and configured, then:

 Before the action is executed the invocation could be intercepted by another object.
 After the action executes, the invocation could be intercepted again by another object.
Such objects who intercept the invocation are called Interceptors. Conceptually, interceptors
are very similar to Servlet Filters or the JDKs Proxy class.

Interceptors Configuration: Interceptors configured in the struts.xml file appear as:

<interceptors>
<interceptor name=”test1” class=”…”/>
<interceptor name=”test2” class=”…”/>
</interceptors>
<action name=”Welcome Struts”>
<interceptor-ref name=”test1”/>
<interceptor-ref name=”test2”/>
<result name=”SUCCESS”>/ Welcome.jsp</result>
<result name=”ERROR”>/ Error.jsp</result>
</action>

In above code two interceptors named test 1 and test 2 are defined. Both of these are them
mapped to the action named WelcomeStruts.

CU IDOL SELF LEARNING MATERIAL (SLM)


Java Struts - I 227

Interceptor Stack: We can bind Interceptor together using an Interceptor Stack which can be
referenced together. We can use the same set of interceptors multiple times. So, instead of
configuring a number of interceptors every time, an interceptor stack can be configured with all
the required interceptors held within. To use Intercept Stack we need to modify the strutd.xml file
as follows:

<interceptors>
<interceptor name=”test1” class=”…”/>
<interceptor name=”test2” class=”…”/>
<interceptor-stack name=”MyStack”>
<interceptor-ref name=”test 1”/>
<interceptor-ref name=”test 2”/>
</interceptor-stack>
</interceptors>
<action name=”WelcomeStruts” class=”test. WelcomeStruts”>
<result name=”SUCCESS”>/Welcome.jsp</result>
<result name=”ERROR”>/Error.jsp</result>
</action>

In above code two interceptors named test 1 and test 2 are defined and a stack named
MyStack group them both. The stack holding both these interceptors is then mapped to the Action
named WelcomeStruts.

Execution Flow of Interceptors


Interceptors are executed as follows:

1. The framework receives a request and decides on the action the URL maps to
2. The framework consults the application’s configuration file, to discover which
interceptors should fire and in what sequence
3. The framework starts the invocation process by executing the first Interceptor in the
Stack
4. After all the interceptors are invoked; the framework causes the action itself to be
executed

CU IDOL SELF LEARNING MATERIAL (SLM)


228 Advanced Internet Programming

10.9 Value Stack


Value Stack is nothing but stack of objects. The Value Stack is a storage area that holds all
of the data associated with the processing of a Request.

Execution Flow of Value Stack


1. The framework receives a request and decides on the action the URL maps to
2. The framework moves the data to the Value Stack whilst preparing for request
processing.
3. The framework manipulates the data as required during the action execution
4. The framework reads the data from there and renders the results i.e. Response page struts
2 maintains a stack of the following objects in the Value Stack:
5. Temporary Objects: these are generated and placed in the Value Stack during execution.
These objects provide temporary storage and are normally generated while processing a
request. For example, the current iteration value for collection being looped over in JSP
tag.
6. The Model Object: If the application user Model objects, the current model object is
placed in the Value Stack before the Action executes.
7. The Action Object: It is the Action that is currently being executed.
8. Named objects: Any object assigned to an identifier called as a Named Object. These
object can either be created by the developer of pre.-defined such as #application
Accessing value Stack: The Value Stack can be accessed by simply using the tags provided
for JSP. When the Value Stack Is queried for an attribute value, each stack element, in the
provided order, is asked whether it holds the queried property. If it holds the queried property,
then the value is returned. If it does not hold the queried property, then the next element down is
queried. This continues until the last element in the stack is scanned.

10.10 Result Types


After executing the Action class , the target view page will be executed based on
configuration in struts.xml. The Srruts2 framework provides set of Result types like; chaining,
dispatcher, redirect action, velocity and free market etc, that has to be configure in struts.xml for
different kind of result. The result type is used to change the behaviour of view page to render the
contents of action class.

CU IDOL SELF LEARNING MATERIAL (SLM)


Java Struts - I 229

Thecom.opensymphony.xwork2.Resultinterface implemented by all the result classes. The


Result interface has a single method public void execute (Action Invocation ) throws Exception.

Thecom.opensymphony.xwork2.config.entities.ResultConfigclass stores the configuration


information from struts.xml for each result configured with Action class.

Thecom.opensymphony.xwork2.config.entities.ResultTypeConfigclass stores information


about result type in struts.xml for each action class.

Default Parameter:
To minimize configuration, Results can be configured with default value in the struts.xml
configuration file. For example, here is a result defined in XML that uses a default parameter:

<result>/Success.jsp</result>

That is the equivalent to this:

<result name="success"type="dispatcher">
<param name="location">/Success.jsp</param>
</result>

Result Configuration:
When method of action class completes, it returns a String value. This value of the
String("success", "input", "error" etc ) is used to select a result element in struts.xml configuration
file. The String value matched with an action mapping will often have a set of results representing
different possible outcomes. A standard set of result tokens are defined by theActionSupportbase
class.

Predefined result names in Action interface :


String SUCCESS = "success";
String NONE = "none";
String ERROR = "error";
String INPUT = "input";
String LOGIN = "login";

Configure multiple results : Please interpret below code as follows.


(a) If method return "success" it forward to /hello/Result.jsp
(b) If method return "error" it forward to /hello/Error.jsp

CU IDOL SELF LEARNING MATERIAL (SLM)


230 Advanced Internet Programming

(c) If method return "input" it forward to /hello/Input.jsp


(d) if method return other than success, error and input then forward to /hello/Other.jsp page

<action name="Hello">
<result>/hello/Result.jsp</result>
<result name="error">/hello/Error.jsp</result>
<result name="input">/hello/Input.jsp</result>
<result name="*">/hello/Other.jsp</result> </action>

The Struts2 framework provides several implementations of the


com.opensymphony.xwork2.Result interface, ready to use in your own applications.

There are eleven types of results in Struts2 :


1. Dispatcher Result : Used for dispatch the request to other JSP page to include contents
or forward contents. It is default result type.
2. Chain Result : Used for Action Chaining
3. Free Marker Result : Used for Free Marker integration
4. Redirect Result : Used to redirect to another URL
5. Redirect Action Result: Used to redirect to another action mapping
6. Stream Result: Used to stream an InputStream back to the browser
7. Velocity Result: Used for Velocity integration
8. XSL Result : Used for XML/XSLT integration
9. PlainText Result: Used to display the raw content of a particular page
The user defined result types can be categorized as follows:

Result Types

Dispatcher Result Redirect Result Velocity Result

Chain Result Redirect Action XSL Result

FreeMarker Result Stream Result PlainText Result

Fig. 10.9: Result Types

CU IDOL SELF LEARNING MATERIAL (SLM)


Java Struts - I 231

1. Dispatcher Result:
 The dispatcher result is used to include or forward to a target view page (JSP). It is
default result type in Struts2 framework.
 It uses RequestDispatcher interface to achieve it, where the target Server or JSP
receive the same request and response either using forward() or include() method.
2. Chain Action Result:
 It is used to achieve action chaining. In the action chaining the multiple actions can
be executed in defined sequence. And the target view page will be displayed after
last action. In the chain result type, the target resource will be any action which is
already configured in struts.xml file
3. FreeMarker Result:
 It is used to integrate the Freemarker templates in the view page. The Freemarker
engine renders the freemarker view page and extension will be .ftl of view page.
4. Redirect Result:
 The redirect result is used to redirect the browser request to the new resource. It
works based on HttpServletResponse.sendRedirect() method. It is redirected by
browser and the target resource can be part of the same application or cannot be
part of the same application. That is, the resource should be apart from the
application resources.
5. Redirect Action
 Redirect action is same as redirect result type. But here, the target result must be an
action either in same application or in the other application. It can be used for both
the purposes.
6. Stream Result
 Streaming refers to input stream and output stream classes in java.
 It is used to Streaming the InputStream back to the client and client can download
the content in the specified format. This is very useful for allowing users to
download content from our web application in any format, for example, pdf, doc,
xls etc.

10.11 File Uuploads


ThefileUploadinterceptor automatically works for all the requests that includes files.

CU IDOL SELF LEARNING MATERIAL (SLM)


232 Advanced Internet Programming

We can use this interceptor to control the working of file upload in struts2 such as defining
allowed types, maximum file size etc.

Parameters of fileupload interceptor


There are 2 parameters defined for fileupload interceptor.
Table 10.1: Parameters of fileupload Interceptor
Parameter Description
MaximumSize specifies maximum size of the file to be uploaded.
allowedTypes specifies allowed types. It may be image/png, image/jpg etc.

Automatically added parameters


It automatically adds 2 parameters in the request:

1. String fileNamerepresents the filename of the file.


2. String contentTypespecifies the content type of the file.

Image upload example using struts 2


Let's see the directory structure of file upload application.

Fig. 10.10: Struts2 Upload Application

CU IDOL SELF LEARNING MATERIAL (SLM)


Java Struts - I 233

1. Create UserImage.jsp
This jsp page creates a form using struts UI tags. It receives file from the user.

index.jsp

<%@pagecontentType="text/html;charset=UTF- <s:actionerror/>
8"%> <s:formaction="userImage"method="post"enc
<%@taglibprefix="s"uri="/struts-tags"%> type="multipart/form-data">
<html> <s:filename="userImage"label="Image"/>
<head> <title>UploadUserImage</title> </head> <s:submitvalue="Upload"align="center"/>
<body> </s:form>
<h2> </body>
Struts2FileUpload&SaveExamplewithoutDatabas </html>
e
</h2>

2. Create SuccessUserImage.jsp
This jsp page creates a form using struts UI tags. It receives name, password and email id
from the user.

SuccessUserImage.jsp

<%@pagecontentType="text/html;charset=UTF UserImage:<s:propertyvalue="userImage"/><br/
-8"%><%@taglibprefix="s" >
uri="/struts-tags"%> ContentType:<s:propertyvalue="userImageCont
<html> entType"/><br/>

<head> FileName:<s:propertyvalue="userImageFileNa
<title>Success:UploadUserImage</title> me"/><br/>

</head> UploadedImage:<imgsrc="userimages/<s:prope
rtyvalue="userImageFileName"/>"
<body>
width="100"height="100"/>
<h2> Struts2FileUploadExample </h2>
</body> </html>

3. Create the action class


This action class inherits the ActionSupport class and overrides the execute method.

RegisterAction.java

package com.javatpoint; File


import java.io.File; Utils.copyFile(userImage,fileToCreate);//copyi

CU IDOL SELF LEARNING MATERIAL (SLM)


234 Advanced Internet Programming

impor tjavax.servlet.http.HttpServletRequest; ngsourcefiletonewfile


import org.apache.commons.io.FileUtils; return SUCCESS;
import }
com.opensymphony.xwork2.ActionSupport; public void setUserImage(FileuserImage) {
public class this.userImage=userImage; }
FileUploadActionextendsActionSupport {
publicStringgetUserImageContentType() {
private FileuserImage;
returnuserImageContentType; }
private StringuserImageContentType;
publicvoidsetUserImageContentType(Stringus
private StringuserImageFileName; erImageContentType) {
public Stringexecute() { this.userImageContentType=userImageConte
try { ntType;
StringfilePath=ServletActionContext.getServletC }
ontext().getRealPath("/").concat("userimages"); publicStringgetUserImageFileName() {
System.out.println("ImageLocation:"+filePath);//s returnuserImageFileName; }
eetheserverconsoleforactuallocation
publicvoidsetUserImageFileName(StringuserI
File mageFileName) {
fileToCreate=newFile(filePath,userImageFileNa
me); this.userImageFileName=userImageFileName
;
public FilegetUserImage() {
}}
return userImage; }

4. Create struts.xml
This xml file defines an extra result by the name input, and an interceptor
jsonValidatorWorkflowStack.

struts.xml
<!DOCTYPEstrutsPUBLIC <paramname="allowedTypes">
"- image/png,image/gif,image/jpeg,image/pj
//ApacheSoftwareFoundation//DTDStrutsConfiguratio peg
n2.0//EN" </param>
"http://struts.apache.org/dtds/struts-2.0.dtd"> </interceptor-ref>
<struts> <interceptor-
<packagename="fileUploadPackage"extends="struts refname="defaultStack"></interceptor-
-default"> ref>
<actionname="userImage"class="com.javatpoint.File <resultname="success">SuccessUserIma
UploadAction"> ge.jsp</result>
<interceptor-refname="fileUpload"> <resultname="input">UserImage.jsp</res
<paramname="maximumSize">2097152</param> ult>
</action> </package> </struts>

CU IDOL SELF LEARNING MATERIAL (SLM)


Java Struts - I 235

Output

10.12 Database Access


Login Application in Struts2 with Database Access.
 It is a complete web application in Struts 2. The program creates login application
without validations.
 The program uses static user name and password. The same program can be modified to
have dynamic authentication by using the data stored from database. This will require
creation of DOJO classes and JSON objects.
 The program prints username on successful login attempt and error page on failure or
error event.

// first.jsp
<%--
Document : first
Created on : Nov 14, 2014, 12:49:46 PM
Author : Infinity
--%>
<%@page contentType = "text/html" pageEncoding = "UTF-8"%>
<%@taglib uri = "/struts-tags" prefix = "s" %>
<!DOCTYPE html>

CU IDOL SELF LEARNING MATERIAL (SLM)


236 Advanced Internet Programming

<html>
<body>
<h1> Login Application </h1>
<hr/>
<s:form action = "verify">
<s:textfield name = "uname" label = "Enter Username" /> <br>
<s:password name = "password" label = "Enter Password" /> <br>
<s:submit value = "Login" align = "center" />
</s:form> </body> </html>
? // Redirect.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package jsp_action;
import com.opensymphony.xwork2.ActionSupport;
public class Redirect extends ActionSupport{
private static final long serialVersionUID = 1L;
private String uname,password;
public String getUname() {
return uname;
}
public void setUname(String uname) {
this.uname = uname;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String execute()
{
if(uname.equals("abc") && password.equals("xyz"))

CU IDOL SELF LEARNING MATERIAL (SLM)


Java Struts - I 237

{
return SUCCESS;
}else
return ERROR;
}}
// successpage.jsp
<%--
Document : next
Created on : Nov 14, 2014, 1:19:42 PM
Author : Infinity
--%>
<%@page contentType = "text/html" pageEncoding = "UTF-8"%>
<%@taglib prefix = "s" uri = "/struts-tags" %>
<!DOCTYPE html>
<h1>
Welcome <s:property value = "uname" />, you have been successfully logged in..
</h1> <hr/>

//errorpage.jsp <%@ taglib prefix = "s" uri = "/struts-tags" %>


<%-- <!DOCTYPE html>
Document : errorpage <html>
Created on : Feb 6, 2015, 6:43:24 PM <body>
Author : Infinity Login failed...!
--% </body> </html>
<%@page contentType = "text/html"
pageEncoding = "UTF-8"%>

// struts.xml <package name = "default" extends = "struts-


default">
<!DOCTYPE struts PUBLIC
<action name = "verify" class =
"-//Apache Software Foundation//DTD "jsp_action.Redirect">
Struts Configuration 2.0//EN"
<result name = "success"> successpage.jsp
"http://struts.apache.org/dtds/struts- </result>
2.0.dtd">
<result name = "error"> errorpage.jsp </result>
<struts>
</action> </package> </struts>

CU IDOL SELF LEARNING MATERIAL (SLM)


238 Advanced Internet Programming

// web.xml
<?xml version = "1.0" encoding = "UTF-8"?>
<web-app version = "3.1" xmlns = "http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi =
"http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation =
"http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>jsp/first.jsp</welcome-file>
</welcome-file-list> </web-app>

The application will run as follows:

CU IDOL SELF LEARNING MATERIAL (SLM)


Java Struts - I 239

First screenshot

unsuccessful login attempt

second run of application

10.13 Practical Assignment


1. Create Struts application to give demo of Date Range Field Validator.
2. Create Form Handling with Struts.

CU IDOL SELF LEARNING MATERIAL (SLM)


240 Advanced Internet Programming

10.14 Summary
.A framework that allowed them to focus on building their application without spending a lot
of time writing the code that organized and coordinated processing. After reviewing a number of
other competing frameworks, they settled on Struts for a number of reasons—some technical and
some not. The Struts technical features that were important to them were:

 Struts performs well.


 Struts has a sound architectural model with a modest learning curve.
 Struts is very solid and stable.
 Struts has a strong set of custom tag libraries that simplify JSP development.

10.15 Key Words/Abbreviations


 Interceptors: Interceptors are used in conjunction with Java EE managed classes to
allow developers to invoke interceptor methods on an associated target class, in
conjunction with method invocations or lifecycle events. Common uses of interceptors
are logging, auditing, and profiling.
 Velocity: Velocity is a Java-based template engine. It permits web page designers to
reference methods defined in Java code.

10.16 Learning Activity


1. Explain the five core components of configuration.
-----------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------
2. Explain ActionSupport Class.
-----------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------

CU IDOL SELF LEARNING MATERIAL (SLM)


Java Struts - I 241

10.17 Unit End Questions (MCQs and Descriptive)


A. Descriptive Types Questions
1. Explain MVC architecture with the help of suitable diagram.
2. Explain steps for Environment setup of Struts.
3. Explain Configuration of struts 2.
4. What are Actions in Struts? Explain Execution flow of Actions.
5. Write short notes on interceptors in Struts.
6. What is value stack in Struts? state and explain Execution flow.
7. Explain Result types in Struts.
8. Explain steps to upload File through Struts.
9. Explain with any suitable example of database Access by using Struts.

B. Multiple Choice/Objective Type Questions


1. Which technology can be used at View Layer in Struts?
(a) J2EE (b) DHTML
(c) XML/XSLT (d) JavaScript
2. ActionServlet, RequestProcessor and Action classes are the components of __________.
(a) View (b) Model
(c) Controller (d) Deployment
3. Which of the following acts as a bridge between user-invoked URL and a business
method?
(a) RequestProcessor (b) ActionServlet
(c) Action Class (d) HttpRequest
4. The Dispatch from the controller to the action class is based on a configuration that is
provided by a __________.
(a) struts-config.xml (b) strts-processor-conifg.xml
(c) struts-configs.xml (d) struts-action-config.xml

CU IDOL SELF LEARNING MATERIAL (SLM)


242 Advanced Internet Programming

5. Struts Framework is based on __________.


(a) Servlet,JSP and Java (b) Servlet,HTML and Java
(c) Servlet,JSP,XML and Java (d) Applet,Xml and Java

Answers
1. (c), 2. (c), 3. (c), 4. (c), 5. (c)

10.18 References
1. https://www.javatpoint.com/struts-2-tutorial
2. https://www.developer.com/java/ent/article.php/10933_1495931_2/An-Introduction-to-
Struts.htm
3. Budi Kurniawan, 1 January 2010, “Struts 2 Design and Programming” Paperback.

CU IDOL SELF LEARNING MATERIAL (SLM)


UNIT 11 JAVA STRUTS - II

Structure:
11.0 Learning Objectives

11.1 Introduction

11.2 Sending Mails

11.2 Validation

11.3 Localization

11.4 Type Conversion

11.5 Exception Handling

11.6 Annotation
11.7 Tags and Integrations
11.8 Practical Assignment

11.9 Summary

11.10 Key Words/Abbreviations

11.11 Learning Activity

11.12 Unit End Questions (MCQs and Descriptive)

11.13 References

CU IDOL SELF LEARNING MATERIAL (SLM)


244 Advanced Internet Programming

11.0 Learning Objectives


After studying this unit, you will be able to:

 Describe sending mails, validation, and localization


 Explain type conversion, exception handling, and annotation
 Discuss tags and integrations

11.1 Introduction
The struts framework is an open source framework for creating well-structured web based
applications. The struts framework is based on the Model View Controller (MVC) paradigm
which distinctly separates all the three layers - Model (state of the application), View
(presentation) and Controller (controlling the application flow). This makes struts different from
conventional JSP applications where sometimes logic, flow and UI are mingled in a Java Server
Page.

The struts framework is a complete web framework as it provides complete web form
components, validators, error handling, internationalization, tiles and more. Struts framework
provides its own Controller component. It integrates with other technologies for both Model and
View components. Struts can integrate well with Java Server Pages (JSP), Java Server Faces
(JSF), JSTL, Velocity templates and many other presentation technologies for View. For Model,
Struts works great with data access technologies like JDBC, Hibernate, EJB and many more.

11.2 Sending mails


The JavaMail is an API that is used to compose, write and read electronic messages (emails).

The JavaMail API provides protocol-independent and plateform-independent framework for


sending and receiving mails.

The javax.mail and javax.mail.activation packages contains the core classes of JavaMail
API.

The JavaMail facility can be applied to many events. It can be used at the time of registering
the user (sending notification such as thanks for your interest to my site), forgot password
(sending password to the users email id), sending notifications for important updates etc. So there
can be various usage of java mail api.

CU IDOL SELF LEARNING MATERIAL (SLM)


Java Struts - II 245

Protocols used in JavaMail API


There are some protocols that are used in JavaMail API.

 SMTP
 POP
 IMAP
 MIME
 NNTP and others

Sending Email in Java


There are various ways to send email using JavaMail API. For this purpose, you must have
SMTP server that is responsible to send mails.

You can use one of the following techniques to get the SMTP server:

 Install and use any SMTP server such as Postcast server, Apache James server, cmail
server etc. (or)
 Use the SMTP server provided by the host provider e.g. my SMTP server is
mail.javatpoint.com (or)
 Use the SMTP Server provided by other companies e.g. gmail etc.
Here, we are going to learn above three approaches to send email using javamail API. But we
should learn the basic steps to send email from java application.

Steps to Send Email using JavaMail API


There are following three steps to send email using JavaMail. They are as follows:

1. Get the session object that stores all the information of host like host name, username,
password etc.
2. compose the message
3. send the message

1. Get the session object


The javax.mail.Session class provides two methods to get the object of session,
Session.getDefaultInstance() method and Session.getInstance() method. You can use any method
to get the session object.

CU IDOL SELF LEARNING MATERIAL (SLM)


246 Advanced Internet Programming

Method of Session Class


Table 11.1: Method of Session Class

No. Method Description


1. public static Session getDefaultInstance(Properties props) returns the default session.
2. public static Session getDefaultInstance (Properties returns the default session.
props,Authenticatorauth)
3. public static Session getInstance(Properties props) returns the new session
4. public static Session get Instance(Properties returns the new session
props,Authenticatorauth)
Example of getDefaultInstance() method

Properties properties=new Properties();

//fill all the information like host name etc.

Session session=Session.getDefaultInstance(properties,null);

Example of getInstance() method

Properties properties=new Properties();

//fill all the information like host name etc.

Session session=Session.getInstance(properties,null);

2. Compose the Message


The javax.mail.Message class provides methods to compose the message. But it is an abstract
class

so its subclass javax.mail.internet.MimeMessage class is mostly used.

To create the message, you need to pass session object in MimeMessage class constructor.

For example:

MimeMessage message=new MimeMessage(session);

Now message object has been created but to store information in this object MimeMessage
class provides many methods. Let’ see methods provided by the MimeMessage class:

CU IDOL SELF LEARNING MATERIAL (SLM)


Java Struts - II 247

Commonly used Methods of MimeMessage class


Table 11.2: Commonly used Methods of MimeMessage class

No. Method Description


1. public void setFrom (Address address) is used to set the from header field.
2. public void addRecipient is used to add the given address to the recipient type.
(Message.Recipient Type type, Address
address)
3. public void is used to add the given addresses to the recipient
addRecipients(Message.RecipientType type.
type, Address[] addresses)

4. public void setSubject(String subject) is used to set the subject header field.
5. public void setText(String textmessage) is used to set the text as the message content using
text/plain MIME type.
6. public void setContent(Object msg, is used to set the content as the message content using
String contentType) given MIME type.

Example to compose the message:

MimeMessage message=new MimeMessage(session);


message.setFrom(new InternetAddress("sonoojaiswal@sssit.org"));
message.addRecipient(Message.RecipientType.To,
new InternetAddress("sonoojaiswal@javatpoint.com"));
message.setHeader("Hi, everyone");
message.setText("Hi, This mail is to inform you...");

3. Send the Message


The javax.mail.Transport class provides method to send the message.

Commonly used Methods of Transport Class


Table 11.3: Commonly used Methods of Transport Class

No. Method Description


1. public static void send(Message message) is used send the message.
2. public static void send(Message message, Address[] is used send the message to the given
address) addresses.

CU IDOL SELF LEARNING MATERIAL (SLM)


248 Advanced Internet Programming

Example to Send the Message

Transport.send(message);

Example for Sending Email


JavaMail API provides a platform-independent and protocol-independent framework to build
mail and messaging applications.

Required Library: In this example, you need to add below libraries in your project build path.

1. mail-1.4.jar

pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" <build>
xmlns:xsi="http://www.w3.org/2001/XMLSchema- <sourceDirectory>src</sourceDirectory>
instance" <plugins> <plugin>
xsi:schemaLocation="http://maven.apache.org/POM/4.0. <artifactId>maven-compiler-
0http://maven.apache.org/xsd/maven-4.0.0.xsd"> plugin</artifactId>
<modelVersion>4.0.0</modelVersion> <version>3.3</version>
<groupId>org.websparrow</groupId> <configuration>
<artifactId>Test</artifactId> <source>1.8</source>
<version>0.0.1-SNAPSHOT</version> <target>1.8</target>
<packaging>war</packaging> </configuration>
<dependencies> </plugin> <plugin>
<dependency> <artifactId>maven-war-plugin</artifactId>
<groupId>org.apache.struts</groupId> <version>2.6</version>
<artifactId>struts2-core</artifactId> <configuration>
<version>2.3.20</version> <warSourceDirectory>WebContent</warS
</dependency> <dependency> ourceDirectory>
<groupId>javax.mail</groupId> <failOnMissingWebXml>false</failOnMiss
<artifactId>mail</artifactId> ingWebXml>
<version>1.4</version> </configuration>
</dependency> </dependencies> </plugin> </plugins> </build> </project>

Software Used
1. Eclipse IDE
2. Tomcat 8
3. JDK 8

CU IDOL SELF LEARNING MATERIAL (SLM)


Java Struts - II 249

Project Structure in Eclipse

Fig. 11.1: Project Structure in Eclipse


Add Struts 2 Filter

Define the struts 2 filters into web.xml

<?xml version="1.0" encoding="UTF-8"?> </welcome-file-list>


<web-app <filter>
xmlns:xsi="http://www.w3.org/2001/XMLSchema- <filter-name>struts2</filter-name>
instance" <filter-
xmlns="http://java.sun.com/xml/ns/javaee" class>org.apache.struts2.dispatcher.ng.filter.S
xsi:schemaLocation="http://java.sun.com/xml/ns/ja trutsPrepareAndExecuteFilter</filter-class>
vaeehttp://java.sun.com/xml/ns/javaee/web- </filter>
app_2_5.xsd" id="WebApp_ID" version="2.5">
<filter-mapping>
<display-
name>Struts2JavaMailApiExample</display- <filter-name>struts2</filter-name>
name> <url-pattern>/*</url-pattern>
<welcome-file-list> </filter-mapping>
<welcome-file>index.jsp</welcome-file> </web-app>

CU IDOL SELF LEARNING MATERIAL (SLM)


250 Advanced Internet Programming

Create Action Class


The next step is creating the Action Class that control the sending of email. In this Action
class, we have to call the method sendMail of SendEmail class and passes the parameter.

Struts2JavaMailAction.java
packageorg.websparrow; @Override
import public String execute() throws Exception {
com.opensymphony.xwork2.ActionSupport; obj = new SendEmail();
public class Struts2JavaMailAction extends resp = obj.sendMail(senderEmail,
ActionSupport { senderPassword, receiverEmail, subject,
private static final long serialVersionUID = message);
8676674317393590961L; if (resp == 1) {
// getter and setters... return "SUCCESS";
private String senderEmail, senderPassword, } else {
receiverEmail, subject, message;
return "ERROR";
SendEmailobj = null;
} } }
Int resp = 0;
Now create a class SendMail which has a method sendMail requires the below parameters.

 from: Email address of the sender. Gmail Account


 password: Password of above email.
 to: Email address of the receiver.
 subject: Subject of the email.
 msg: Contents of the message.

SendEmail.java
packageorg.websparrow; protectedPasswordAuthenticationgetPasswordAut
import java.util.Properties; hentication(){

impor tjavax.mail.Message; returnnewPasswordAuthentication(from,


password);
import javax.mail.MessagingException;
} });
import javax.mail.PasswordAuthentication;
try {
import javax.mail.Session;
Message message=new MimeMessage(session);
import javax.mail.Transport;
message.setFrom(newInternetAddress(from));
import javax.mail.internet.InternetAddress;
// recipients email address
import javax.mail.internet.MimeMessage;
message.setRecipients(Message.RecipientType.

CU IDOL SELF LEARNING MATERIAL (SLM)


Java Struts - II 251

public class SendEmail{ TO,InternetAddress.parse(to));


public intsendMail(String from, String // add the Subject of email
password, String to, String subject, String message.setSubject(subject);
msg) {
// message body
// setting gmailsmtp properties
message.setText(msg);
Properties props =newProperties();
Transport.send(message);
props.put("mail.smtp.auth","true");
return1;
props.put("mail.smtp.starttls.enable","true");
}catch(MessagingException e)
props.put("mail.smtp.host","smtp.gmail.com");
{
props.put("mail.smtp.port","587");
e.printStackTrace();
// check the authentication
return 0;
Session
session=Session.getInstance(props,newjava } } }
x.mail.Authenticator() {

Create View Component


In this example, we have created 3 JSP pages.

 index.jsp for taking the input from the user.


 success.jsp for email successfully sent.
 error.jsp for error message if any.

index.jsp

<%@taglib prefix="s" uri="/struts-tags"%> <div class="row">


<html> <div class="col-md-6">
<head> <div class="form-group">
<link rel="stylesheet" <label
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/ for="senderEmail">Login</label><input
css/bootstrap.min.css" /> type="text" name="senderEmail"
<title>Sending email using Struts 2 and JavaMail class="form-control" id="senderEmail"
API</title> placeholder="Sender email"
required="required" />
<style type="text/css">
<br><input type="password" class="form-
.jumbotron { control" id="senderPassword"
background: #358CCE; placeholder="Password"
color: #FFF; name="senderPassword"
required="required" />
border-radius: 0px;
</div>
}
<div class="form-group">

CU IDOL SELF LEARNING MATERIAL (SLM)


252 Advanced Internet Programming

.jumbotron-sm { <label for="receiverEmail">Receiver


padding-top: 24px; Email</label><input type="text"
name="receiverEmail" class="form-control"
padding-bottom: 24px; id="receiverEmail" placeholder="Receiver
} email"
.jumbotron small { required="required" />
color: #FFF; </div>
} <div class="form-group">
.h2 small { <label for="subject">Subject</label><input
font-size: 18px; type="text" class="form-control" id="subject"
name="subject" placeholder="Subject"
} required="required" />
</style> </div> </div>
</head> <div class="col-md-6">
<body> <div class="form-group">
<div class="jumbotronjumbotron-sm"> <label for="message"> Message</label>
<div class="container"> <textarea name="message" id="message"
<div class="row"> class="form-control" rows="11" cols="25"
<div class="col-sm-12 col-lg-12"> required="required"
placeholder="Message"></textarea>
<h2 class="h2">
</div>
WebSparrow.org <small>Sending email using
Struts 2 and JavaMail API</small> </div>

</h2> <div class="col-md-12">

</div> </div> </div> </div> <button type="submit" class="btnbtn-primary


pull-right" id="btnContactUs">Send
<div class="container"> Message</button>
<div class="row"> </div> </div> </form>
<div class="col-md-8"> </div> </div> </div>
<div class="well well-sm"> </div> </body> </html>
<form action="sendemail" method="post">

success.jsp

<html> .h2 small {


<head> font-size: 18px;
<link rel="stylesheet" }
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/ </style> </head> <body>
bootstrap.min.css" />
<div class="jumbotronjumbotron-sm">
<title>Sending email using Struts 2 and JavaMail
API</title> <div class="container">

CU IDOL SELF LEARNING MATERIAL (SLM)


Java Struts - II 253

<style type="text/css"> <div class="row">


.jumbotron { <div class="col-sm-12 col-lg-12">
background: #358CCE; <h2 class="h2">
color: #FFF; WebSparrow.org <small>Sending email
border-radius: 0px; using Struts 2 and JavaMail API</small>

} </h2>

.jumbotron-sm { </div> </div> </div> </div>

padding-top: 24px; <div class="container">

padding-bottom: 24px; } <p style="color: green;">Email Sent


Successfully</p>
.jumbotron small {
</div>
color: #FFF; }
</body> </html>

error.jsp

<html> .h2 small {


<head> font-size: 18px;
<link rel="stylesheet" }
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bo </style> </head>
otstrap.min.css" />
<body>
<title>Sending email using Struts 2 and JavaMail
API</title> <div class="jumbotronjumbotron-
sm">
<style type="text/css">
<div class="container">
.jumbotron {
<div class="row">
background: #358CCE;
<div class="col-sm-12 col-lg-12">
color: #FFF;
<h2 class="h2">
border-radius: 0px;
WebSparrow.org <small>Sending
} email using Struts 2 and JavaMail
.jumbotron-sm { API</small>
padding-top: 24px; </h2> </div> </div> </div> </div>
padding-bottom: 24px; <div class="container">
} <p style="color: red;">Some error
.jumbotron small { occurred. For more info check the
console.</p>
color: #FFF;
</div> </body> </html>
}

CU IDOL SELF LEARNING MATERIAL (SLM)


254 Advanced Internet Programming

Configuration File
Create the struts.xml file in the source package and map the Action class.

struts.xml

<?xml version="1.0" encoding="UTF-8" ?> <package name="default" namespace="/"


<!DOCTYPE struts PUBLIC extends="struts-default">

"-//Apache Software Foundation//DTD Struts <action name="sendemail"


Configuration 2.0//EN" class="org.websparrow.Struts2JavaMailAction"
>
"http://struts.apache.org/dtds/struts-2.0.dtd">
<result
<struts> name="SUCCESS">/success.jsp</result>
<constant name="struts.devMode" value="true" <result name="ERROR">/error.jsp</result>
/>
</action> </package> </struts>

11.3 Validation
To avoid the wrong values, we need to perform validation on forms where user submits some
values. For example, if user writes his/her email id as abc, we need to give error message to the
user that the given email id is not correct. So, that we can have only valuable informations.

There are three ways to perform validation in struts 2.

1. By Custom Validation: Here, we must implement the Validateable interface (or extend
ActionSupport class) and provide the implementation of validate method.
2. By Input Validation (built-in validators) : Struts 2 provides a lot of predefined that can
be used in struts 2 application to perform validation.
Struts 2 provides following bundled validators.

 requiredstring validator
 stringlength validator
 email validator
 date validator
 int validator
 double validator
 url validator
 regex validator

CU IDOL SELF LEARNING MATERIAL (SLM)


Java Struts - II 255

3. By Ajax Validation (built-in validators with ajax): If we don’t want to refresh the
page, we can use jsonValidation interceptor to perform validation with ajax.
Client side validation is usually achieved using Javascript. However, one should not rely
upon client side validation alone. The best practices suggest that the validation should be
introduced at all levels of your application framework. Now let us look at two ways of adding
validation to our Struts project.

Here, we will take an example of an Employee whose name and age should be captured
using a simple page, and we will put these two validations to make sure that the user always
enters a name and age which should be in a range between 28 and 65.

Let us start with the main JSP page of the example.

Create Main Page


Let us write main page JSP file index.jsp, which will be used to collect Employee related
information mentioned above.

<%@ page language = "java" contentType <body>


= "text/html; charset = ISO-8859-1" <s:form action = "empinfo" method = "post">
pageEncoding = "ISO-8859-1"%> <s:textfield name = "name" label = "Name" size =
<%@ taglib prefix = "s" uri = "/struts- "20" />
tags"%> <s:textfield name = "age" label = "Age" size = "20"
<!DOCTYPE html PUBLIC "-//W3C//DTD />
HTML 4.01 Transitional//EN" <s:submit name = "submit" label = "Submit"
"http://www.w3.org/TR/html4/loose.dtd"> align="center" />
<html> <head> </s:form>
<title>Employee Form</title> </head> </body> </html>
The index.jsp makes use of Struts tag, which we have not covered yet, but we will study
them in tags related chapters. But for now, just assume that the s:textfield tag prints a input field,
and the s:submit prints a submit button. We have used label property for each tag which creates
label for each tag.

Create Views
We will use JSP file success.jsp which will be invoked in case defined action returns
SUCCESS.

<%@ page language = "java" contentType = <html> <head>


"text/html; charset = ISO-8859-1" <title>Success</title>

CU IDOL SELF LEARNING MATERIAL (SLM)


256 Advanced Internet Programming

pageEncoding = "ISO-8859-1"%> </head>


<%@ taglib prefix = "s" uri = "/struts-tags"%> <body>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML Employee Information is captured
4.01 Transitional//EN" successfully.
"http://www.w3.org/TR/html4/loose.dtd"> </body> </html>

Create Action
So let us define a small action class Employee, and then add a method called validate() as
shown below in Employee.java file. Make sure that your action class extends the ActionSupport
class, otherwise your validate method will not be executed.

package com.tutorialspoint.struts2; public intgetAge() {


import return age;
com.opensymphony.xwork2.ActionSupport; }
public class Employee extends ActionSupport { public void setAge(int age) {
private String name; this.age = age;
privateint age; }
public String execute() { public void validate() {
return SUCCESS; if (name == null || name.trim().equals("")) {
} addFieldError("name","The name is required");
public String getName() { }
return name; if (age < 28 || age > 65) {
} addFieldError("age","Age must be in between
public void setName(String name) { 28 and 65");
this.name = name; } } } }
As shown in the above example, the validation method checks whether the ‘Name’ field has
a value or not. If no value has been supplied, we add a field error for the ‘Name’ field with a
custom error message. Secondly, we check if entered value for ‘Age’ field is in between 28 and
65 or not, if this condition does not meet we add an error above the validated field.

Configuration Files
Finally, let us put everything together using the struts.xml configuration file as follows –

<?xml version = "1.0" Encoding = "UTF-8"?> <action name = "empinfo"


<!DOCTYPE struts PUBLIC class =
"-//Apache Software Foundation//DTD Struts "com.tutorialspoint.struts2.Employee"
Configuration 2.0//EN" method = "execute">

CU IDOL SELF LEARNING MATERIAL (SLM)


Java Struts - II 257

"http://struts.apache.org/dtds/struts-2.0.dtd"> <result name =


<struts> "input">/index.jsp</result>

<constant name = "struts.devMode" value = "true" /> <result name =


"success">/success.jsp</result>
<package name = "helloworld" extends = "struts-
default"> </action> </package> </struts>

Following is the content of web.xml file –

<?xml version = "1.0" Encoding = "UTF-8"?> <welcome-file>index.jsp</welcome-file>


<web-app xmlns:xsi = </welcome-file-list>
"http://www.w3.org/2001/XMLSchema- <filter>
instance"
<filter-name>struts2</filter-name>
xmlns = "http://java.sun.com/xml/ns/javaee"
<filter-class>
xmlns:web =
"http://java.sun.com/xml/ns/javaee/web- org.apache.struts2.dispatcher.FilterDispatcher
app_2_5.xsd" </filter-class>
xsi:schemaLocation = </filter>
"http://java.sun.com/xml/ns/javaee <filter-mapping>
http://java.sun.com/xml/ns/javaee/web- <filter-name>struts2</filter-name>
app_3_0.xsd"
<url-pattern>/*</url-pattern>
id = "WebApp_ID" version = "3.0">
</filter-mapping>
<display-name>Struts 2</display-name>
</web-app>
<welcome-file-list>
Now, right click on the project name and click Export > WAR File to create a War file. Then
deploy this WAR in the Tomcat’s webapps directory. Finally, start Tomcat server and try to
access URL http://localhost:8080/HelloWorldStruts2/index.jsp. This will produce the following
screen

Now do not enter any required information, just click on Submit button. You will see the
following result –

CU IDOL SELF LEARNING MATERIAL (SLM)


258 Advanced Internet Programming

Enter the required information but enter a wrong From field, let us say name as "test" and
age as 30, and finally click on Submit button. You will see the following result −

11.4 Localization
Internationalization (i18n) is the process of planning and implementing products and services
so that they can easily be adapted to specific local languages and cultures, a process called
localization. The internationalization process is called translation or localization enablement.

Internationalization is abbreviated i18n because the word starts with the letter “i” and ends
with “n”, and there are 18 characters between the first i and the last n.

Struts2 provides localization, i.e., internationalization (i18n) support through resource


bundles, interceptors and tag libraries in the following places −

 The UI Tags
 Messages and Errors.
 Within action classes.

CU IDOL SELF LEARNING MATERIAL (SLM)


Java Struts - II 259

Resource Bundles
Struts2 uses resource bundles to provide multiple language and locale options to the users of
the web application. You don’t need to worry about writing pages in different languages. All you
have to do is to create a resource bundle for each language that you want. The resource bundles
will contain titles, messages, and other text in the language of your user. Resource bundles are the
file that contains the key/value pairs for the default language of your application.

The simplest naming format for a resource file is −

Here, bundlename could be ActionClass, Interface, SuperClass, Model, Package, Global


resource properties. Next part language_country represents the country locale for example,
Spanish (Spain) locale is represented by es_ES, and English (United States) locale is represented
by en_US etc. where you can skip country part which is optional.

When you reference a message element by its key, Struts framework searches for a
corresponding message bundle in the following order −

 ActionClass.properties
 Interface.properties
 SuperClass.properties
 model.properties
 package.properties
 struts.properties
 global.properties
To develop your application in multiple languages, you should maintain multiple property
files corresponding to those languages/locale and define all the content in terms of key/value pairs.

For example, if you are going to develop your application for US English (Default), Spanish,
and French, then you would have to create three properties files. Here I will use global.properties
file only, you can also make use of different property files to segregate different type of messages.

 global.properties: By default English (United States) will be applied


 global_fr.properties: This will be used for Franch locale.
 global_es.properties: This will be used for Spanish locale.

CU IDOL SELF LEARNING MATERIAL (SLM)


260 Advanced Internet Programming

Access the messages


There are several ways to access the message resources, including getText, the text tag, key
attribute of UI tags, and the i18n tag. Let us see them in brief −

To display i18n text, use a call to getText in the property tag, or any other tag, such as the UI
tags as follows −

<s:property value = "getText('some.key')" />

The text tag retrieves a message from the default resource bundle, i.e., struts.properties

<s:text name = "some.key" />

The i18n tag pushes an arbitrary resource bundle on to the value stack. Other tags within the
scope of the i18n tag can display messages from that resource bundle−

<s:i18n name = "some.package.bundle">


<s:text name = "some.key" />
</s:i18n>

The key attribute of most UI tags can be used to generate a message from a resource bundle-

<s:textfield key = "some.key" name = "textfieldName"/>

his example tries to show in a simple and straight forward way of creating a web application
with Internationalization or I18N capability.

In this example, we are creating following pages:

1. HelloWorld.java
2. HelloWorld_en.properties and HelloWorld _hi.properties
3. HelloWorld.jsp
4. struts.xml

1. Create the Action Class


/** */
* @author LEE private String message;
*/ /**
packagecom.nirvanaitedge.lee; * Return Message property.
import *

CU IDOL SELF LEARNING MATERIAL (SLM)


Java Struts - II 261

com.opensymphony.xwork2.ActionSupport; * @return Message property


public class HelloWorld extends ActionSupport */
{ public String getMessage() {
public String execute() throws Exception { return message;
setMessage(getText(MESSAGE)); }
return SUCCESS; /**
} * Set Message property.
/** *
* Provide default value for Message property. * @param message Text to display on
*/ HelloWorld page.
public static final String MESSAGE = */
"HelloWorld.message"; public void setMessage(String message) {
/** this.message = message;
* Field for Message property. } }

2. Create the Properties file


1.HelloWorld_en.properties 2.HelloWorld_hi.properties
HelloWorld.message=Good Morning! HelloWorld.message=Suprabhat!

3. Create HelloWorld.jsp for input


<%-- <h3>Languages</h3>
Document : newjsp <ul> <li>
Created on : 14 Jan, 2015, 6:46:19 PM <s:url id="url" action="HelloWorld">
Author : LEE <s:param
--%> name="request_locale">en</s:param>

<%@ page contentType="text/html; </s:url>


charset=UTF-8" %> Click <s:ahref="%{url}">here</s:a> to greet in
<%@ taglib prefix="s" uri="/struts-tags" %> English.

<html> </li> <li>

<head> <s:url id="url" action="HelloWorld">

<title><s:text <s:param name="request_locale">in</s:param>


name="HelloWorld.message"/></title> </s:url>
</head> Click <s:ahref="%{url}" >here</s:a> to greet in
<body> Hindi.

<h2><s:property value="message"/></h2> </li> </ul> </body> </html>

CU IDOL SELF LEARNING MATERIAL (SLM)


262 Advanced Internet Programming

4 Define action in struts.xml


<struts>
<package name="com.nirvanaitedge.lee" namespace="/com.nirvanaitedge.lee"
extends="struts-default">
<action name="HelloWorld" class="com.nirvanaitedge.lee.HelloWorld">
<result>/com.nirvanaitedge.lee/HelloWorld.jsp</result>
</action> </package> </struts>

Make a note that we don ’ t need to specify ‘ method = “ execute ” ’ as action tag attribute
because Struts by default checks the ‘execute’ method if no method is specified. The ‘method’
attribute of action class is used only when we are using a method name other than ‘execute’ who’
s result we need to map in struts.xml file.

Running the Application:


HelloWorld.jsp is loaded with two hyperlinks. Clicking on any of the links will greet in the
specific language.

Clicking on 1st hyperlink greets in English.

Clicking on second hyperlink greets in Hindi.

CU IDOL SELF LEARNING MATERIAL (SLM)


Java Struts - II 263

11.4 Type Conversion


Struts uses a variety of type converters under the covers to do the heavy lifting.

For example, if you have an integer attribute in your Action class, Struts automatically
converts the request parameter to the integer attribute without you doing anything. By default,
Struts comes with a number of type converters like:

 Integer, Float, Double, Decimal


 Date and Datetime
 Arrays and Collections
 Enumerations
 Boolean
 BigDecimal

11.5 Exception Handling


Struts provides an easy way for handling uncaught exceptions which might be thrown during
execution of action classes. Uncaught exceptions are ones which are not caught by the regular try-
catch clause. There are two methods for handing uncaught exceptions in Struts:

 Global exception handling: specifies exception mappings (exception type - view name)
which apply to all action classes in a Struts package.
 Exception handling per action: specifies exception mappings which apply to a specific
action class.

CU IDOL SELF LEARNING MATERIAL (SLM)


264 Advanced Internet Programming

Understanding the Internal Working of Exception Interceptor


If there occurs exception, it is wrapped in ExceptionHolder and pushed in the valuestack so
that we can easily access exception object from the result.

Parameters of exception interceptor

There are 3 parameters defined for exception interceptor. All are optional.
Table 11.4: Parameters Defined for Exception Interceptor
Parameter Description
logEnabled specifies log should be enabled or not. You can pass true or false.
logLevel specifies the log level. It may be trace, debug, info, warn, error, fatal. Default log level
is debug.
logCategory specifies the log category eg. com.mycompany.app. The default is
com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor…
Struts provides an easier way to handle uncaught exception and redirect users to a dedicated
error page. You can easily configure Struts to have different error pages for different exceptions.

Struts makes the exception handling easy by the use of the “exception” interceptor. The
“exception” interceptor is included as part of the default stack, so you don’t have to do anything
“extra to configure it. It is available out-of-the-box ready for you to use.

Let us see a simple Hello World example with some modification in HelloWorldAction.java
file. Here, we deliberately introduced a NullPointer Exception in our HelloWorldAction action
code.

package com.tutorialspoint.struts2; x = x.substring(0);


import return SUCCESS; }
com.opensymphony.xwork2.ActionSupport; public String getName() {
public class HelloWorldAction extends return name; }
ActionSupport{
public void setName(String name) {
private String name;
this.name = name;
public String execute() {
} }
String x = null;
Let us keep the content of HelloWorld.jsp as follows −

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


<%@ taglib prefix = "s" uri = "/struts-tags" %>
<html>

CU IDOL SELF LEARNING MATERIAL (SLM)


Java Struts - II 265

<head> <title>Hello World</title> </head>


<body>
Hello World, <s:property value = "name"/>
</body> </html>

Following is the content of index.jsp –

<%@ page language = "java" contentType = </head>


"text/html; charset = ISO-8859-1" <body>
pageEncoding = "ISO-8859-1"%> <h1>Hello World From Struts2</h1>
<%@ taglib prefix = "s" uri = "/struts-tags"%> <form action = "hello">
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML <label for = "name">Please enter your
4.01 Transitional//EN" name</label><br/>
"http://www.w3.org/TR/html4/loose.dtd"> <input type = "text" name = "name"/>
<html> <input type = "submit" value = "Say Hello"/>
<head> <title>Hello World</title> </form> </body> </html>
Your struts.xml should look like –

<?xml version = "1.0" Encoding = "UTF-8"?> <action name = "hello"


<!DOCTYPE struts PUBLIC class =
"-//Apache Software Foundation//DTD Struts "com.tutorialspoint.struts2.HelloWorldAction
Configuration 2.0//EN" "

"http://struts.apache.org/dtds/struts-2.0.dtd"> method = "execute">

<struts> <result name =


"success">/HelloWorld.jsp</result>
<constant name = "struts.devMode" value = "true"
/> </action>

<package name = "helloworld" extends = "struts- </package>


default"> </struts>
Now right click on the project name and click Export > WAR File to create a War file. Then
deploy this WAR in the Tomcat’s webapps directory. Finally, start Tomcat server and try to
access URL http://localhost:8080/HelloWorldStruts2/index.jsp. This will produce the following
screen −

CU IDOL SELF LEARNING MATERIAL (SLM)


266 Advanced Internet Programming

Enter a value “Struts2” and submit the page. You should see the following page –

As shown in the above example, the default exception interceptor does a great job of
handling the exception.

Let us now create a dedicated error page for our Exception. Create a file called Error.jsp with
the following contents −

<%@ page language = "java" contentType = "text/html; charset = ISO-8859-1"


pageEncoding = "ISO-8859-1"%>
<%@ taglib prefix = "s" uri = "/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head> <title></title> </head>
<body>
This is my custom error page
</body> </html>

CU IDOL SELF LEARNING MATERIAL (SLM)


Java Struts - II 267

Let us now configure Struts to use this error page in case of an exception. Let us modify the
struts.xml as follows –

<?xml version = "1.0" Encoding = "UTF-8"?> <action name = "hello"


<!DOCTYPE struts PUBLIC class =
"-//Apache Software Foundation//DTD Struts "com.tutorialspoint.struts2.HelloWorldAction"
Configuration 2.0//EN" method = "execute">
"http://struts.apache.org/dtds/struts-2.0.dtd"> <exception-mapping exception =
<struts> "java.lang.NullPointerException"

<constant name = "struts.devMode" value = result = "error" />


"true" /> <result name =
<package name = "helloworld" extends = "success">/HelloWorld.jsp</result>
"struts-default"> <result name = "error">/Error.jsp</result>
</action> </package> </struts>
As shown in the example above, now we have configured Struts to use the dedicated
Error.jsp for the NullPointerException. If you rerun the program now, you shall now see the
following output −

11.6 Annotation
Struts 2 provides you convenient way to create struts application using annotations. So, there
is no need to have struts.xml file.

As we have said earlier, there are 2 ways to use zero configuration file (no struts.xml file).

1. By convention
2. By annotation
Annotations used in struts 2 application.

CU IDOL SELF LEARNING MATERIAL (SLM)


268 Advanced Internet Programming

For simple annotation example of struts 2, we can use 3 annotations:

1. @Action annotation is used to mark the action class.


2. @Results annotation is used to define multiple results for one action.
3. @Result annotation is used to display single result.
Struts provides two forms of configuration. The traditional way is to use the struts.xml file
for all the configurations. We have seen so many examples of that in the tutorial so far. The other
way of configuring Struts is by using the Java 5 Annotations feature. Using the struts annotations,
we can achieve Zero Configuration.

To start using annotations in your project, make sure you have included the following jar
files in your WebContent/WEB-INF/lib folder –

 struts2-convention-plugin-x.y.z.jar  commons-logging-api-x.y.jar
 asm-x.y.jar  freemarker-x.y.z.jar
 antlr-x.y.z.jar  javassist-.xy.z.GA
 commons-fileupload-x.y.z.jar  ognl-x.y.z.jar
 commons-io-x.y.z.jar  struts2-core-x.y.z.jar
 commons-lang-x.y.jar  xwork-core.x.y.z.jar
 commons-logging-x.y.z.jar
Now, let us see how you can do away with the configuration available in the struts.xml file
and replace it with annotaions.

To explain the concept of Annotation in Struts2, we would have to reconsider our validation
example explained in Struts2 Validations chapter.

Here, we shall take an example of an Employee whose name, age would be captured using a
simple page, and we will put two validations to make sure that ÜSER always enters a name and
age should be in between 28 and 65.

Let us start with the main JSP page of the example.

Create Main Page


Let us write main page JSP file index.jsp, which is used to collect Employee related
information mentioned above.

CU IDOL SELF LEARNING MATERIAL (SLM)


Java Struts - II 269

<%@ page language <title>Employee Form</title>


="java"contentType="text/html; charset = </head> <body>
ISO-8859-1"
<s:formaction="empinfo"method="post">
pageEncoding="ISO-8859-1"%>
<s:textfieldname="name"label="Name"size="20"/>
<%@taglib prefix ="s"uri="/struts-tags"%>
<s:textfieldname="age"label="Age"size="20"/>
<!DOCTYPE html PUBLIC "-//W3C//DTD
HTML 4.01 Transitional//EN" <s:submitname="submit"label="Submit"align="center"
/>
"http://www.w3.org/TR/html4/loose.dtd">
</s:form>
<html>
</body>
<head>
</html>
The index.jsp makes use of Struts tag, which we have not covered yet but we will study them
in tags related chapters. But for now, just assume that the s:textfield tag prints a input field, and
the s:submit prints a submit button. We have used label property for each tag which creates label
for each tag.

Create Views
We will use JSP file success.jsp which will be invoked in case the defined action returns
SUCCESS.

<%@ page language ="java"contentType="text/html; <html>


charset = ISO-8859-1" pageEncoding="ISO-8859- <head> <title>Success</title>
1"%>
</head>
<%@taglib prefix ="s"uri="/struts-tags"%>
<body>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01
Transitional//EN" Employee Information is captured
successfully.
"http://www.w3.org/TR/html4/loose.dtd">
</body> </html>

Create Action
This is the place where annotation is used. Let us re-define action class Employee with
annotation, and then add a method called validate () as shown below in Employee.java file. Make
sure that your action class extends the ActionSupport class, otherwise your validate method will
not be executed.

package com.tutorialspoint.struts2; @Action(value="/empinfo")


import publicString execute() {
com.opensymphony.xwork2.ActionSupport; return SUCCESS;
import

CU IDOL SELF LEARNING MATERIAL (SLM)


270 Advanced Internet Programming

org.apache.struts2.convention.annotation.Action; }
import @RequiredFieldValidator( message ="The
org.apache.struts2.convention.annotation.Result; name is required")
import publicStringgetName() {
org.apache.struts2.convention.annotation.Results return name;
;
}
import
com.opensymphony.xwork2.validator.annotations. publicvoidsetName(String name) {
*; this.name = name;
@Results({ }
@Result(name @IntRangeFieldValidator(message ="Age
="success",Location="/success.jsp"), must be in between 28 and 65", min ="29",
@Result(name ="input",Location="/index.jsp") max ="65")

}) publicintgetAge() {

publicclassEmployeeextendsActionSupport{ return age; }

privateString name; publicvoidsetAge(int age){

privateint age; this.age= age;


} }
We have used few annotations in this example. Let me go through them one by one −

 First, we have included the Results annotation. A Results annotation is a collection of


results.
 Under the results annotation, we have two result annotations. The result annotations have
the name that correspond to the outcome of the execute method. They also contain a
location as to which view should be served corresponding to return value from execute()
 The next annotation is the Action annotation. This is used to decorate the execute()
method. The Action method also takes in a value which is the URL on which the action
is invoked.
 Finally, I have used two validation annotations. I have configured the required field
validator on name field and the integer range validator on the age field. I have also
specified a custom message for the validations.

Configuration Files
We really do not need struts.xml configuration file, so let us remove this file and let us check
the content of web.xml file –

<?xml version ="1.0"Encoding="UTF-8"?> <filter-name>struts2</filter-name>


<web- <filter-class>

CU IDOL SELF LEARNING MATERIAL (SLM)


Java Struts - II 271

appxmlns:xsi="http://www.w3.org/2001/XMLSchem org.apache.struts2.dispatcher.FilterDispatc
a-instance" her
xmlns="http://java.sun.com/xml/ns/javaee" </filter-class>
xmlns:web="http://java.sun.com/xml/ns/javaee/web- <init-param>
app_2_5.xsd" <param-name>struts.devMode</param-
xsi:schemaLocation="http://java.sun.com/xml/ns/jav name>
aee <param-value>true</param-value>
http://java.sun.com/xml/ns/javaee/web- </init-param>
app_3_0.xsd" </filter>
id="WebApp_ID"version="3.0"> <filter-mapping>
<display-name>Struts 2</display-name> <filter-name>struts2</filter-name>
<welcome-file-list> <url-pattern>/*</url-pattern>
<welcome-file>index.jsp</welcome-file> </filter-mapping>
</welcome-file-list> </web-app>
<filter>
Now, right click on the project name and click Export > WAR File to create a War file. Then
deploy this WAR in the Tomcat’ webapps directory. Finally, start Tomcat server and try to access
URL http://localhost:8080/HelloWorldStruts2/index.jsp. This will produce the following screen −

Now do not enter any required information, just click on Submit button. You will see the
following result –

CU IDOL SELF LEARNING MATERIAL (SLM)


272 Advanced Internet Programming

Enter the required information but enter a wrong From field, let us say name as "test" and
age as 30, and finally click on Submit button. You will see the following result –

11.7 Tags and Integrations


Struts 2 Data Tags Example
In this example you will learn how to use the property tag, the set tag and the push tag. These
tags are part of the Struts 2 Data Tags. Before we see the syntax of each tag you need to know
what an ActionContext and a ValueStack is.

ActionContext
Object 0
parameters

application
Value Stack attr

Object n-1 session

Object n request

 The ActionContext is a global storage area that holds all the data associated with the
processing of a request.
 The ActionContext is thread local this makes the Struts 2 actions thread safe.
 The ValueStack is the part of the ActionContext. In Struts 2 actions resides on the
ValueStack.

CU IDOL SELF LEARNING MATERIAL (SLM)


Java Struts - II 273

The Property Tag


The property tag is used to retrieve the data from the ValueStack or some other object in the
ActionContext like application or session. Let’s see how to display the following details using the
property tag.

Our Action class AlbumInfoAction contains the following piece of code.

package vaannila; public String execute() {


public class AlbumInfoAction{ return "success"; }
private String title; public String getTitle() {
private Artist artist; return title; }
public String populate() public void setTitle(String title) {
{ this.title = title; }
title = "Thriller"; public Artist getArtist() {
artist = new Artist("Michael Jackson","King of return artist; }
pop"); public void setArtist(Artist artist) {
return "populate"; this.artist = artist;
} } }

Struts 2 Property Tag Example


Our Artist data class contains the following code.

package vaannila; public void setName(String name) {


public class Artist { this.name = name;
private String name; }
private String bio; public String getBio() {
Artist(String name, String bio) return bio;
{ }

CU IDOL SELF LEARNING MATERIAL (SLM)


274 Advanced Internet Programming

this.name = name; public void setBio(String bio) {


this.bio = bio; } this.bio = bio;
public String getName() { } }
return name; }
Let’s see how we can access the action class attributes using the property tag in the jsp page.
The albumDetails.jsp page contains the following code.

<%@taglib uri="/struts-tags" prefix="s"%> <body>


<html> <div class="content">
<head> <b>Album Title :</b>
<s:head /> <s:property value="title" /> <br>
<style type="text/css"> <b>Artist Name :</b>
@import url(style.css); <s:property value="artist.name" />
</style> <br> <b>Artist Bio :</b>
<title>Album Details</title> <s:property value="artist.bio" />
</head> <br> </div> </body> </html>
As you can see title is the property of the AlbumInfoAction so we can access it directly. But
name and bio are properties of the Artist class so to access them we need to go one step deeper.
We need to use a second-level OGNL expression to access them.

Struts 2 Set Tag Example

The set tag is used to assign a property value to another name. This helps in accessing the
property in a faster and easier way. To access the artist name we need to go one level deeper and
fetch it when we used the property tag, instead you can assign the value to another property in the
ActionContext and access it directly. The following code shows how to do this.

<s:set name="artistName" value="artist.name" />


<s:set name="artistBio" value="artist.bio" />
<b>Album Title :</b> <s:property value="title" /> <br>
<b>Artist Name :</b> <s:property value="#artistName" /> <br>
<b>Artist Bio :</b> <s:property value="#artistBio" /> <br>

The property artistName and artistBio will now be stored in the ActionContext. To refer then
you need to use the following syntax #objectName.

You can also place the property value in the session map in the following way. Now the
value artistName and artistBio will persist throughout the session.

CU IDOL SELF LEARNING MATERIAL (SLM)


Java Struts - II 275

<s:set name="artistName" value="artist.name" scope="session" />


<s:set name="artistBio" value="artist.bio" scope="session" />
<b>Album Title :</b> <s:property value="title" /> <br>
<b>Artist Name :</b> <s:property value="#session['artistName']" /> <br>
<b>Artist Bio :</b> <s:property value="#session['artistBio']" /> <br>

In the same way you can also store the values in other maps available in the ActionContext.

Struts 2 Push Tag Example


You can push a value into the ValueStack using the push tag. The value we pushed using
push tag will be on top of the ValueStack, so it can be easily referenced using the first-level
OGNL expression instead of a deeper reference. The following code shows how to do this.

<b>Album Title :</b> <s:property value="title" /> <br>


<s:push value="artist">
<b>Artist Name :</b> <s:property value="name" /> <br>
<b>Artist Bio :</b> <s:property value="bio" /> <br>
</s:push>

Control tags are used for manipulation and navigation of data from a collection. Some of the
important Struts 2 control tags are:

if-elseif-else tags: These are the basic control tags used for conditional logic in result pages.
elseif and else tags always work with if tags. if and elseif tags have test attribute where we can
provide expression that should result in boolean values, true or false. Example usage is:

<s:if test="expression">
//do something
</s:if>
<s:elseif test="expression">
//do something
</s:elseif>
<s:else>
//do something
</s:else>

else tag doesn’t have any attribute.

CU IDOL SELF LEARNING MATERIAL (SLM)


276 Advanced Internet Programming

iterator tag: We can use iterator tag to loop through a collection of objects. The collection
could be array, list, map etc. iterator tags provide option to define a variable in the ActionContext
with status attribute. IteratorStatus provides the current status of iterator and expose some
methods to get count, odd or even, first or last element etc. Example usage is:

<s:iterator value="list" status="itStatus">


<s:property/>
</s:iterator>

For iterating a map, we need to provide property tag value as key and value.

<s:iterator value="map">
Key=<s:property value="key"/>, Value=<s:property value="value"/><br>
</s:iterator>

The other control tags are provided to work with iterators.

append tag: This tag can be used to append multiple lists and then use them in iterator. The
lists to append are provided with param tag and lists are appended one after another. So first list
elements will be retrieved first by iterator then second list elements and so on. Example usage is:

<s:append var="myList">
<s:param value="list1"></s:param>
<s:param value="list2"></s:param>
</s:append>
<s:iterator value="#myList">
<s:property/>
</s:iterator>

merge tag: We can use merge tag to merge multiple lists. The first elements from all the lists
are merged first, then second element and so on. We can use merge tag like below.

<s:merge var="myList">
<s:param value="list1"></s:param>
<s:param value="list2"></s:param>
</s:merge>
<s:iterator value="#myList">
<s:property/><br>
</s:iterator>

CU IDOL SELF LEARNING MATERIAL (SLM)


Java Struts - II 277

sort tag: We can use sort tag to get the sorted list. We need to provide a comparator to be
used for sorting the list. We can use it like below.

<s:bean name="MyComparator" var="myComparator"></s:bean>


<s:sort comparator="#myComparator" source="list">
<s:iterator>
<s:property/><br>
</s:iterator>
</s:sort>

subset tag: We can use subset tag to get the subset of an iterator. We need to provide a
Decider implementation that will be used by subset tag to filter elements as whether to include
them in iterator or not. We can use it like below.

<s:subset source="list" decider="myDecider">


<s:iterator>
<s:property/><br>
</s:iterator>
</s:subset>

generator tag: We can use generator tag to create an iterator from given values. We can
provide separator to use the delimiter for the values and we can also provide Converter
implementation to convert the String to an Object. We can use it like below.

<s:generator val="%{'1,2,3'}" separator="," var="intsIterator" />


<s:iterator value="#intsIterator">
<s:property /><br/>
</s:iterator>

Struts 2 Tiles Framework Integration Tutorial Example


We can customize the layout of the struts 2 application by integrating with tiles framework.

A web page can contain many parts (known as tile) such as header, left pane, right pane,
body part, footer etc. In tiles framework, we manage all the tile by our Layout Manager page.

Advantage of Tiles Framework


There are following advantages of tiles framework:

CU IDOL SELF LEARNING MATERIAL (SLM)


278 Advanced Internet Programming

 Customization by centralized page We can customize the layout of all the pages by
single page (centralized page) only.
 Code reusability A single part e.g. header or footer can be used in many pages. So it
saves coding.
 Easy to modify If any part (tile) is modified, we don’t need to change many pages.
 Easy to remove If any part (tile) of the page is removed, we don’t need to remove the
code from all the pages. We can remove the tile from our layout manager page.

HEADER

LEFT CENTER RIGHT

FOOTER

Fig 11.2: Tile Framework


Steps to create tiles application
The steps are as follows:

1. Add tiles library in your application


2. Define Struts2TilesListener in web.xml file
3. Create the input page (index.jsp)
4. Create the Action class
5. Extend the tiles-default package in your package and define all the result type as tiles in
struts.xml file
6. Create the tiles.xml file and define all the tiles definitions
7. Create the LayoutManager page
8. Create the View components

1. Add tiles Library in your Application


If you are using myeclipse IDE, you can add tiles library by right click on the project ->
Build Path -> Add Library -> Add Myeclipse Library -> Select the Struts 2 tiles library -> ok.

CU IDOL SELF LEARNING MATERIAL (SLM)


Java Struts - II 279

If you are using eclipse or Netbeans IDE, you need to add the required tiles library in your
project.

Steps to Create Tiles Application


The steps are as follows:

1. Add tiles library in your application


2. Define Struts2TilesListener in web.xml file
3. Create the input page (index.jsp)
4. Create the Action class
5. Extend the tiles-default package in your package and define all the result type as tiles in
struts.xml file
6. Create the tiles.xml file and define all the tiles definitions
7. Create the LayoutManager page
8. Create the View components

1. Add tiles library in Your Application


If you are using myeclipse IDE, you can add tiles library by right click on the project ->
Build Path -> Add Library -> Add Myeclipse Library -> Select the Struts 2 tiles library -> ok.

If you are using eclipse or Netbeans IDE, you need to add the required tiles library in your
project.

Define Struts2TilesListener in web.xml file


Provide entry of listener class Struts2TilesListener in the web.xml file.

web.xml <filter-class>
<?xml version="1.0" encoding="UTF-8"?> org.apache.struts2.dispatcher.ng.filter.StrutsPrepare
<web-app version="2.5" AndExecuteFilter
</filter-class>
xmlns="http://java.sun.com/xml/ns/javaee" </filter>
xmlns:xsi="http://www.w3.org/2001/XMLS <filter-mapping>
chema-instance"
xsi:schemaLocation="http://java.sun.com/ <filter-name>struts2</filter-name>
xml/ns/javaee <url-pattern>/*</url-pattern>
http://java.sun.com/xml/ns/javaee/web- </filter-mapping>
app_2_5.xsd"> <listener>

CU IDOL SELF LEARNING MATERIAL (SLM)


280 Advanced Internet Programming

<welcome-file-list> <listener-
<welcome-file>index.jsp</welcome-file> class>org.apache.struts2.tiles.StrutsTilesListener</lis
tener-class>
</welcome-file-list>
</listener>
<filter>
</web-app>
<filter-name>struts2</filter-name>

3. Create the input page (index.jsp)


index.jsp
<%@ taglib uri="/struts-tags" prefix="s" %>

<s:form action="login">
<s:textfield name="name" label="Name"></s:textfield>
<s:password name="password" label="Password"></s:password>
<s:submit value="login"></s:submit>
</s:form>

4. Create the action class


This action class contains one field name and defines the execute method.

Login.java if(password.equals("admin")) {
package com.javatpoint; return "success";
public class Login { }
private String name,password; else{
//getters and setters return "error";
public String execute(){ } } }

5. Inherit the tiles-default package and define all the result type as tiles in struts.xml
This xml file defines one package with one action and two results.

struts.xml <action name="login"


<?xml version="1.0" encoding="UTF-8" ?> class="com.javatpoint.Login">
<!DOCTYPE struts PUBLIC "-//Apache <result name="success" type="tiles">login-
Software Foundation//DTD Struts Configuration success</result>
2.1//EN"
<result name="error" type="tiles">login-
"http://struts.apache.org/dtds/struts-2.1.dtd"> error</result>
<struts>
</action>
<package name="abc" extends="tiles-default"
> </package> </struts>

CU IDOL SELF LEARNING MATERIAL (SLM)


Java Struts - II 281

6. Create the tiles.xml file and define all the tiles definitions
The tiles.xml file must be located inside the WEB-INF directory.

tiles.xml <put-attribute name="body"


<?xml version="1.0" encoding="UTF-8" ?> value="/login-success.jsp"/>

<!DOCTYPE tiles-definitions PUBLIC </definition>

"-//Apache Software Foundation//DTD Tiles <definition name="login-error"


Configuration 2.0//EN" template="/layoutmanager.jsp">

"http://tiles.apache.org/dtds/tiles-config_2_0.dtd"> <put-attribute name="title" value="Login


Error"/>
<tiles-definitions>
<put-attribute name="body"
<definition name="login-success" value="/login-error.jsp"/>
template="/layoutmanager.jsp">
</definition> </tiles-definitions>
<put-attribute name="title" value="Welcome Page"/>

7. Create the LayoutManager page


It is the layout manager page. It used getAsString tag of tiles to include the string resource
and insertAttribute tag of tiles to include the page resource.

layoutmanager.jsp <title><tiles:getAsString name="title" /></title>


<%@ taglib uri="http://tiles.apache.org/tags- </head>
tiles" prefix="tiles" %> <body>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML <%@ include file="header.jsp" %>
4.01 Transitional//EN"
<tiles:insertAttribute name="body" />
"http://www.w3.org/TR/html4/loose.dtd">
<%@ include file="footer.jsp" %>
<html>
</body> </html>
<head>

8. Create View components


There are many view components such as header.jsp, footer.jsp, welcome.jsp etc.

header.jsp login-success.jsp
<h2 style="background-color:pink;text- <%@ taglib uri="/struts-tags" prefix="s" %>
align:center;">It is header tile</h2> Welcome, <s:property value="name"/>
<hr/> </textrea></div> <hr/>
footer.jsp <strong>login-error.jsp</strong>
<hr> <div class="codeblock"><textarea
<h2 style="background-color:pink;text- name="code" class="xml" >
align:center;">It is footer tile</h2>

CU IDOL SELF LEARNING MATERIAL (SLM)


282 Advanced Internet Programming

Sorry, username or password error!


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

Output

Password is not admin, so error page will be displayed.

If password is admin, success page will be displayed.

CU IDOL SELF LEARNING MATERIAL (SLM)


Java Struts - II 283

How to define multiple tiles files in struts 2 applicaiton

To define multiple tiles, you need to add following entry in your web.xml file.
<context-param id="struts_tiles">
<param-name>org.apache.tiles.impl.BasicTilesContainer.DEFINITIONS_CONFIG</param-name>
<param-value>/WEB-INF/tiles1.xml,/WEB-INF/tiles2.xml</param-value>
</context-param>

11.8 Practical Assignment


1. Write a struts application to upload multiple files.
2. Create struts application to check whether entered URL is valid or not through struts.

11.9 Summary
Struts2 is a popular and mature web application framework based on the MVC design pattern.
Struts2 is not just a new version of Struts 1, but it is a complete rewrite of the Struts architecture.

The Webwork framework initially started with Struts framework as the basis and its goal was
to offer an enhanced and improved framework built on Struts to make web development easier for
the developers.

After a while, the Webwork framework and the Struts community joined hands to create the
famous Struts2 framework.

11.10 Key Words/Abbreviations


 Eclipse IDE: It is a general purpose open platform that facilitates and encourages the
development of third party plug-ins
 Validation: Validation is a term that comes from the word “valid” which means “can be
justified or defended”
 API: Application program interface
 SMTP: Simple Mail Transfer Protocol
 POP: Post Office Protocol
 IMAP: Internet Message Access Protocol

CU IDOL SELF LEARNING MATERIAL (SLM)


284 Advanced Internet Programming

 MIME: Multipurpose Internet Mail Extensions


 NNTP: Network News Transfer Protocol

11.10 Learning Activity


1. Which Protocols used in JavaMail API?
-----------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------
2. Write steps to send Email using JavaMail API.
-----------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------

11.11 Unit End Questions (MCQ and Descriptive)


A. Descriptive Types Questions
1. Explain how to send mails.
2. List and explain different types of Validation.
3. Write note on Localization.
4. Explain all Type conversion.
5. What is Exception Handling?
6. Explain Annotation.
7. What are Tags and Integrations ?

B. Multiple Choice/Objective Type Questions


1. Struts supports which of these model components?
(a) JavaBeans (b) EJB
(c) CORBA (d) All Mentioned above
2. Which validates the given string with the specified regular expression,it can be used in
password, security key etc.?
(a) Regex Validation (b) Url Validation
(c) Email Validation (d) RequiredString Validator

CU IDOL SELF LEARNING MATERIAL (SLM)


Java Struts - II 285

3. Which type of validation we must implement the Validateable interface (or extend
ActionSupport class) and provide the implementation of validate method?
(a) By Input Validation (b) By Ajax Validation
(c) By Custom Validation (d) None of the above
4. Which is used to make asynchronous request i.e. it doesn’t block the user and it sends
only required field data to the server side not all, So it makes the performance fast?
(a) AJAX Support (b) Integration Support
(c) Various Tag Support (d) Theme and Template Support
5. Struts combines which of these in to a unified Framework?
(a) Java Servlets
(b) Java Server pages
(c) Custom tags and Message Resources
(d) All mentioned above.

Answers
1. (d), 2. (a), 3. (c), 4. (a), 5. (d)

11.12 References
1. https://netbeans.org/kb/docs/web/quickstart-webapps-struts.html
2. http://mrbool.com/introduction-to-struts-framework/27062
3. Don Brown, Chad Michael Davis, Scott Stanlick, “Struts 2 in Action” 1st Edition.

CU IDOL SELF LEARNING MATERIAL (SLM)


PRACTICAL BASICS
UNIT 1
vcvc
Practical - 1
Implementation of CRUD Operation on JDBC Application with Oracle-MySQL-
PostgresSQL
Source code:
Insert operation

package crudapplication;
import java.sql.*;
public class CrudApplication {
public static void main(String[] args) {
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/test", "root", "");
Statement stmt= conn.createStatement();
stmt.execute("insert into user values(1,'Meet','Andheri','meet@mail.com')");
stmt.execute("insert into user values(2,'Sohrab','Andheri','sohrab@mail.com')");
stmt.execute("insert into user values(3,'Verlyn','Andheri','verlyn@mail.com')");
System.out.println("record inserted");
stmt.close();
conn.close();
}
catch (Exception e) {
System.out.println("Exception occured: "+e);
} } }

CU IDOL SELF LEARNING MATERIAL (SLM)


Basics 287

Output

Update and Delete Operation


package crudapplication;
import java.sql.*;

CU IDOL SELF LEARNING MATERIAL (SLM)


288 Advanced Internet Programming

public class CrudApplication {


public static void main(String[] args) {
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/test", "root", "");
Statement stmt= conn.createStatement();
stmt.execute("delete from user where id='3'");
System.out.println("record deleted");
stmt.executeUpdate("update user set address='Kandivali' where id='2'");
System.out.println("record updated");
stmt.close();
conn.close();
}
catch (Exception e) {
System.out.println("Exception occured: "+e);
}} }

CU IDOL SELF LEARNING MATERIAL (SLM)


Basics 289

Practical - 2
Implementation of Java Swings with JDBC Applications with Oracle-MySQL-
PostgresSQL
Source code:
package App;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class UICrud extends javax.swing.JFrame {
public UICrud() {
initComponents();
}
@SuppressWarnings("unchecked")
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jTextField1 = new javax.swing.JTextField();
jLabel2 = new javax.swing.JLabel();
jTextField2 = new javax.swing.JTextField();
jLabel3 = new javax.swing.JLabel();
jTextField3 = new javax.swing.JTextField();
jLabel4 = new javax.swing.JLabel();
jTextField4 = new javax.swing.JTextField();
jButton1 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setText("id");
jLabel2.setText("name");
jLabel3.setText("address");
jLabel4.setText("email");
jButton1.setText("Insert");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt); }
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());

CU IDOL SELF LEARNING MATERIAL (SLM)


290 Advanced Internet Programming

getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(28, 28, 28)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
.addComponent(jLabel2)
.addComponent(jLabel3)
.addComponent(jLabel4))
.addGap(36, 36, 36)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jTextField1, javax.swing.GroupLayout.DEFAULT_SIZE, 115, Short.MAX_VALUE)
.addComponent(jTextField2)
.addComponent(jTextField3)
.addComponent(jTextField4)))
.addGroup(layout.createSequentialGroup()
.addGap(83, 83, 83)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 87,
javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(31, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(23, 23, 23)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)

CU IDOL SELF LEARNING MATERIAL (SLM)


Basics 291

.addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel4)
.addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(53, 53, 53)
.addComponent(jButton1)
.addContainerGap(57, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/test", "root", "");
Statement stmt= conn.createStatement();
String id= jTextField1.getText();
String name= jTextField2.getText();
String address= jTextField3.getText();
String email= jTextField4.getText();
String query ="insert into user values("+id+",'"+name+"','"+address+"','"+email+"')";
stmt.execute(query);
System.out.println("record inserted");
stmt.close();
conn.close();
}
catch (Exception e) {
System.out.println("Exception occured: "+e);
} }

CU IDOL SELF LEARNING MATERIAL (SLM)


292 Advanced Internet Programming

public static void main(String args[]) {


try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels())
{
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
} }
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(UICrud.class.getName()).log(java.util.logging.Level.SEVERE, null,
ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(UICrud.class.getName()).log(java.util.logging.Level.SEVERE, null,
ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(UICrud.class.getName()).log(java.util.logging.Level.SEVERE, null,
ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(UICrud.class.getName()).log(java.util.logging.Level.SEVERE, null,
ex);
}
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new UICrud().setVisible(true);
} }); }
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JTextField jTextField1;
private javax.swing.JTextField jTextField2;
private javax.swing.JTextField jTextField3;
private javax.swing.JTextField jTextField4;
// End of variables declaration
}

CU IDOL SELF LEARNING MATERIAL (SLM)


Basics 293

Output

Practical - 3
Create a table of the cookies associated with the suitable home page. If there are no
active cookies display as stating “No Cookies” otherwise display cookie name and
value in a tabular format.
Source code:
Index.html

<h3>Cookie Example</h3>
<body>
<form method="get" action="http://localhost:8080/WebApplication/CookieSample.jsp">
Cookie Header <input type="text" name="particluar"><br>
Cookie Value <input type="text" name="val"><br>
<input type="submit" value="Add Cookie" name="add">
<input type="submit" value="List Cookies" name="list">
</form>
</body>

CU IDOL SELF LEARNING MATERIAL (SLM)


294 Advanced Internet Programming

CookieSample.jsp

<body>
<%
String str1 = request.getParameter("particluar"); // item name
String str2 = request.getParameter("val"); // item quantity
String str3 = request.getParameter("add"); // submit button by name add
String str4 = request.getParameter("list"); // submit button by name list
if(str3 != null)
{
Cookie c1 = new Cookie(str1, str2);
response.addCookie(c1);
response.sendRedirect("index.html");
}
else if(str4 != null)
{
Cookie clientCookies[] = request.getCookies();
if (clientCookies != null)
{
out.print("<table border=1 align=center> "
+ "<tr> "
+ "<th>Cookie Name</th>"
+"<th> Cookie Value</th>"
+"</tr>");
for( int i = 0; i < clientCookies.length; i++)
{
out.print("<tr>");
out.print("<td>" + clientCookies[i].getName() + " </td><td>" + clientCookies[i].getValue() + "</td></tr>");
} }
else {
out.print("No Cookies");
} }
%>
</body>

CU IDOL SELF LEARNING MATERIAL (SLM)


Basics 295

Output:

Practical - 4
Aim
Create Login Form and Perform State Management using Cookies, HttpSession and
URL Rewriting.
Source Code
1. State management using cookies:

CookieLog.jsp

<%
Cookie[] cookies = request.getCookies();
String uname=null;
if (cookies != null)
{

CU IDOL SELF LEARNING MATERIAL (SLM)


296 Advanced Internet Programming

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


{
Cookie c = cookies[i];
if (c.getName().equals("username"))
{
uname = c.getValue();
} }
if(uname!=null)
{
out.println("Welcome " + uname);
}
else
{
%>
<h3>Cookie Login</h3>
<body>
<form method="get" action="CookieProcess.jsp">
UserName <input type="text" name="uname"><br>
Password <input type="password" name="pass"><br>
<input type="submit" value="Login" name="login">
</form>
</body>
<%
}
%>
<%
}
else
{
%>
<h3>Cookie Login</h3>
<body>
<form method="get" action="CookieProcess.jsp">
UserName <input type="text" name="uname"><br>
Password <input type="password" name="pass"><br>

CU IDOL SELF LEARNING MATERIAL (SLM)


Basics 297

<input type="submit" value="Login" name="login">


</form>
</body>
<%
} %>

CookieProcess.jsp
<%
String str1 = request.getParameter("uname"); // item name
String str2 = request.getParameter("pass"); // item quantity
String str3 = request.getParameter("login"); // submit button by name add
if(str3 != null)
{
if(str1.equals("admin") && str2.equals("admin"))
{
Cookie c1 = new Cookie("username", str1);
response.addCookie(c1);
response.sendRedirect("http://localhost:8080/Cookie_Login/CookieLog.jsp");
}
else
{
out.print("Authentication Failed"); }
} %>

Output:

CU IDOL SELF LEARNING MATERIAL (SLM)


298 Advanced Internet Programming

Index.html
<form method="post" action="Validate">
User: <input type="text" name="user" /><br/>
Password: <input type="text" name="pass" ><br/>
<input type="submit" value="submit">
</form>

Validate.java
import java.io.IOException;
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 javax.servlet.http.*;
@WebServlet(urlPatterns = {"/Validate"})
public class Validate extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
String name = request.getParameter("user");
String pass = request.getParameter("pass");
if(pass.equals("admmin"))
{
//creating a session
HttpSession session = request.getSession();
session.setAttribute("user", name);
response.sendRedirect("Welcome");
} }
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

CU IDOL SELF LEARNING MATERIAL (SLM)


Basics 299

processRequest(request, response);
}
public String getServletInfo() {
return "Short description";
} }

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;
import javax.servlet.http.*;
@WebServlet(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();
HttpSession session = request.getSession();
String user = (String)session.getAttribute("user");
out.println("Hello "+user);
}
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);
}
public String getServletInfo() {
return "Short description";
} }

CU IDOL SELF LEARNING MATERIAL (SLM)


300 Advanced Internet Programming

Practical - 5
Study and Implement MVC using Spring Framework
Spring MVC is based on Model-View-Controller architecture. Spring MVC
architecture at a high level is shown below:

Fig: P1.1: Spring MVC Architecture


DispatcherServlet is the front controller class to take all requests and start processing them. It
can be configured in web.xml file. It passes request to appropriate controller class and sends the
response back when view pages have rendered the response page.

HomeController.java will be the single controller class in our spring MVC example
application.

Spring MVC App Eclipse Project Setup


Since it is a web application and we want to use maven for dependencies management, first
of all we have to create a dynamic web application and then convert it to a maven project. Below
images show how to do this and get our project skeleton structure ready.

Right click on the project explorer window and click on “New -> Dynamic Web Project” as
shown in below image.

CU IDOL SELF LEARNING MATERIAL (SLM)


Basics 301

Provide name as “spring-mvc-app” in the next popup page, rest of the things should not
required to be changed.

CU IDOL SELF LEARNING MATERIAL (SLM)


302 Advanced Internet Programming

On next page, provide the source folder as “src/main/java”. You might have to remove “src”
folder from the list before adding this.

Next is the web module page, provide the context root of application as “spring-mvc-app”
and make sure to check “Generate web.xml deployment descriptor” option.

CU IDOL SELF LEARNING MATERIAL (SLM)


Basics 303

Click on Finish and you will have a new Dynamic Web Project in your eclipse project
explorer.

Converting Dynamic Web Project to Maven Project


We want to use maven for easily manage our spring mvc dependencies. So let’s convert our
web project to maven.

Right click on the project and select “Configure -> Convert to Maven Project”.

Next provide the pom.xml configurations as shown below.

CU IDOL SELF LEARNING MATERIAL (SLM)


304 Advanced Internet Programming

Spring MVC Dependencies to pom.xml


We need to add spring-web and spring-webmvc dependencies in pom.xml, also add servlet-
api, jsp-api and jstl dependencies. Our final pom.xml file will be like below.

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-


instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>spring-mvc-app</groupId>
<artifactId>spring-mvc-app</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>Spring MVC App</name>
<description>Spring MVC Simple App</description>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
<configuration>
<source>1.8</source>

CU IDOL SELF LEARNING MATERIAL (SLM)


Basics 305

<target>1.8</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.3</version>
<configuration>
<warSourceDirectory>WebContent</warSourceDirectory>
</configuration>
</plugin>
</plugins>
</build>
</project>

Notice the finalName configuration in build, so that our WAR file name doesn’t have version
details.

When the project is build by Eclipse, you will notice all the jars showing up in maven
dependencies section.

Spring MVC DispatcherServlet as Front Controller


We have to add Spring MVC framework to our web application, for that we need to
configure DispatcherServlet in web.xml as shown below.

<?xml version="1.0" encoding="UTF-8"?>


<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>spring-mvc-app</display-name>
<!-- Add Spring MVC DispatcherServlet as front controller -->
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-servlet.xml</param-value>

CU IDOL SELF LEARNING MATERIAL (SLM)


306 Advanced Internet Programming

</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>

contextConfigLocation init-param is used to provide the location of spring bean


configuration file.

Spring MVC Example Bean Configuration File


Next step is to create spring bean configuration file spring-servlet.xml as shown below.

Right click WEB-INF ( New ( File and type the name and click fFnish.

CU IDOL SELF LEARNING MATERIAL (SLM)


Basics 307

<?xml version="1.0" encoding="UTF-8"?>


<beans:beans xmlns="https://www.springframework.org/schema/mvc"
xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="https://www.springframework.org/schema/beans"
xmlns:context="https://www.springframework.org/schema/context"
xsi:schemaLocation="https://www.springframework.org/schema/mvc
https://www.springframework.org/schema/mvc/spring-mvc.xsd
https://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-
beans.xsd
https://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<!-- DispatcherServlet Context: defines this servlet's request-processing
infrastructure -->
<!-- Enables the Spring MVC @Controller programming model -->
<annotation-driven />
<context:component-scan base-package="spring" />
<!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views
directory -->
<beans:bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
</beans:beans>

There are three important configurations.

1. annotation-driven tells DispatcherServlet to look for Controller classes


using @Controller annotation.
2. context:component-scan tells DispatcherServlet where to look for controller classes.
3. InternalResourceViewResolver bean configuration to specify location of view pages and
suffix used. Controller class methods return name of the view page and then suffix is
added to figure out the view page to use for rendering the response.

Spring MVC Controller Class


We have a single controller class to respond for two URIs – “/” for home page and “/user”
for user page.

CU IDOL SELF LEARNING MATERIAL (SLM)


308 Advanced Internet Programming

package spring.controller;
import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import spring.model.User;
@Controller
public class HomeController {
/**
* Simply selects the home view to render by returning its name.
*/
@RequestMapping(value = "/", method = RequestMethod.GET)
public String home(Locale locale, Model model) {
System.out.println("Home Page Requested, locale = " + locale);
Date date = new Date();
DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG,
locale);
String formattedDate = dateFormat.format(date);
model.addAttribute("serverTime", formattedDate);
return "home";
}
@RequestMapping(value = "/user", method = RequestMethod.POST)
public String user(@Validated User user, Model model) {
System.out.println("User Page Requested");
model.addAttribute("userName", user.getUserName());
return "user";
} }

Spring MVC Model Class


We have a simple model class with a single variable and it’s getter-setter methods. It’s a
simple POJO class.

CU IDOL SELF LEARNING MATERIAL (SLM)


Basics 309

package spring.model;
public class User {
private String userName;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
} }

Spring MVC View Pages


We have two view pages as defined below.

home.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="https://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ page session="false"%>
<html>
<head>
<title>Home</title>
</head>
<body>
<h1>Hello world!</h1>
<P>The time on the server is ${serverTime}.</p>
<form action="user" method="post">
<input type="text" name="userName"><br> <input type="submit" value="Login">
</form> </body> </html>
user.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"https://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

CU IDOL SELF LEARNING MATERIAL (SLM)


310 Advanced Internet Programming

<title>User Home Page</title>


</head>
<body>
<h3>Hi ${userName}</h3>
</body> </html>

The Spring MVC takes care of mapping form variables to model class variables, that is why
we have same variable name in both places.

Now our spring mvc example project is ready to de deployed and test.

Spring MVC Eclipse Project Deployment


We can use Eclipse export as WAR file option to deploy it directly to any running tomcat
server webapps directory. However you can also use command line to build the project and then
copy it into your favourite servlet container deployment directory.

CU IDOL SELF LEARNING MATERIAL (SLM)


Basics 311

Spring MVC Example Test


Once the spring mvc project is deployed, we can access the home page
at https://localhost:8080/spring-mvc-example/. Change the tomcat port and context-root
accordingly.

HPH

CU IDOL SELF LEARNING MATERIAL (SLM)


312 Advanced Internet Programming

HPH
Practical - 6
Create Database of Student Subject-Wise Data and Retrieve All Data using JSP and
Generate xml Structure Along with DTD and XML Schema Definition
Create DTD document, which describes final XML metadata file, Connect to Database
Create JSPage, which generates XML file from your database

DTD:
<!ELEMENT Student(SName, S1Marks, S1Marks, S1Marks,S1Marks)>
<!ELEMENT SName(#PCDATA)>
<!ELEMENT S1MARKS(#PCDATA)>
<!ELEMENT S2MARKS(#PCDATA)>
<!ELEMENT S3MARKS(#PCDATA)>
<!ELEMENT S4MARKS(#PCDATA)>
<!ELEMENT S5MARKS(#PCDATA)>
<!-- Main Oracle Connection html page -->
<html><head>
<title>JSP + XML sample - entry page</title>
</head>
<body>
<p><strong>Oracle Connection</strong></p>
<!-- Include JSPage, which generates XML file from Oracle database -->
<form action="OraDB2XmlFile.jsp" method=get>
<table>
?????? <!-- Insert Oracle Datbase Name -->
?????? <tr><td>Database:</td><td><input type=text name=database></td></tr>
?????? <!-- Insert Server Name where your database is stored -->
?????? <tr><td>Server Name:</td><td><input type=text name=servernm></td></tr>
?????? <!-- Insert your User Name to connect your database -->

CU IDOL SELF LEARNING MATERIAL (SLM)


Basics 313

?????? <tr><td>User Name:</td><td><input type=text name=username></td></tr>


?????? <!-- Insert your account password -->
?????? <tr><td>Password:</td><td><input type=password name=password></td></tr>
</table>
<br>
<!-- Submit button -->
<input type=submit value="Submit">
</form>
</body>
</html>

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

<%
// Identify a carriage return character for each output line
int iLf = 10;
char cLf = (char)iLf;

// Create a new empty binary file, which will content XML output
File outputFile = new File(<YourFileName>);
outputFile.createNewFile();
FileWriter outfile = new FileWriter(outputFile);
// the header for XML file
outfile.write("<?xml version='1.0' encoding='ISO-8859-1'?>"+cLf);

try {
?????? // The HTTP request's parameters to get a database connection
?????? String servernm = request.getParameter("servernm");
?????? String database = request.getParameter("database");
?????? String username = request.getParameter("username");
?????? String password = request.getParameter("password");

?????? // We access the database directly from the JSP with the Oracle JDBC driver

CU IDOL SELF LEARNING MATERIAL (SLM)


314 Advanced Internet Programming

?????? DriverManager.registerDriver (new oracle.jdbc.driver.OracleDriver());


?????? // Define connection string and make a connection to database
?????? Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@"+servernm+":1521:"+
???????????????????????????????????????????????????? database, username, password);
?????? Statement stat = conn.createStatement();
?????? // Create a recordset
?????? ResultSet rset = stat.executeQuery("Select * From Students”);
?
?????? // Expecting at least one record
?????? if( !rset.next() ) {
????????????? throw new IllegalArgumentException("No data found for the Cars table");
?????? }
?????? outfile.write("<Table>"+cLf);

?????? // Parse our recordset


?????? while(rset.next()) {
????????????? outfile.write("<Student>"+cLf);
????????????? outfile.write("<S1Marks>" + rset.getString("S1Marks") +"</S1Marks>"+cLf);
????????????? outfile.write("<S2Marks>" + rset.getString("S2Marks") +"</S2Marks >"+cLf);
????????????? outfile.write("<S3Marks>" + rset.getString("S3Marks") +"</S3Marks>"+cLf);
????????????? outfile.write("<S4Marks>" + rset.getString("S4Marks") +"</S4Marks>"+cLf);
????????????? outfile.write("<S5Marks>" + rset.getString("S5Marks") +"</S5Marks>"+cLf);
????????????? outfile.write("</Student>"+cLf);
?????? }
?????? outfile.write("</Table>"+cLf);
?????? // Everything must be closed
?????? rset.close();
?????? stat.close();
?????? conn.close();
?????? outfile.close();
}
catch( Exception er ) {
%>
?????? <exception><%= er.getMessage()%></exception>
<%

CU IDOL SELF LEARNING MATERIAL (SLM)


Basics 315

?????? outfile.close();
}
%>

Practical - 7
Create Servlet file which contains following functions:
 Connect
 Create Database
 CreateTable
 Insert Records into respectivetable Update records of particular table of database
 Delete Records from table
 Delete table and also database.
Design database for student administration. Develop servlet(s) to perform CRUD operations.

HomePage.html
<!DOCTYPE html>
<html>
<head>
<title>Home page</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body> <center>
<h1>Student Administration</h1>
<form action="createtblStud">
<input type="submit" value="Create tblStudent">
</form>
<br>

CU IDOL SELF LEARNING MATERIAL (SLM)


316 Advanced Internet Programming

<form action="insertData.html">
<input type="submit" value="Insert">
</form>
<br>
<form action="updateData.html">
<input type="submit" value="Update">
</form> <br>
<form action="deleteData.html">
<input type="submit" value="Delete">
</form> <br>
<form action="selectStud">
<input type="submit" value="Show All Records">
</form> </center>
</body> </html>

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-
app_3_1.xsd" version="3.1">
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>HomePage.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>createtblStud</servlet-name>
<servlet-class>createtblStud</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>createtblStud</servlet-name>

CU IDOL SELF LEARNING MATERIAL (SLM)


Basics 317

<url-pattern>/createtblStud</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>selectStud</servlet-name>
<servlet-class>selectStud</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>selectStud</servlet-name>
<url-pattern>/selectStud</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>InsertStudent</servlet-name>
<servlet-class>InsertStudent</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>InsertStudent</servlet-name>
<url-pattern>/InsertStudent</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>UpdateStudent</servlet-name>
<servlet-class>UpdateStudent</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>UpdateStudent</servlet-name>
<url-pattern>/UpdateStudent</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>DeleteStudent</servlet-name>
<servlet-class>DeleteStudent</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>DeleteStudent</servlet-name>
<url-pattern>/DeleteStudent</url-pattern>
</servlet-mapping>
<servlet>

CU IDOL SELF LEARNING MATERIAL (SLM)


318 Advanced Internet Programming

<servlet-name>UpdateStudentDetails</servlet-name>
<servlet-class>UpdateStudentDetails</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>UpdateStudentDetails</servlet-name>
<url-pattern>/UpdateStudentDetails</url-pattern>
</servlet-mapping>
</web-app>

createtblStud.java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.sql.*;
public class createtblStud extends HttpServlet{
public void service(HttpServletRequest request,HttpServletResponse response) throws IOException
{
Connection con;
Statement st;
PrintWriter out=response.getWriter();
response.setContentType("text/html");
out.println("<center>");
try
{
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:9300/dbStudent","root","root");
st=con.createStatement();
String query="create table tblStudent(RollNo int,StudName varchar(20),MarksSSC float,MarksHSC
float);";
System.out.println(query);
int c=st.executeUpdate(query);
if(c==0)
out.println("<h1>Table created<br>");
else
out.println("<h1>Error in creation/already exists<br>");

CU IDOL SELF LEARNING MATERIAL (SLM)


Basics 319

out.println("<a href='HomePage.html'>Click to go to Home Page</a><br>");


}
catch(Exception e)
{
System.out.println(e);
out.println("<h1>Error in creation/already exists<br>");
out.println("<a href='HomePage.html'>Click to go to Home Page</a><br>");
} } }

insertData.html
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert</title>
</head>
<body>
<center>
<h1>Student Data Insertion</h1>
<form action="InsertStudent">
<table>
<tr>
<td>Roll no</td>
<td><input type="text" name="txtRollNo"></td>
</tr> <tr>
<td>Student Name</td>
<td><input type="text" name="txtStudName"></td>
</tr> <tr>
<td>Marks in SSC</td>
<td><input type="text" name="txtMarksSSC"></td>
</tr> <tr>
<td>Marks in HSC</td>
<td><input type="text" name="txtMarksHSC"></td>
</tr> <tr>
<td><input type="submit" name="Insert"></td>

CU IDOL SELF LEARNING MATERIAL (SLM)


320 Advanced Internet Programming

</tr>
</table> </form> </center> </body> </html>

InsertStudent.java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.sql.*;
public class InsertStudent extends HttpServlet{
public void service(HttpServletRequest request,HttpServletResponse response) throws IOException
{
Connection con;
Statement st;
PrintWriter out=response.getWriter();
response.setContentType("text/html");
out.println("<center>");
try
{
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:9300/dbStudent","root","root");
st=con.createStatement();
int no=Integer.parseInt(request.getParameter("txtRollNo"));
String name=request.getParameter("txtStudName");
float marksSSC=Float.parseFloat(request.getParameter("txtMarksSSC"));
float marksHSC=Float.parseFloat(request.getParameter("txtMarksHSC"));
String query="insert into tblStudent values("+no+",'"+name+"',"+marksSSC+","+marksHSC+")";
System.out.println(query);
int c=st.executeUpdate(query);
if(c!=0)
out.println("<h1>Record inserted<br>");
else
out.println("<h1>Error in insertion<br>");
out.println("<a href='HomePage.html'>Click to go to Home Page</a><br>");
out.println("<a href='insertData.html'>Click to add one more record</a></h1>");
}

CU IDOL SELF LEARNING MATERIAL (SLM)


Basics 321

catch(Exception e)
{
System.out.println(e);
out.println("<h1>Error in insertion<br>");
out.println("<a href='HomePage.html'>Click to go to Home Page</a><br>");
out.println("<a href='insertData.html'>Click to add one more record</a></h1>");
} } }

deleteData.html
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Delete</title>
</head>
<body>
<center>
<h1>Student Data Deletion</h1>
<form action="DeleteStudent">
<table>
<tr>
<td>Roll No</td>
<td><input type="text" name="txtRollNo"></td>
</tr> <tr>
<td><input type="submit" name="Delete"></td>
</tr>
</table> </form> </center> </body> </html>

DeleteStudent.java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.sql.*;
public class DeleteStudent extends HttpServlet{
public void service(HttpServletRequest request,HttpServletResponse response) throws IOException

CU IDOL SELF LEARNING MATERIAL (SLM)


322 Advanced Internet Programming

{
Connection con;
Statement st;
PrintWriter out=response.getWriter();
response.setContentType("text/html");
out.println("<center>");
try
{
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:9300/dbStudent","root","root");
st=con.createStatement();
int no=Integer.parseInt(request.getParameter("txtRollNo"));
String query="select * from tblStudent where RollNo="+no+";";
ResultSet rs=st.executeQuery(query);
if(rs.next())
{
query="delete from tblStudent where RollNo="+no+";";
int c=st.executeUpdate(query);
if(c!=0)
out.println("<h1>Record deleted<br>");
}
else
out.println("<h1>No such record<br>");
out.println("<a href='HomePage.html'>Click to go to Home Page</a><br><br>");
}
catch(Exception e)
{
System.out.println(e);
out.println("<h1>Error in deletion<br>");
out.println("<a href='HomePage.html'>Click to go to Home Page</a><br><br>");
} } }

updateData.html
<!DOCTYPE html>
<html>

CU IDOL SELF LEARNING MATERIAL (SLM)


Basics 323

<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Updation</title>
</head>
<body>
<center>
<h1>Student Data Updation</h1>
<form action="UpdateStudent">
<table>
<tr>
<td>Roll No</td>
<td><input type="text" name="txtRollNo"></td>
</tr>
<tr>
<td><input type="submit" name="Update"></td>
</tr>
</table> </form> </center> </body> </html>

UpdateStudent.java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.sql.*;
public class UpdateStudent extends HttpServlet{
public void service(HttpServletRequest request,HttpServletResponse response) throws IOException
{
Connection con;
Statement st;
PrintWriter out=response.getWriter();
response.setContentType("text/html");
out.println("<center>");
try
{
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:9300/dbStudent","root","root");

CU IDOL SELF LEARNING MATERIAL (SLM)


324 Advanced Internet Programming

st=con.createStatement();
int no=Integer.parseInt(request.getParameter("txtRollNo"));
String query="select * from tblStudent where RollNo="+no+";";
ResultSet rs=st.executeQuery(query);
if(rs.next())
{
no=Integer.parseInt(rs.getString(1));
String name=rs.getString(2);
float marksSSC=rs.getFloat(3);
float marksHSC=rs.getFloat(4);
out.println("<form action='UpdateStudentDetails'><table><tr><td>Roll No</td><td><input type='text'
name='txtRollNo' value="+no+"></td></tr>");
out.println("<tr><td>Student Name</td><td><input type='text' name='txtStudName'
value="+name+"></td></tr>");
out.println("<tr><td>Marks in SSC</td><td><input type='text' name='marksSSC'
value="+marksSSC+"></td></tr>");
out.println("<tr><td>Marks in HSC</td><td><input type='text' name='marksHSC'
value="+marksHSC+"></td></tr>");
out.println("<tr><td><input type='submit' name='Update'></td></tr></table></form>");
}
else
out.println("<h1>No such record<br>");
out.println("<a href='HomePage.html'>Click to go to Home Page</a><br><br>");
}
catch(Exception e)
{
System.out.println(e);
out.println("<h1>Error in updation<br>");
out.println("<a href='HomePage.html'>Click to go to Home Page</a><br><br>");
} } }

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

CU IDOL SELF LEARNING MATERIAL (SLM)


Basics 325

public class UpdateStudentDetails extends HttpServlet{


public void service(HttpServletRequest request,HttpServletResponse response) throws IOException
{
Connection con;
Statement st;
PrintWriter out=response.getWriter();
response.setContentType("text/html");
out.println("<center>");
try
{
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:9300/dbStudent","root","root");
st=con.createStatement();
int no=Integer.parseInt(request.getParameter("txtRollNo"));
String name=request.getParameter("txtStudName");
float marksSSC=Float.parseFloat(request.getParameter("marksSSC"));
float marksHSC=Float.parseFloat(request.getParameter("marksHSC"));
String query="update tblStudent set
StudName='"+name+"',MarksSSC="+marksSSC+",MarksHSC='"+marksHSC+"' where RollNo="+no+";";
System.out.println(query);
int c=st.executeUpdate(query);
if(c!=0)
out.println("<h1>Record updated<br>");
else
out.println("<h1>Error in updation<br>");
out.println("<a href='HomePage.html'>Click to go to Home Page</a><br>");
}
catch(Exception e)
{
System.out.println(e);
out.println("<h1>Error in updation<br>");
out.println("<a href='HomePage.html'>Click to go to Home Page</a><br>");
} } }

CU IDOL SELF LEARNING MATERIAL (SLM)


326 Advanced Internet Programming

selectStud.java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.sql.*;
public class selectStud extends HttpServlet{
public void service(HttpServletRequest request,HttpServletResponse response) throws IOException
{
Connection con;
Statement st;
PrintWriter out=response.getWriter();
response.setContentType("text/html");
out.println("<center>");
try
{
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:9300/dbStudent","root","root");
st=con.createStatement();
out.print("<h1>Records in tblStudent</h1>");
String query="select * from tblStudent";
ResultSet rs=st.executeQuery(query);
out.println("<table border='1'><tr><td>Roll No</td><td>Student Name</td><td>Marks in
SSC</td><td>Marks in HSC</td></tr>");
while(rs.next())
{
out.print("<tr><td>"+rs.getString(1) +"</td><td>"+ rs.getString(2) +"</td><td>"+ rs.getString(3)
+"</td><td>"+ rs.getString(4) + "</td></tr>");
}
out.println("<a href='HomePage.html'>Click to go to Home Page</a><br>");
}
catch(Exception e)
{
System.out.println(e);
out.println("<h1>Error<br>");
out.println("<a href='HomePage.html'>Click to go to Home Page</a><br>");
} }}

CU IDOL SELF LEARNING MATERIAL (SLM)


Basics 327

Output:
Home page

Table Creation

Record Data Insertion

CU IDOL SELF LEARNING MATERIAL (SLM)


328 Advanced Internet Programming

Update Record Data

Before Updation

After Updation

Record Deletion when Not in Database

CU IDOL SELF LEARNING MATERIAL (SLM)


Basics 329

Show All Records

Practical - 8
Create a Servlet that uses session tracking to keep per-client access counts. Also
show other generic- info about the session.
index.html

<html>
<head><title>Cookie Demo</title></head>
<body>
<form action="Page1" >
Enter Your Name <input type="text" name="txtName"><br>
<input type="submit" value="~~~ Click to Enter ~~~">
</form>

CU IDOL SELF LEARNING MATERIAL (SLM)


330 Advanced Internet Programming

</body>
</html>

Page1.java

package mypack;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Cookie;
public class Page1 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("<html><head><title>Page1</title></head>");
out.println("<body bgcolor=pink >");
String uname = request.getParameter("txtName");
out.println("<h1>~~~ Welcome "+uname+"</h1>");
Cookie ck1 = new Cookie("username", uname);
Cookie ck2 = new Cookie("visit","1");
response.addCookie(ck1); response.addCookie(ck2);
out.println("<h1><a href=Page2 >Click to visit Page 2 </a></h1>");
out.println("</body>");
out.println("</html>");
}
}

Page2.java

package mypack;
import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.http.*;

CU IDOL SELF LEARNING MATERIAL (SLM)


Basics 331

public class Page2 extends HttpServlet {


public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("<html><head><title>Page2</title></head>");
out.println("<body bgcolor=yellow >");
Cookie [] ck = request.getCookies();
for(int i=0;i<ck.length;i++){
if(ck[i].getName().equals("visit")){
int count = Integer.parseInt(ck[i].getValue())+1;
out.println("<h1>Visit No : "+count+"</h1>");
ck[i] = new Cookie("visit",count+"");
response.addCookie(ck[i]);
}
else {
out.println(ck[i].getName()+ " = "+ck[i].getValue()); }
out.println("<h1><a href=Page3 >Click to visit Page 3 </a></h1>");
out.println("<h1><a href=Page4 >Click to visit Page 4 </a></h1>");
out.println("<h1><a href=Page5 >Click to visit Page 5 </a></h1>");
out.println("</body>");
out.println("</html>");
}}

Repeat the code from Page2.java for Page3.java, Page4.java and Page5.java with
relevant changes.

CU IDOL SELF LEARNING MATERIAL (SLM)


332 Advanced Internet Programming

Practical - 9
Make a Program which Creates a Cookie on the Server Side using Servlets and
when Server Returns a Response to the User also Send Cookies to Clients for Later
Retrieve Its Data from that Client
// Java program to illustrate methods
// of Cookie class
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class cookieTest
*/
@WebServlet("/cookieTest")
public class cookieTest extends HttpServlet
{
private static final long serialVersionUID = 1L;

CU IDOL SELF LEARNING MATERIAL (SLM)


Basics 333

/**
* @see HttpServlet#HttpServlet()
*/
public cookieTest() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
// Create a new cookie with the name test cookie
// and value 123
Cookie cookie = new Cookie("test_cookie", "123");

// setComment() method
cookie.setComment("Just for testing");

// setDomain() method
// cookie.setDomain("domain");
// setMaxAge() method
cookie.setMaxAge(3600);
// setPath() method
cookie.setPath("/articles");
// setSecure() method
cookie.setSecure(false);
// setValue() method
cookie.setValue("321");
// setVersion() method
cookie.setVersion(0);
response.addCookie(cookie);

CU IDOL SELF LEARNING MATERIAL (SLM)


334 Advanced Internet Programming

PrintWriter pw = response.getWriter();
pw.print("<html><head></head><body>");
Cookie ck[] = request.getCookies();
if (ck == null) {
pw.print("<p>This is first time the page is requested.</p>");
pw.print("<p>And therefore no cookies found</p></body></html>");
} else {
pw.print("<p>Welcome Again...Cookies found</p>");
for (int i = 0; i < ck.length; i++) {
// getName() method
pw.print("<p>Name :" + ck[i].getName() + "</p>");
// getValue() method
pw.print("<p>Value :" + ck[i].getValue() + "</p>");
// getDomain() method
pw.print("<p>Domain :" + ck[i].getDomain() + "</p>");
// getPath() method
pw.print("<p>Name :" + ck[i].getPath() + "</p>");
// getMaxAge() method
pw.print("<p>Max Age :" + ck[i].getMaxAge() + "</p>");
// getComment() method
pw.print("<p>Comment :" + ck[i].getComment() + "</p>");
// getSecure() method
pw.print("<p>Name :" + ck[i].getSecure() + "</p>");
// getVersion() method
pw.print("<p>Version :" + ck[i].getVersion() + "</p>");
}
pw.print("<body></html>");
}
pw.close();
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)

CU IDOL SELF LEARNING MATERIAL (SLM)


Basics 335

throws ServletException, IOException


{
doGet(request, response);
}
}

Output: The following output are from a web browser0

For the first request:

This is first time the page is requested.

And therefore no cookies found.

For the second request:


Welcome Again...Cookies found
Name :test_cookie
Value :321
Domain :null
Name :null
Max Age :-1
Comment :null
Name :false

CU IDOL SELF LEARNING MATERIAL (SLM)


PRACTICAL JAVASCRIPT/CSS
UNIT 2
vcvc

Practical - 1
1. Create a registration page using HTML and CSS with right corner of the page having
current date and time.
2. Design specification for the webpage as follows:
(a) The text box background color will be displayed and shadowed when th cursor
inserts into the text field.
(b) The text area background color will be displayed by and shadowed when the cursor
places into textarea.
(c) The submit button background color will be displayed and shadowed when the
cursor moves over the submit button.
(d) For the same page and write validation function for registration page and modify
the onSubmit event handler in the form code to validate the following form fields:
(i) FirstName

– Must be entered

– Must be Character

(ii) Password

– Password length should be between 6 to 20 characters.

(iii) Gender(Use radio button)

– Must be selected

(iv) Mobile Number

– Must be in format(XXXXXXXXXXXX)

CU IDOL SELF LEARNING MATERIAL (SLM)


JavaScript/CSS 337

(v) Email

– Email address must contain at least an @ sign and a dot(.)

<!DOCTYPE html>
<!--

To change this license header, choose License Headers in Project Properties.

To change this template file, choose Tools | Templates

and open the template in the editor.

<html>
<head>
<title>Registration</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<style>
.input-group {
float: right;
}
.button {
background-color: #4CAF50; /* Green */
border: none;
color: white;
padding: 16px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin: 4px 2px;
transition-duration: 0.4s;
cursor: pointer;
}
button1 {
background-color: white;

CU IDOL SELF LEARNING MATERIAL (SLM)


338 Advanced Internet Programming

color: black;
border: 2px solid #4CAF50; }
.button1:hover {
background-color: #4CAF50;
color: white; }
</style> <body>
<form onsubmit="myFunction();">
<div class="input-group">
<span id="datetime"></span>
</div>
Name:<input type='text' name='name' id="name" style="background-color:yellow"
onfocus="nameChanged();"/>
<label id='nameRes' style="color:red"></label><br>
<br> Email: <input type='text' name='email' id='email'/>
<br> Password: <input type='password' name='pass' id="pass" /><br>
Gender<input type='radio' name='gender' id="r1" value="Male">Male
<input type='radio' name='gender'id="r2" value="Female">Female<br>
Mobile:<input type='text' name='mobile' id="mobile" /><br>
Address<textarea id="address" name='address'rows="4" cols="50" style="background-color:green"
onfocus="addressChanged();"></textarea><br>
<button type='submit' id="submit" class="button button1">Submit</button>
</form> <script>
var dt = new Date();
document.getElementById("datetime").innerHTML = dt.toLocaleString();
function myFunction() {
var alphaExp = /^[a-zA-Z]+$/;
var name = document.getElementById("name");
if(name.value.length == 0) {
alert("Name cannot be blank");
return false; }
if(!name.value.match(alphaExp)) {
alert("Name Must be character");
return false; }
var emailExp = /^[a-zA-Z0-9]+[@]+[a-zA-Z]+[.]+[a-zA-Z]+$/;
var email = document.getElementById("email");

CU IDOL SELF LEARNING MATERIAL (SLM)


JavaScript/CSS 339

if(!email.value.match(emailExp)) {
alert("Enter valid email"); }
var uInput = document.getElementById("pass");
if((uInput.value.length>= 6 && uInput.value.length <= 20)) {
}
else {
window.alert("Please enter between 6 and 20 characters" );
uInput.focus();
return false; }
var r1 = document.getElementById("r1");
var r2 = document.getElementById("r2");
if (!r1.checked && !r2.checked) {
alert("Select gender");
return false; }
var mobileExp = /^[0-9]+$/;
var mobile = document.getElementById("mobile");
if((mobile.value.length>= 10 && mobile.value.length <= 12))
{
}
if(!mobile.value.match(mobileExp)) {
alert("Enter valid mobile");
return false; }
alert("All details are correct\nTHank YOu");
}
function nameChanged() {
var inputVal = document.getElementById("name");
inputVal.style.backgroundColor = "lightyellow";
}
function addressChanged() {
var inputVal = document.getElementById("address");
inputVal.style.backgroundColor = "yellowgreen"; }
function mousever() {
var inputVal = document.getElementById("email");
inputVal.style.backgroundColor="#ffcccc";
} </script> </body> </html>

CU IDOL SELF LEARNING MATERIAL (SLM)


340 Advanced Internet Programming

1. Create a registration page using HTML and CSS with right corner of the page
having current date and time.

2. Design specification for the webpage as follows:


(a) The text box background color will be displayed and shadowed when th cursor
inserts into the text field.
(b) The text area background color will be displayed by and shadowed when the cursor
places into textarea.
(c) The submit button background color will be displayed and shadowed when the
cursor moves over the submit button.

(d) For the same page and write validation function for registration page and modify
the onSubmit event handler in the form code to validate the following form fields:
(i) FirstName
– Must be entered

– Must be Character

CU IDOL SELF LEARNING MATERIAL (SLM)


JavaScript/CSS 341

(ii) Password
Password length should be between 6 to 20 characters.

(iii) Gender(Use radio button)


Must be selected

(iv) Mobile Number


Must be in format(XXXXXXXXXXXX)

CU IDOL SELF LEARNING MATERIAL (SLM)


342 Advanced Internet Programming

(v) Email
Email address must contain at least an @ sign and a dot(.)

When all input are entered correctly

CU IDOL SELF LEARNING MATERIAL (SLM)


PRACTICAL JAVA SERVER PAGES
UNIT 3
vcvc
Practical - 1
Create a Bean that Represents Information Needed to Calculate an Employee's
Salary. Has String (Employee Name) and int (Employee ID) Properties. Create an
Application to Demonstrate Automatically Filling in Bean Properties from Request
Parameters
1. Create new Web Application
File> New Project > Under Categories select “Java Web” – Under Project Select
Web Application > Next > Rename Project as “JSPBeanEx” > Next > Next >
Finish.
2. In index.htmlw

<body>
<div>XYZ org</div>
<form action ="NewServlet">
Employee Name: <input type ="text" name="empname"/>
Employee ID: <input type ="text" name="empid"/>
<input type="submit" value="submit"/>
</form>
</body>

3. Creating Java bean

CU IDOL SELF LEARNING MATERIAL (SLM)


344 Advanced Internet Programming

Type package name as “pkg”> Finish.

Add new Java Class “EmpDetails” in the Package “pkg”

//EmpDetails.java

package pkg;
public class EmpDetails {
private String empname;
private int empid;
public int getEmpid() {
return empid;
}
public void setEmpid(int empid) {
this.empid = empid;
}
public String getEmpname() {

CU IDOL SELF LEARNING MATERIAL (SLM)


Java Server Pages 345

return empname; }
public void setEmpname(String empname) {
this.empname = empname;
} }

4. Create a servlet “NewServlet” to set EmpDetails bean proerties.

Then click Next.

//NewServlet.java
import javax.servlet.RequestDispatcher;

protected void processRequest(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
pkg.EmpDetails emp=new pkg.EmpDetails();
int empid=Integer.parseInt(request.getParameter("empid"));
String empname=request.getParameter("empname");
emp.setEmpid(empid);

CU IDOL SELF LEARNING MATERIAL (SLM)


346 Advanced Internet Programming

emp.setEmpname(empname);
/**** Storing Bean In Session ****/
request.getSession().setAttribute("emp", emp);
RequestDispatcher rd = request.getRequestDispatcher("/beanData.jsp");
rd.forward(request, response); }

5. Create jsp “beanData” to show the bean properties.

CU IDOL SELF LEARNING MATERIAL (SLM)


Java Server Pages 347

//beanData,jsp

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


<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Emp Details</title>
</head> <body>
Employee Id:${emp.empid}<br>
Name:${emp.empname}
</body> </html>

6. Executing the application:


(i) Right Click on application to build.

(ii) Right Click on application to build.

(iii) Right Click on application to execute(Select Run).

CU IDOL SELF LEARNING MATERIAL (SLM)


348 Advanced Internet Programming

Experiment: II
(i) Create an emp table in the database with fields name, id and designation.
(ii) Create a HTML file with fields name, id and designation. Make sure that the
textfields have the same name as name, id and designation.
(iii) Create a javabean with fields name, id and designation.
(iv) On click of the submit button of the HTML, invoke a jsp page which will
extract the values that were given by the HTML page and it invokes a servlet.
(v) The Servlet will make a connection to the database and store the value in the
table.
(vi) Connection to the database should have been established using a separate
java class.
(vii) You can enhance the program by including more features like deletion,
updation and selecting all records.
1. Open MySql Command Line Client

create database mscit;


use mscit;
create table emp(id int, name varchar(20), designation varchar(20));
select * from emp;

2. Create new Web Application

File> New Project > Under Categories select “Java Web” – Under Project Select Web Application > Next
> Rename Project as “JSPBeanEx2” > Next > Next > Finish.

3. In index.html

<body> <div>XYZ org</div>


<form action ="newjsp.jsp">
Employee Name: <input type ="text" name="name"/>
Employee ID: <input type ="text" name="id"/>

CU IDOL SELF LEARNING MATERIAL (SLM)


Java Server Pages 349

Employee Designation: <input type ="text" name="designation"/>


<input type="submit" name="save" value="Save"/>
</br> </form>
<form action ="ShowData">
<input type="submit" name="show" value="Show"/>
</form> </body>

4. Creating a Java bean

Type package name as “pkg”> Finish.


Add new Java Class “EmpDetails” in the Package “pkg”

CU IDOL SELF LEARNING MATERIAL (SLM)


350 Advanced Internet Programming

//EmpDetails.java
package pkg;
public class EmpDetails {
private String empname;
private int empid;
private String designation;
public int getEmpid() {
return empid;
}
public void setEmpid(int empid) {
this.empid = empid; }
public String getEmpname() {
return empname;
}
public void setEmpname(String empname) {
this.empname = empname; }
public String getEmpDesignation() {
return designation;
}
public void setEmpDesignation(String designation) {
this.designation = designation;
} }

CU IDOL SELF LEARNING MATERIAL (SLM)


Java Server Pages 351

5. Creating jsp “newjsp” to set bean properties

//newjsp.jsp
<%@page language="java" 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>
<%
pkg.EmpDetails emp=new pkg.EmpDetails();
int id=Integer.parseInt(request.getParameter("id"));
String name=request.getParameter("name");

CU IDOL SELF LEARNING MATERIAL (SLM)


352 Advanced Internet Programming

String designation=request.getParameter("designation");
emp.setEmpid(id);
emp.setEmpname(name);
emp.setEmpDesignation(designation);
/**** Storing Bean In Session ****/
request.getSession().setAttribute("emp", emp);
RequestDispatcher rd = request.getRequestDispatcher("/NewServlet");
rd.forward(request, response);
%> </body> </html>

6. Create a Servlet “NewServlet” to store values in database.

Then click Next.

CU IDOL SELF LEARNING MATERIAL (SLM)


Java Server Pages 353

//NewServlet.java
import java.sql.*;
import pkg.EmpDetails;
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
Connection dbcon = null;
PreparedStatement stmt = null;
try
{
if(request.getParameter("save").equals("Save")) {
Class.forName("com.mysql.jdbc.Driver").newInstance();
dbcon = DriverManager.getConnection("jdbc:mysql://localhost/mscit","root","123456");
stmt=dbcon.prepareStatement("insert into Emp values(?,?,?)");
EmpDetails emp = new EmpDetails();
emp=(EmpDetails)request.getSession().getAttribute("emp");
stmt.setInt(1,emp.getEmpid());
stmt.setString(2,emp.getEmpname());
stmt.setString(3,emp.getEmpDesignation());
stmt.executeUpdate();
out.println(" records inserted");
dbcon.close();
} }
catch(Exception e)
{
out.println(e.toString());
} }
catch(Exception e)
{
} }
Add mysql java connector jar file

CU IDOL SELF LEARNING MATERIAL (SLM)


354 Advanced Internet Programming

Add Servlet “ShowData” to display values


//ShowData.java
import java.sql.*;
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
Connection dbcon = null;
PreparedStatement stmt = null;
Class.forName("com.mysql.jdbc.Driver").newInstance();
dbcon = DriverManager.getConnection("jdbc:mysql://localhost/mscit","root","123456");
String query = "SELECT * FROM emp";
Statement st = dbcon.createStatement();

CU IDOL SELF LEARNING MATERIAL (SLM)


Java Server Pages 355

ResultSet rs = st.executeQuery(query);
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet ShowData</title>");
out.println("</head>");
out.println("<body>");
out.println("ID Name Designation");
out.println("<br>");
while (rs.next())
{
int id = rs.getInt("id");
String name = rs.getString("name");
String designation = rs.getString("designation");
out.println(id+" "+name+" "+designation);
out.println("<br>");
}
out.println("</body>");
out.println("</html>");
} catch(Exception e) { }
}

7. Executing the application:


(i) Right Click on application to build.

CU IDOL SELF LEARNING MATERIAL (SLM)


356 Advanced Internet Programming

(ii) Right Click on application to build.

(iii) Right Click on application to execute(Select Run).

Note: Delete and Update can be implemented in the same way.

CU IDOL SELF LEARNING MATERIAL (SLM)


PRACTICAL AJAX
UNIT 4
vcvc
Practical - 1
(A) Develop a web application to dynamically check for availability of an email-id for registration. If
email-id does not exist in the database “Available!” else “Not Available!”, should be displayed
next to the email textbox. If email-id pattern does not conform to an email-id, display Invalid
Email Id. Perform the check when the textbox loses focus. Consider the following fields for
the Profile table:

EMAIL, PASSWORD, NAME,

DATEOFBIRTH, GENDER,

CITY, PINCODE, MOBILE

Note* : Check should be performed irrespective of uppercase or lowercase data.

1. Open MySql Command Line Client

create database mscit;


use mscit;
create table emp(id int, name varchar(20), email varchar(30),pass varchar(20),dob varchar(20),
gender varchar(6),city varchar(20), pincode varchar(10), mobile varchar(10));
insert into emp values(2,'mscit','xyz@gmail.com','123456','1-10-1994',
'male','mumbai','400000','9865432222');
insert into emp values(1,'mscit','abc@gmail.com','123456','1-10-1994',
'male','mumbai','400000','9876543210');

select email from emp;

CU IDOL SELF LEARNING MATERIAL (SLM)


358 Advanced Internet Programming

2. Create new Web Application

File> New Project > Under Categories select “Java Web” – Under Project Select Web Application > Next
> Rename Project as “JavaAjaxTest” > Next > Next > Finish.

3. In index.html

<!doctype html>
<html>
<body >
<form method='post' action="saveServlet">
ID<input type='text' name='id' /><br>
Name:<input type='text' name='name' /><br>
Email: <input type='text' name='email' id='email'>
<span id='response' style="color:red"></span><br>
Password: <input type='password' name='pass' /><br>
DOB:<input type='text' name='dob' /><br>
Gender<input type='radio' name='gender' value="Male">Male
<input type='radio' name='gender' value="Female">Female<br>
CITY:<input type='text' name='city' /><br>
Pincode:<input type='text' name='pincode' /><br>
Mobile:<input type='text' name='mobile' /><br>
<input type='submit' value='submit' name='submit'><br>
</form>
<!-- Script -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#email').focusout(function(){
var email = $('#email').val();
$.ajax({
type: 'post',
data: {ajax: 1,email:email},
url:'checkEmail',
success: function(response){
$('#response').text( response);
}
});
}); });
</script> </body> </html>

CU IDOL SELF LEARNING MATERIAL (SLM)


AJAX 359

4. Add a servlet checkEmail

//checkEmail.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
Connection dbcon = null;
Class.forName("com.mysql.jdbc.Driver").newInstance();
dbcon = DriverManager.getConnection("jdbc:mysql://localhost/mscit","root","123456");
String query = "SELECT email FROM emp";
Statement st = dbcon.createStatement();
ResultSet rs = st.executeQuery(query);
String email=request.getParameter("email");
int existEmail=0;
while (rs.next())
{
String dbemail = rs.getString("email");
if(email.equalsIgnoreCase(dbemail))
{
existEmail=1;
} }
if(existEmail==0)
out.println("Available");
else
out.println("Not-Available");
}

CU IDOL SELF LEARNING MATERIAL (SLM)


360 Advanced Internet Programming

catch(Exception e)
{ System.out.println("error"+e.getMessage()); } }

Add new Servlet “saveServlet” to save data in database

//saveServlet.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
Connection dbcon = null;
PreparedStatement stmt = null;
Class.forName("com.mysql.jdbc.Driver").newInstance();
dbcon = DriverManager.getConnection("jdbc:mysql://localhost/mscit","root","123456");
stmt=dbcon.prepareStatement("insert into Emp values(?,?,?,?,?,?,?,?,?)");
stmt.setInt(1,Integer.parseInt(request.getParameter("id")));
stmt.setString(2,request.getParameter("name"));
stmt.setString(3,request.getParameter("email"));
stmt.setString(4,request.getParameter("pass"));
stmt.setString(5,request.getParameter("dob"));
stmt.setString(6,request.getParameter("gender"));
stmt.setString(7,request.getParameter("city"));
stmt.setString(8, request.getParameter("pincode"));
stmt.setString(9,request.getParameter("mobile"));
stmt.executeUpdate();
out.println(" records inserted");
dbcon.close();
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet saveServlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Data inserted");
out.println("</body>");
out.println("</html>");
}

CU IDOL SELF LEARNING MATERIAL (SLM)


AJAX 361

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

Add mysql java connector jar file

5. Executing the application:


(i) Right Click on application to build.

CU IDOL SELF LEARNING MATERIAL (SLM)


362 Advanced Internet Programming

(ii) Right Click on application to build.

(iii) Right Click on application to execute(Select Run).

CU IDOL SELF LEARNING MATERIAL (SLM)


www.cuidol.in
1800-1213-88800

INSTITUTE OF DISTANCE & ONLINE LEARNING


NH-95, Chandigarh-Ludhiana Highway, Gharuan, Mohali (Punjab)
Phone:- 7527009635 | Email: info@cuidol.in
FOLLOW US ON:

You might also like