Professional Documents
Culture Documents
ADVANCED INTERNET
PROGRAMMING
(THEORY AND PRACTICAL)
MCA631/MCA636
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.
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 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.
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 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.
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.
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.
(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.
Structure:
1.0 Learning Objectives
1.1 Introduction
1.11 Summary
1.15 References
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.
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:
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.
(i) java.sql
(ii) javax.sql.
Java SE and Java EE platforms are included in both the packages.
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.
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.
Java Java
Application 1 Application 2
JDBC API
Driver Manager
JDBC-ODBC Bridge
JDBC Driver
ODBC Driver
Microsoft
MySQL Oracle
Access Database
Database Database
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
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.
This type of diver is faster than JDBC-ODBC driver. Java API Driver
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
Native Protocol
OB
Syntax
Connection con=DriverManager.getConnection(url,"loginName","Password")
Statement createStatement()
PreparedStatementprepareStatement(String sql)
returns a new PreparedStatement object. PreparedStatement objects are precompiled SQL
statements.
CallableStatementprepareCall(String sql)
returns a new CallableStatement object. CallableStatement objects are SQL stored procedure
call statements.
For statements that create or modify tables, the method to use is executeUpdate.
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();
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.
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"));
}
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.
{ 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.....:");
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.
Answers
1. (c), 2. (a), 3. (d), 4. (a), 5. (c)
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
Structure:
2.0 Learning Objectives
2.1 Introduction
2.12 JButton
2.13 JLabel
2.14 JText
2.15 JTextArea
2.17 Jlist
2.18 JcomboBox
2.22 J scrollBar
2.26 Summary
2.31 References
2.1 Introduction
MVC stands for Model View and Controller. It is a design pattern that separates the
business logic, presentation logic and data.
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.
VIEWER
MODEL
CONTROLLER
Controller Action
Servlet Filter
Interceptor
Web Browser Select result
Client
View
Result
Render result
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.
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:
Output
NORTH
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.*; ;
;
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));
JFrame f; f.setVisible(true);
FlowLayoutDemo() { }
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();
} }
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");
Output:
Flower
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 ).
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.
Component JLabel
JList
JTable
Container JComponent
JComboBox
JMenu
Applet
AbstractButton
Frame Dialog
JButton
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.
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.
The argument to setDefaultCloseOperation must be one of the following values, which are
defined in the Window Constants interface:
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.
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
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.
//First.java /*
Import java.applet.Applet; <applet code="First.class" width="300"
Import java.awt.Graphics; height="300">
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.
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.
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.
protected void setUI(ComponentUI newUI) It sets the look and feel delegate for this
component.
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.
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);
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); }
}
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.
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);
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).
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);
+"Youcanchangethenumberoflinesthatcanbedisplayed frame.add(textAreal);
atatime," frame.add(scrollPane);
+"aswellasthenumberofcolumns.Youcanwraplinesand frame.pack();
wordstoo."
frame.setVisible(true);
+"YoucanalsoputyourJTextAreainaJScrollPanetomakei
tscrollable."; }}
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);
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);
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
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);
String s[]={"Dbms","Java","Linux","OS"};
Output
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);
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.
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.
Example:
{ popupMenu.addSeparator();
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"); }
m1=new MenuItem("New"); {
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
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
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.
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:
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( ).
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
default, page-up and page-down increments are 10. You can change this value by calling set
BlockIncrement( ).
1. void setUnitIncrement(intnewIncr)
2. void setBlockIncrement(intnewIncr)
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.
JFrame f; }
OptionPaneExample() { publicstaticvoidmain(String[]args) {
f=newJFrame(); newOptionPaneExample();
JOptionPane.showMessageDialog(f,"SuccessfullyU } }
Output:
Output:
2.24 JFileChooser
A JFileChooser is a dialog to select a file or files.
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);
}}
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();
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.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:
2. Lightweight Containers
It inherits JComponent class.
It is a general purpose container.
It can be used to organize related components together.
Example: JPanel
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”.
Structure:
3.0 Learning Objectives
3.1 Introduction
3.3 Events
3.16 References
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.
The modern approach to handling events is based on the delegation event model, which
defines standard and consistent mechanisms to generate and process events.
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
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.
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.
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.
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.
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.
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.
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)
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)
{
b = (JButton)ae.getSource();
sayHi();
}
});
b.addActionListener(this)
publi void actionPerformed(ActionEvent ae){
b = (JButton)ae.getSource();
sayHi();
}
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.
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.
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); } }
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.
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);
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");
Example of JApplet:
import javax.swing.*; prsMe.addActionListener(this);
import java.awt.*; answr.addActionListener(this); }
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.
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
Structure:
4.0 Learning Objectives
4.1 Introduction
4.11 Summary
4.15 References
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.
Database
Legacy Application
Java Application
Web Service
Client (End User) Web Server
(Servlets/JSP)
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.
Client
HTTP Response
Servlet Container
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.
Client 1
Java Server/
java Server
Page/XML
Client 2 Application
Server
Database/
Client 3 Web Services
Web Server
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.
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.
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.
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.
Client Tier
Applications Browsers
APIs
Middle Tier
J2EE Platform
EJB Server Web Server
APIs APIs
EIS Tier
Applications Database
Servers
Files Databases
HTTP Server
HTTP Protocol
Database
Servlets Tasks
Servlets perform the following major tasks:
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.
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.
Init (servletConfig)
4. Call the service method. Service (req, resp)
Destroy ()
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
(Unavailable
unavailable for exception
service thrown)
(Initialization
Failed)
Destroy
Unload
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.
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.
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.
HttpServletRequest
HttpServletResponse
HttpSession
HttpSessionListener
HttpSessionAttributeListener
HttpSessionBindingListener
HttpSessionActivationListener
HttpSessionContext (deprecated now)
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
HttpServlet
Cookie
HttpServletRequestWrapper
HttpServletResponseWrapper
HttpSessionEvent
HttpSessionBindingEvent
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.
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.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.
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
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
Explain servicing client requests and GET and POST request methods
Discuss Retrieving data from databaseto servlet, Servlet config and Servletcontext
Elaborate session tracking
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.
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 Response
Client
It is the protocol that allows web servers and browsers to exchange data over the web.
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.
Web Server
Database
HTTP Protocol
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.
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.
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.
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.
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-
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
st=con.createStatement(); } } }
insertData.html
<!DOCTYPE html> <td><input type="text"
<html> name="txtStudName"></td>
<head> </tr>
<body> </tr>
<center> <tr>
InsertStudent.java
import javax.servlet.*; marksSSC=Float.parseFloat(request.getPar
import javax.servlet.http.*; ameter("txtMarksSSC"));
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>
<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+";";
updateData.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>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
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");
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
ServletConfig:
ServletConfig is an object containing some initial parameters or configuration
information created by Servlet Container and passed to the servlet during initialization.
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.
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.
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.
<a href=”/bookshop/logincheck”>
<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.
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 }
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.
Example of Cookies
// index.html public void doPost(HttpServletRequest request,
<form action="servlet1" method="post"> HttpServletResponse response) {
// 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.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. 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
Structure:
6.0 Learning Objectives
6.1 Introduction
6.8 Summary
6.12 References
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.
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.
xhttp.open("GET","ajax_info.txt",true);
xhttp.send();
GET or POST?
GET is simpler and faster than POST, and can be used in most cases.
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();
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");
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).
xhttp.open("GET","ajax_test.asp",true);
By sending asynchronously, the JavaScript does not have to wait for the server response, but
can instead:
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;
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.
Example
Following is the example to show the usage of statusand response Text properties –
} <br />
function successFunc(response) { <br />
if (200 == response.status) { <input type = "button" value = "Submit" onclick
alert("Call is success"); = "SubmitRequest();"/>
} </body> </html>
#!/usr/bin/perl
print "Content-type: text/html\n\n";
print "This content is returned by AJAX cgi ";
print "Current Time " . localtime
Example
Following is the example to show the usage of getAllHeaders() and
getResponseHeader(name) methods –
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
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.
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
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.
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”).
Fetching data from MYSQL database in JSP and Servlet with JSON and JQuery.
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.
In this example, we have written the server side code inside the index.jsp file.
<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);
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();
<body> }
%>
6.8 Summary
AJAX is a developer’s dream, because you can:
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”.
Structure:
7.0 Learning Objectives
7.1 Introduction
7.4 Handling XML data using PHP and AJAX, AJAX JSON
7.6 Summary
7.10 References
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.
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.
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.
</head> </form>
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++) }
{ } }
“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.
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.
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.
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.
<html> document.getElementById("txtHint").innerHTM
<head> L = xmlhttp.responseText;
<script> } }
return; <form>
} Select a Course:
<?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>");
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.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.
Classic web pages, (which do not use AJAX) must reload the entire page if the content
should change.
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”.
Structure:
8.0 Learning Objectives
8.1 Introduction
8.10 Filter
8.13 Summary
8.17 References
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.
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.
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.
Web Server
7. Instantiate Servlet
JSP Scriptlet
JSP Declaration
JSP Expression
JSP Comments
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:
<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.
<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.
Syntax:
</p>
</body> </html>
Output:
Today’s Date: 03-Aug-2016 10:52:21
JSP Directive Elements can be declared within the following special characters '<%@ %>'.
Syntax for using directive in the JSP page is as follows :
HTML comment tag is denoted by the special characters '<!-- -->' where, '<!--' specifies the
start tag and '-->' specifies the end tag.
Syntax:
<html>
<head>
<title>JSP Comments</title> </head>
<body>
<%-- this will hide on JSP page --%>
</body> </html>
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>
In a scripting element, if the characters %> needs to be used, escape the greater than sign
with a backslash:
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:
As an alternative to escaping quote characters, the character entities ' and " can
also be used.
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
Syntax
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.
Syntax:
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.
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.
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:
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: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:getProperty
Gets the value of a Bean property so that you can display it in a result page.
Syntax
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).
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:
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
<html>
<head>
<title>Welcome in In the program of URL rewriting</title> </head> <body>
<font size = 6>Hello</font> <%= session.getAttribute("username") %>
</body> </html>
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:
<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,
<%= 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.
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>
Output:
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.
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.
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 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.
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.
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.
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.
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].
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
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.
Once JSP or servlet completes its logic , request goes back to filter N and then Filter N-1..
and so on.
void init(FilterConfig)
doFilter (ServletRequest, ServletResponse, FilterChain)
public void destroy()
Request Response
Filter1 Filter1
Filter2 Filter2
Filter3 Filter3
JSP
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.
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.
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.
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
TLD File
JSP File Tag Handler class
Defining tag
Using tag name and Tag Business logic to be
Handler class performed on tag
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.
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.
Structure:
9.0 Learning Objectives
9.4 Sessions
9.6 Mapping
9.14 Summary
9.18 References
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.
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.
Hibernate Overview
(Object Relational Mapping)
Mapping
Object Relational
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.
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
Supported Databases
Hibernate supports almost all the major RDBMS. Following is list of few of the database
engines supported by Hibernate.
Java Application
Persistent Object
Hibernet
Database
Java Application
Persistent Object
Hibernet
Database
Database
APPLICATION
Persistent
HIBERNATE
Objects
DATABASE
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.
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.
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.
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.
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.
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.
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.
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.
Ans:
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.
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:
2. hibernate.jndi.class 5. hibernate.connection.username
The InitialContext class for JNDI. The database username.
3. hibernate.jndi.<JNDIpropertyname> 6. hibernate.connection.password
Passes any JNDI property you like to the JNDI The database password.
InitialContext.
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:
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();
} 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();
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.
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".
Some rules that should be, not must be followed by a persistence class.
There are following main rules of persistent classes, however, none of these rules are hard
requirements −
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>
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.
Example
Employee.java
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:
ORM
JDBC Relational
Java Middlewate
Database
Application
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.
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.
Consider we are going to use the following EMPLOYEE table to store our objects −
Following is the mapping of Employee class with annotations to map objects with the
defined EMPLOYEE table −
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.
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 −
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.
org.hibernate.SessionFactory;import tx = session.beginTransaction();
org.hibernate.cfg.Configuration; List employees = session.createQuery("FROM
public class ManageEmployee { Employee").list();
ME.listEmployees(); } finally {
} session.close();
try { try {
tx = session.beginTransaction(); tx = session.beginTransaction();
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>
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>
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:
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.
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 −
If you need to fully qualify a class name in HQL, just specify the package and class name as
follows
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 −
The AS keyword is optional and you can also specify the alias directly after the class name,
as follows −
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 −
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 −
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 −
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 −
DELETE Clause
The DELETE clause can be used to delete one or more objects. Following is the simple
syntax of using DELETE clause −
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 −
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 −
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.
Restrictions class
Restrictions class provides methods that can be used as Criterion. The commonly used
methods of Restrictions class are as follows:
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.
2. public static Order desc(String propertyName) applies the descending order on the
basis of given property.
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();
1.Criteria c=session.createCriteria(Emp.class);
2. c.setProjection(Projections.property("name"));
3. List list=c.list();
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
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();
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
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.
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
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.
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 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 −
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.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.
Answers
1. (c), 2. (d), 3. (b), 4. (a), 5. (a)
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
Structure:
10.0 Learning Objectives
10.1 Introduction
10.6 Configuration
10.7 Actions
10.8 Interceptors
10.14 Summary
10.18 References
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.
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.
languages such as PHP, JAVA etc). ‘Controller” controls the interaction/transactions between the
“Model” and “Viewer”.
VIEWER
MODEL
CONTROLLER
Controller Action
Servlet Filter
Interceptor
View
Result
Render result
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 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.
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.
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.
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.
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.
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 −
%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
%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 −
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.
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:
10.6 Configuration
The Model-View-Controller Framework in Struts2 has five core components for
configuration:
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()
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.
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.
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.
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";
1. publicStringexecute();
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.
Welcome.java
package com.javatpoint;
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; }
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:
In above code, Action returns the SUCCESS. We have to modify struts.xml configuration
file as follows:
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 }}}
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.
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:
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>
<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.
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.
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
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>
<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.
<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>
Result Types
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.
We can use this interceptor to control the working of file upload in struts2 such as defining
allowed types, maximum file size etc.
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>
RegisterAction.java
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>
Output
// 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>
<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"))
{
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/>
// 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>
First screenshot
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:
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.
Structure:
11.0 Learning Objectives
11.1 Introduction
11.2 Validation
11.3 Localization
11.6 Annotation
11.7 Tags and Integrations
11.8 Practical Assignment
11.9 Summary
11.13 References
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.
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.
SMTP
POP
IMAP
MIME
NNTP and others
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.
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
Session session=Session.getDefaultInstance(properties,null);
Session session=Session.getInstance(properties,null);
To create the message, you need to pass session object in MimeMessage class constructor.
For example:
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:
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.
Transport.send(message);
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
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.
SendEmail.java
packageorg.websparrow; protectedPasswordAuthenticationgetPasswordAut
import java.util.Properties; hentication(){
index.jsp
success.jsp
} </h2>
error.jsp
Configuration File
Create the struts.xml file in the source package and map the Action class.
struts.xml
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.
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
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.
Create Views
We will use JSP file success.jsp which will be invoked in case defined action returns
SUCCESS.
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.
Configuration Files
Finally, let us put everything together using the struts.xml configuration file as follows –
Now do not enter any required information, just click on Submit button. You will see the
following result –
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.
The UI Tags
Messages and Errors.
Within action classes.
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.
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.
To display i18n text, use a call to getText in the property tag, or any other tag, such as the UI
tags as follows −
The text tag retrieves a message from the default resource bundle, i.e., struts.properties
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−
The key attribute of most UI tags can be used to generate a message from a resource bundle-
his example tries to show in a simple and straight forward way of creating a web application
with Internationalization or I18N capability.
1. HelloWorld.java
2. HelloWorld_en.properties and HelloWorld _hi.properties
3. HelloWorld.jsp
4. struts.xml
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.
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:
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.
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.
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 −
Let us now configure Struts to use this error page in case of an exception. Let us modify the
struts.xml as follows –
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.
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.
Create Views
We will use JSP file success.jsp which will be invoked in case the defined action returns
SUCCESS.
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.
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() {
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 –
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 –
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 –
ActionContext
Object 0
parameters
application
Value Stack attr
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.
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.
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.
In the same way you can also store the values in other maps available in the ActionContext.
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>
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:
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>
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>
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.
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.
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.
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.
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
FOOTER
If you are using eclipse or Netbeans IDE, you need to add the required tiles library in your
project.
If you are using eclipse or Netbeans IDE, you need to add the required tiles library in your
project.
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>
<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>
<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>
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.
6. Create the tiles.xml file and define all the tiles definitions
The tiles.xml file must be located inside the WEB-INF directory.
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>
Output
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.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.
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.
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);
} } }
Output
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());
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)
.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);
} }
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>
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>
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)
{
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:
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 {
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";
} }
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:
HomeController.java will be the single controller class in our spring MVC example
application.
Right click on the project explorer window and click on “New -> Dynamic Web Project” as
shown in below image.
Provide name as “spring-mvc-app” in the next popup page, rest of the things should not
required to be changed.
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.
Click on Finish and you will have a new Dynamic Web Project in your eclipse project
explorer.
Right click on the project and select “Configure -> Convert to Maven Project”.
<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.
</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>
Right click WEB-INF ( New ( File and type the name and click fFnish.
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";
} }
package spring.model;
public class User {
private String userName;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
} }
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">
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.
HPH
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 -->
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
?????? 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>
<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>
<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>
<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>");
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>
</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>");
}
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
{
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>
<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");
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.*;
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>");
} }}
Output:
Home page
Table Creation
Before Updation
After Updation
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>
</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.*;
Repeat the code from Page2.java for Page3.java, Page4.java and Page5.java with
relevant changes.
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;
/**
* @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);
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)
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
– Must be selected
– Must be in format(XXXXXXXXXXXX)
(v) Email
<!DOCTYPE html>
<!--
<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;
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");
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>
1. Create a registration page using HTML and CSS with right corner of the page
having current date and time.
(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.
(v) Email
Email address must contain at least an @ sign and a dot(.)
<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>
//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() {
return empname; }
public void setEmpname(String empname) {
this.empname = empname;
} }
//NewServlet.java
import javax.servlet.RequestDispatcher;
emp.setEmpname(empname);
/**** Storing Bean In Session ****/
request.getSession().setAttribute("emp", emp);
RequestDispatcher rd = request.getRequestDispatcher("/beanData.jsp");
rd.forward(request, response); }
//beanData,jsp
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
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
//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;
} }
//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");
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>
//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
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) { }
}
DATEOFBIRTH, GENDER,
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>
//checkEmail.java
catch(Exception e)
{ System.out.println("error"+e.getMessage()); } }
//saveServlet.java
catch(Exception e)
{
out.println(e.getMessage());
} }