0% found this document useful (0 votes)
16 views149 pages

Advance Java

The document contains lecture notes for an Advanced Java Programming course at Maharaja Institute of Technology Mysore, detailing the course objectives, outcomes, and syllabus. It outlines the vision and mission of the institution, emphasizing the development of competent professionals and the importance of ethical practices. The syllabus covers key topics such as Servlets, JSP, JDBC, and EJB, aimed at equipping students with practical skills for dynamic web application development.

Uploaded by

chandra kala
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views149 pages

Advance Java

The document contains lecture notes for an Advanced Java Programming course at Maharaja Institute of Technology Mysore, detailing the course objectives, outcomes, and syllabus. It outlines the vision and mission of the institution, emphasizing the development of competent professionals and the importance of ethical practices. The syllabus covers key topics such as Servlets, JSP, JDBC, and EJB, aimed at equipping students with practical skills for dynamic web application development.

Uploaded by

chandra kala
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 149

Maharaja Education Trust (R), Mysuru

Maharaja Institute of Technology Mysore


Belawadi, SrirangaPattanaTaluk, Mandya – 571 477

Approved by AICTE, New Delhi,


Affiliated to VTU, Belagavi& Recognized by Government of Karnataka

Lecture Notes on
Advanced Java Programming (18MCA41)

Prepared by

Department of Master of Computer Applications

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page 1


Maharaja Education Trust (R), Mysuru
Maharaja Institute of Technology Mysore
Belawadi, SrirangaPattanaTaluk, Mandya – 571 477

Vision/ ಆಶಯ
“To be recognized as a premier technical and management institution promoting extensiveeducation
fostering research, innovation and entrepreneurial attitude"
ಸಂಶೋಧನೆ,
ಆವಿಷ್ಕಾ ರಹಾಗೂಉದ್ಯ ಮಶೋಲತೆಯನ್ನು ಉತೆತ ೋಜಿಸುವಅಗ್ರ ಮಾನ್ಯ ತಾಂತ್ರರ ಕಮತ್ತತ ಆಡಳಿತವಿಜ್ಞಾ ನ್ಶಕ್ಷಣ
ಕಾಂದ್ರ ವಾಗಿಗುರುತ್ರಸಿಕೊಳ್ಳು ವುದು.
Mission/ ಧ್ಯ ೇಯ
➢ To empower students with indispensable knowledge through dedicated teaching and collaborative
learning.
ಸಮರ್ಪಣಾಮನೋಭಾವದ್ಬೋಧನೆಹಾಗೂಸಹಭಾಗಿತವ ದ್ಕಲಿಕಾಕರ ಮಗ್ಳಿಾಂದ್ವಿದ್ಯಯ ರ್ಥಪಗ್ಳನ್ನು ಅತಯ ತಾ ೃ
ಷ್ಟ ಜ್ಞಾ ನ್ಸಂರ್ನ್ು ರಾಗಿಸುವುದು.
➢ To advance extensive research in science, engineering and management disciplines.
ವೈಜ್ಞಾ ನಿಕ,

ತಾಂತ್ರರ ಕಹಾಗೂಆಡಳಿತವಿಜ್ಞಾ ನ್ವಿಭಾಗ್ಗ್ಳಲಿಿ ವಿಸತ ೃತಸಂಶೋಧನೆಗ್ಳೊಡನೆಬೆಳವಣಿಗೆಹಾಂದು


ವುದು.
➢ To facilitate entrepreneurial skills through effective institute - industry collaboration and interaction
with alumni.
ಉದ್ಯ ಮಕ್ಷ ೋತಗ್ಳೊಡನೆಸಹಯೋಗ್,
ಸಂಸ್ಥೆ ಯಹಿರಿಯವಿದ್ಯಯ ರ್ಥಪಗ್ಳೊಾಂದಿಗೆ ನಿರಂತರಸಂವಹನ್ಗ್ಳಿಾಂದ್ವಿದ್ಯಯ ರ್ಥಪಗ್ಳಿಗೆಉದ್ಯ ಮಶೋಲತೆಯಕೌಶ
ಲಯ ರ್ಡೆಯಲುನೆರವಾಗುವುದು.
➢ To instill the need to uphold ethics in every aspect.
ಜಿೋವನ್ದ್ಲಿಿ ನೈತ್ರಕಮೌಲಯ ಗ್ಳನ್ನು ಅಳವಡಿಸಿಕೊಳ್ಳು ವುದ್ರಮಹತವ ದ್ಕುರಿತ್ತಅರಿವುಮೂಡಿಸುವುದು
.
➢ To mould holistic individuals capable of contributing to the advancement of the society.
ಸಮಾಜದ್ಬೆಳವಣಿಗೆಗೆಗ್ಣನಿೋಯಕೊಡುಗೆನಿೋಡಬಲಿ ರ್ರಿಪೂಣಪವಯ ಕ್ತತ ತವ ವುಳು ಸಮರ್ಪನಾಗ್ರಿೋಕರ

ನ್ನು ರೂಪಿಸುವುದು.

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page 2


Maharaja Institute of Technology Mysore
Department of MCA

Vision/ ಆಶಯ

“To be the premier source that provides a transformative education to create computer
professionals, competent entrepreneurs & technocrats to meet the global challenges.”

“ಜಾಗತಿಕ ಸವಾಲುಗಳನ್ನು ಎದುರಿಸಲು ಕಂಪ್ಯಯ ಟರ್ ವೃತಿಿ ಪರರು, ಸಮರ್ಥ ಉದ್ಯ ಮಿಗಳು
ಮತ್ತಿ ತಂತ್ರ ಜ್ಞ ರನ್ನು ರಚಿಸಲು ಪರಿವತ್ಥಕ ಶಿಕ್ಷಣವನ್ನು ಒದ್ಗಿಸುವ ಪರ ಮುಖ
ಮೂಲವಾಗಿದೆ”

Mission/ ಧ್ಯ ೇಯ

➢ To facilitate students to nurture skills to practice their professions competently to meet


the ever-changing needs of society & environment.
ಸಮಾಜ್ ಮತ್ತಿ ಪರಿಸರದ್ ಬದ್ಲಾಗುತಿಿ ರುವ ಅಗತ್ಯ ತೆಗಳನ್ನು ಪ್ಯರೈಸಲು ತ್ಮಮ
ವೃತಿಿ ಗಳನ್ನು ಸಮರ್ಥವಾಗಿ ಅಭ್ಯಯ ಸ ಮಾಡಲು ಕೌಶಲಯ ಗಳನ್ನು ಬೆಳೆಸಲು
ವಿದ್ಯಯ ರ್ಥಥಗಳಿಗೆ ಅನ್ನಕೂಲ ಮಾಡಿಕೊಡುವುದು
➢ To develop the potential of human resources with new ideas, research to meet the
requirements of cutting edge technology.
ಹೊಸ ಆಲೇಚನೆಗಳೊಂದಿಗೆ ಮಾನವ ಸಂಪನ್ಮಮ ಲಗಳ ಸಾಮರ್ಯ ಥವನ್ನು
ಅಭಿವೃದಿಿ ಪಡಿಸಲು, ಅತ್ಯಯ ಧುನಿಕ ತಂತ್ರ ಜಾಞ ನದ್ ಅವಶಯ ಕತೆಗಳನ್ನು ಪ್ಯರೈಸಲು
ಸಂಶೇಧನೆ

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page 3


Maharaja Institute of Technology Mysore
Department of MCA

Program Outcomes

1. An ability to apply knowledge in computer applications to become successful professionals.


2. An ability to develop logic and understand the essential mathematics related to Information
Technology.
3. An ability to Design, implement, and evaluates a software product.
4. An ability to apply skills for solving technical problems in software development.
5. An ability to familiarize with emerging & advanced software tools.
6. An ability to experience the industrial environment for understanding the impact of
computational solutions in a global & societal context.
7. An ability to analyze the knowledge of contemporary issues.
8. An ability to apply professional ethics.
9. An ability to get readiness to collaborate in a multi-disciplinary team.
10. An ability to communicate effectively.
11. An ability to participate in life-long learning.
12. An ability to handle the projects through appropriate project management techniques.

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page 4


Maharaja Institute of Technology Mysore
Department of MCA
Course Overview

Subject:Advanced Java Programming Subject Code:18MCA41


This course focus on the development of dynamic database web application using Java servlets, JSP
and Java Beans. Usage of servlets, JSP, Bean in providing dynamic behaviour to the application.
Implementing Dynamic HTML using Servlet and demonstration of service methods, auto web page
refresh, Session tracking using cookie and Http Session in Servlet. Learn the fundamental of
connecting to the database. Demonstrate JSP (page attributes, action tags and all basic tags) and
introduction to EJB application.

Course Objectives

The objectives of this course is to make students to learn-


• Learn the concept of Servlet, JSP and its services
• Learn how to create packages and interfaces
• Need and usage of Session management techniques.
• Build Database connection
• Introduction to Enterprise Java Bean Applications
• Developing dynamic database web applications using servlets and JSP.

Course Outcomes
COs Description

Understand the Advanced java concepts, JDBC Architecture, Database interactions


18MCA41.1
and EJB.

18MCA41.2 Apply the usage of Servlets, JSP and Java beans in the development of Java Web
and Enterprise Application.
18MCA41.3 Analyze a solution for the given problem scenario.

18MCA41.4 Recommend the solutions through Java Web application /Java Enterprise
Application.
18MCA41.5 Design the learning's into real world problems solutions.

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page 5


Maharaja Institute of Technology Mysore
Department of MCA
Syllabus

Subject: Advanced Java Programming Subject Code:18MCA41

MODULE-1
Servlet
Servlet Structure, Servlet packaging, HTML building utilities, Lifecycle, SingleThreadModel
interface, Handling Client Request: Form Data, Handling Client Request: HTTP Request Headers.
Generating server Response: HTTP Status codes, Generating server Response: HTTP Response
Headers, Handling Cookies, Session Tracking.
MODULE-2
Introduction to JSP
Overview of JSP: JSP Technology, Need of JSP, Benefits of JSP, Advantages of JSP, Basic
syntax,Invoking java code with JSP scripting elements, creating Template Text, Invoking java code
from JSP, Limiting java code in JSP, using jsp expressions, comparing servlets and jsp, writing
scriptlets. For example Using Scriptlets to make parts of jsp conditional, using declarations,
declaration example.
MODULE-3
Controlling the Structure of generated servletsand Java Beans
Controlling the Structure of generated servlets: The JSP page directive, import attribute, session
attribute, isElignore attribute, buffer and autoflush attributes, info attribute, errorPage and iserrorPage
attributes, isThreadSafe Attribute, extends attribute, language attribute, Including files and applets in
jsp Pages, using java beans components in JSP documents JAR files, manifest file, Working with
Java Beans. Introspection, Customizers, Bean properties: Simple properties, Design Pattern events,
creating bound properties, Bean Methods, Bean info class, Persistence.
MODULE-4
Annotations and JDBC
Annotations: Built-in Annotations with examples, Custom Annotation.
Talking to Database, Immediate Solutions, Essential JDBC program, using prepared Statement
Object, Interactive SQL tool. JDBC in Action Result sets, Batch updates, Mapping, Basic JDBC data
types, Advanced JDBC data types, immediate solutions.
MODULE-5
EJB and Server Side Component Models
Introduction to EJB: The Problem domain, Breakup responsibilities, Code Smart not hard, the
Enterprise java bean specification, Components Types. Server Side Component Types: Session
Beans, MessageDriven Beans, Entity Beans, The Java Persistence Model. Container services:
Dependency Injection, Concurrency, Instance pooling n caching, Transactions, security, Timers,
Naming and object stores, Interoperability, Life Cycle Callbacks, Interceptors, platform integration.
Developing your first EJB, Models: The Stateless Session Bean, the Stateful Session Bean, the
Singleton Session Bean, Message-Driven Beans. EJB and PERSISTENCE. Persistence Entity
manager Mapping Persistence objects, Entity Relationships.
Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page 6
Maharaja Institute of Technology Mysore
Department of MCA

Index

Subject:Advanced Java Programming Subject Code:18MCA41

SL. No. Contents Page No.


1 Module-1 10-
1.1 Introduction to Web, HTTP Protocol, 10-15
1.2 Introduction to CGI 16-17
1.3 Introduction to Servlets,Servlet structure 17-21
1.4 Servlet Life Cycle 21-24
1.5 The Servlet API (Servlet Packaging) and Creating Servlet 24-29
1.6 Servlets - Form Data, GET and POST Requests 29-35
1.7 Servlets - Client HTTP Request 35-39
1.8 Servlets - Server HTTP Response 40-44
1.9 Servlets - Http Status Codes 44-46
1.10 Servlet Request 46-49
1.11 Servlet Response 49-50
1.12 Introduction Request Dispatcher Interface 50-55
1.13 sendRedirect() Method 55-56
1.14 ServletConfig interface 56-57
1.15 ServletContext Interface 57-60
1.16 Introduction to Attributes 60-61
1.17 Managing Session in Servlets / Session Tracking in Servlets 61-77
1.18 SingleThreadModel interface 77
1.19 ServletInputStream class 78
1.20 ServletOutputStream class 78
1.21 Deployment Descriptor (web.xml) 78-79

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page 7


2 Module-2 80-90
2.1. Overview of JSP 80
Advantage of JSP
2.2. 80-81

2.3. Life cycle of a JSP Page 81-83

JSP Scriptlet tag (Scripting elements)


2.4. 83-84

2.5 Comparing JSP and Servlets 85

JSP Implicit Objects


2.6. 85-90

Module-3
3 91-113

3.1. Controlling the structure of generated servlets or JSP directives 91


3.2. JSP page directive 91-94
3.3. Jsp include Directive 94-95
3.4. jsp taglib directives 95-96
3.5. JSP Action Tags 96-98
3.6. Using java beans components in JSP documents 99-101
3.7. Introduction to Java Beans 102-104
3.8. Elements of a JavaBean 104
3.9. The JavaBean Component Specification 104
3.10. Services of JavaBean Components 104-105
3.11. Features of a JavaBean 105
3.12. Steps to Develop a User-Defined JavaBean 105-107
3.13. Introspection 107
3.14. Design patterns for JavaBean Properties 107-111
3.15. Design Patterns for Events 111
3.16. Persistence 111
3.17. Customizers 111
3.18. The Java Beans API 112
3.19. The BeanInfo Interface 113

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page 8


4 Module-4 114-136

4.1. Java Annotations 114-115


4.2. Java Custom Annotation 115-116
4.3. Built-in Annotations used in custom annotations in java 116-118
4.4. JDBC 118
4.5. JDBC Architecture 118-120
4.6. JDBC Driver 120-124
4.7. JDBC Packages 124

4.8. Talking to Database (JDBC Process Steps/A Brief Overview of the 124-127
JDBC Process)
4.9. Statement object to executes the SQL Queries 127-129
4.10. ResultSet 129-133

4.11. 133-134
JDBC - Data Types
4.12. Advanced JDBC data types 134
4.13. Transaction Processing 135-136

5 Module-5 137-149

5.1. Introduction to EJB 137


5.2. The Enterprise JavaBeans (EJB) 137-138
5.3. Server-Side Component Types (or) (Types of EJB’s) 138-140
5.4. Stateless session bean 140-142
5.5. Statefull Session Bean 142-144

5.6. Singleton session bean 144

5.7. Message Driven Bean 145-147

5.8. EJB and Persistence or (Entity Bean) 147-149


5.9. Container services 149

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page 9


Module-1

1.1 Introduction to Web


In the Web there are billions of clients and server connected through wires and wireless networks.
The web clients make requests to web server. The web server receives the request, finds the resources
and return the response to the client. When a server answers a request, it usually sends some type of
content to the client. The client uses web browser to send request to the server. The server often sends
response to the browser with a set of instructions written in HTML(HyperText Markup Language).
All browsers know how to display HTML page to the client.

What is a Server?
✓ A server is a computer that responds to requests from a client
✓ A server is also the software that responds to these requests; a client could be the browser or
other software making these requests
Web Terminology:

Terminology Description

Website: static vs It is a collection of related web pages that may contain text,
dynamic images, audio and video.

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page 10


HTTP It is the data communication protocol used to establish
communication between client and server.

HTTP Requests It is the request send by the computer to a web server that contains
all sorts of potentially interesting information.

Get vs Post It gives the difference between GET and POST request.

Container It is used in java for dynamically generate the web pages on the
server side.

Server: Web vs It is used to manage the network resources and for running the
Application program or software that provides services.

Content Type It is HTTP header that provides the description about what are you
sending to the browser.

Website

Website is a collection of related web pages that may contain text, images, audio and video. Each
website has specific internet address (URL) that you need to enter in your browser to access a
website.

A website can be of two types:


1. Static Website
2. Dynamic Website

Static website

The codes are fixed for each page so the information contained in the page does not change and it
looks like a printed page. There is no changes in the content of the page i.e. no dynamic behaviours.

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page 11


Dynamic website

Dynamic website is a collection of dynamic web pages whose content changes dynamically. It
accesses content from a database. Therefore, when we alter or update the content of the database, the
content of the website is also altered or updated.
Dynamic website uses client-side scripting or server-side scripting, or both to generate dynamic
content.
Client side scripting generates content at the client computer on the basis of user input. The web
browser downloads the web page from the server and processes the code within the page to render
information to the user.
In server side scripting, the software runs on the server and processing is completed in the server then
plain pages are sent to the user.

Static vs Dynamic website

Static Website Dynamic Website

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page 12


Prebuilt content is same every Content is generated quickly and changes regularly.
time the page is loaded.

It uses the HTML code for It uses the server side languages such
developing a website. asPHP,SERVLET, JSP, or ASP.NET etc. for
developing a website.

It sends exactly the same It may generate different response for each request.
response for every request.

HTTP (Hypertext Transfer Protocol)

• HTTP is a protocol that clients and servers use on the web to communicate.
• It is similar to other internet protocols such as SMTP(Simple Mail Transfer Protocol) and
FTP(File Transfer Protocol) but there is one fundamental difference.
• HTTP is a stateless protocol i.e HTTP supports only one request per connection. This means that
with HTTP the clients connect to the server to send one request and then disconnects. This
mechanism allows more users to connect to a given server over a period of time.
• The client sends an HTTP request and the server answers with an HTML page to the client, using
HTTP.

HTTP Methods
HTTP request can be made using a variety of methods, but the ones you will use most often are Get
and Post. The method name tells the server the kind of request that is being made, and how the rest of
the message will be formatted.

The HTTP request methods are:

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page 13


HTTP Description
Request

GET Asks to get the resource at the requested URL.

POST Asks the server to accept the body info attached. It is like GET request with
extra info sent with the request.

HEAD Asks for only the header part of whatever a GET would return. Just like GET
but with no body.

TRACE Asks for the loopback of the request message, for testing or troubleshooting.

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

Difference between GET and POST requests:

GET Request POST Request

Data is sent in header to the server Data is sent in the request body

Get request can send only limited amount Large amount of data can be sent.
of data

Get request is not secured because data is Post request is secured because data is not
exposed in URL exposed in URL.

Get request can be bookmarked and is more Post request cannot be bookmarked.
efficient.

Anatomy of Get Request:

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

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page 14


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's see what information is sent to the server.

Anatomy of Post Request

The query string (name/value pairs) is sent in HTTP message body for a POST request:
As we know, in case of post request original data is sent in message body.
Example of post request:

What Web Application Development involves.


✓ Web application development involves development of Dynamic HTML applications that can
interact with database
✓ In the development of web based applications the interaction of Web application works on
this way

Client CGI/Servlets SERVER


Browser

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page 15


1.2. Introduction to CGI
✓ CGI (Common gateway interface) written in pearl language which acts as an interface
between client and server to deal with request and response
✓ CGI allowed the separate process to read data from the HTTP request and write data to the
HTTP response.
✓ JOBS of CGI and SERVLET
✓ Explicit, implicit data sent by client to server is processed and another explicit , implicit data
is returned
✓ Explicit data : information received from client GUI ex: username , password
✓ Implicit data : HTTP information that is generated by the client (browser) rather than user.
✓ Http information contains data about request such as cookies, media types, and compression
scheme.

How Does CGI works? Why use Servlet when CGI is available?
✓ In CGI every time a request is made a new process starts
✓ Ex: let say 100 instances of an application require CGI program to process their request
simultaneously, the CGI program must be loaded 100 times in memory. (100 copies are made)
✓ It Degrades the performance as the instance increases
✓ Once CGI program terminates all the data used by the process is lost and cannot be used by
other programs

Working mechanism of CGI(Commmon Gateway Interface):

✓ CGI technology enables the web server to call an external program and pass HTTP request
information to the external program to process the request. For each request, it starts a new
process.

Disadvantages of CGI
1. If number of clients increases, it takes more time for sending response.
2. For each request, it starts a process and Web server is limited to start processes.
3. It uses platform dependent language e.g. C, C++, perl.

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page 16


What makes Servlet better?
✓ Java Servlet technology avoids drawbacks of CGI,
✓ First only one copy is loaded in JVM no matter the number of simultaneous requests made.
✓ Each request begins a thread to the java servlet rather than a new process. This saves memory
and increases response time.
✓ It is persistent:java servlet remains alive after the request is fulfilled. And data used by
servlet can be retained and can be used for business requirement of J2EE applications.

Advantage of Servlet:

✓ There are many advantages of servlet over CGI. The web container creates threads for
handling the multiple requests to the servlet. Threads have a lot of benefits over the Processes
such as they share a common memory area, lightweight, cost of communication between the
threads are low.

Benefits of servlet are as follows:

1. Better performance: because it creates a thread for each request not process.
2. Portability: because it uses java language.
3. Robust: Servlets are managed by JVM so we don't need to worry about memory leak,
garbage collection etc.
4. Secure: because it uses java language.

1.3. Introduction to Servlets.

“Servlet technology is used to create web application (resides at server side and generates
dynamic web page)”.

✓ A servlet is a Java program that runs within a Web server.


✓ Servlets receive and respond to requests from Web clients, usually across HTTP, the Hyper
Text Transfer Protocol.
✓ Servlet is an opposite of applet as a server-side applet.
✓ Applet is an application running on client while servlet is running on server.
Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page 17
✓ Servlets are server side components that provide a powerful mechanism for developing web
applications.
✓ Using servlets we can create fast and efficient server side applications and can run it on any
servlet enabled web server.
✓ Servlet runs entirely inside the JVM (Java Virtual Machine).
✓ It is multithreaded
✓ Executed by Webserver
Ex: Tomcat, Glassfish, JBoss, IBM Websphere etc.
✓ Since the servlet runs on server side so it does not depend on browser compatibility
✓ Runs on Webbrowser
Ex: Mozilla Firefox, Internet Explorer, Netscape, Google Chrome etc.
✓ The content of the dynamic web pages need to be generated dynamically.
✓ In the early days of the Web, a server could dynamically construct a page by creating a
separate process to handle each client request.
✓ The process would open connections to one or more databases in order to obtain the necessary
information.
✓ It communicated with the Web server via an interface known as the Common Gateway
Interface (CGI).

Servlet Working Process: / How a Servlet Application works?


Servlet Technology is used to create web applications. Servlet technology uses Java language to
create web applications.

Web applications are helper applications that resides at web server and build dynamic web pages. A
dynamic page could be anything like a page that randomly chooses picture to display or even a page
that displays the current time.

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page 18


✓ Web container is responsible for managing execution of servlets and JSP pages for Java EE
application.
✓ When a request comes in for a servlet, the server hands the request to the Web
Container. Web Container is responsible for instantiating the servlet or creating a new thread
to handle the request. Its the job of Web Container to get the request and response to the
servlet. The container creates multiple threads to process multiple requests to a single servlet.
✓ Servlets don't have a main() method. Web Container manages the life cycle of a Servlet
instance.

1. User sends request for a servlet by clicking a link that has URL to a servlet.

2. The container finds the servlet using deployment descriptor and creates two objects :
a. HttpServletRequest
b. HttpServletResponse

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page 19


3. Then the container creates or allocates a thread for that request and calls the
Servlet's service()method and passes the request, response objects as arguments.

4. The service() method, then decides which servlet method, doGet() or doPost() to call, based
on HTTP Request Method(Get, Post etc) sent by the client. Suppose the client sent an HTTP
GET request, so the service() will call Servlet's doGet() method.

5. Then the Servlet uses response object to write the response back to the client.
Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page 20
6. After the service() method is completed the thread dies. And the request and response
objects are ready for garbage collection.

Servlets Architecture: Following diagram shows the position of Servlets in a Web


Application.

1.4. Servlet Life Cycle

The web container maintains the life cycle of a servlet instance.Life cycle of the servlet involves
following steps:

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page 21


1. Servlet class is loaded.
2. Servlet instance is created.
3. Init() method is invoked.
4. Service() method is invoked.
5. Destroy() method is invoked.

As displayed in the above diagram, there are three states of a servlet: new, ready and end. The
servlet is in new state if servlet instance is created. After invoking the init() method, Servlet
comes in the ready state. In the ready state, servlet performs all the tasks. When the web
container invokes the destroy() method, it shifts to the end state.

1) Servlet class is loaded

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) Servlet instance is created

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) init(-) method is invoked

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page 22


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. Syntax of the init method is given below:
public void init(ServletConfig config) throws ServletException

4) service(-,-) method is invoked

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.
The syntax of the service method of the Servlet interface is given below:

public void service(ServletRequest request, ServletResponse response) throws ServletExcepti


on, IOException

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. The syntax
of the destroy method of the Servlet interface is given below:

public void destroy()


Syntax / Example:
import javax.servlet.Servlet;

public interface Servlet {


void init(ServletConfig config) throws ServletException;
void service(ServletRequest req, ServletResponse res) throws
ServletException, java.io.IOException;
void destroy();
}

Procedure:
✓ First, user enters URL, browser then generates an HTTP request for this URL, & this request is
then sent to the appropriate server.
✓ Second, this HTTP request is received by web server, web server maps this request to a particular
servlet.
✓ The servlet is dynamically retrieved & loaded into the address space of the server.
✓ Third, server invokes init( ) method of the servlet. This method is invoked only when the servlet
is first loaded into memory.
✓ It is possible to pass initialization parameters to the servlet so it may configure itself.
✓ Fourth, the server invokes the service ( ) method of the servlet. This method is called to process
the HTTP request. It may also formulate an HTTP response for the client.
Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page 23
✓ The service( ) method is called for each HTTP request.
✓ Finally, the server may decide to unload the servlet from its memory. The server calls the destroy(
) method to relinquish any resources such as file handles that are allocated for the servlet .

1.5. The Servlet API (Servlet Packaging) and Creating Servlet


Packages Description
javax.servlet The javax.servlet package contains a number
of classes and interfaces that describe and
define the contracts between a servlet class and
the runtime environment provided for an
instance of such a class by a conforming
servlet container.
javax.servlet.http The javax.servlet.http package contains a
number of classes and interfaces that describe
and define the contracts between a servlet class
running under the HTTP protocol and the
runtime environment provided for an instance
of such a class by a conforming servlet
container.

There are three different ways to create a servlet.

1. By implementing Servlet interface


2. By extending GenericServlet class
3. By extending HttpServlet class

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page 24


1.By implementing Servlet interface :

Servlet interface provides common behaviour to all the servlets.

Servlet interface needs to be implemented for creating any servlet (either directly or indirectly). It
provides 3 life cycle methods that are used to initialize the servlet, to service the requests, and to
destroy the servlet and 2 non-life cycle methods.

Methods of Servlet interface:


Method Description

public void init(ServletConfig config) initializes the servlet. It is the life cycle method of
servlet and invoked by the web container only
once.

public void service(ServletRequest provides response for the incoming request. It is


request,ServletResponse response) invoked at each request by the web container.

public void destroy() is invoked only once and indicates that servlet is
being destroyed.

public ServletConfig getServletConfig() returns the object of ServletConfig.

public String getServletInfo() returns information about servlet such as writer,


copyright, version etc.

Servlet Example by implementing Servlet interface:


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

public class First implements Servlet{


ServletConfig config=null;

public void init(ServletConfig config){


this.config=config;
System.out.println("servlet is initialized");
}

public void service(ServletRequest req,ServletResponse res)


throws IOException,ServletException{

res.setContentType("text/html");

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page 25


PrintWriter out=res.getWriter();
out.print("<html><body>");
out.print("<b>hello simple servlet</b>");
out.print("</body></html>");

}
public void destroy(){System.out.println("servlet is destroyed");}
public ServletConfig getServletConfig(){return config;}
public String getServletInfo(){return "copyright 2007-1010";}

2.By extending GenericServlet class :


✓ GenericServletclass implements Servlet, ServletConfig and Serializable interfaces. It
provides the implementation of all the methods of these interfaces except the service method.
✓ “GenericServlet class can handle any type of request so it is protocol-independent”.
✓ You may create a generic servlet by inheriting the GenericServlet class and providing the
implementation of the service method.

Methods of GenericServlet class:


1. public void init(ServletConfig config) is used to initialize the servlet.
2. public abstract void service(ServletRequest request, ServletResponse response)provides
service for the incoming request. It is invoked at each time when user requests for a servlet.
3. public void destroy() is invoked only once throughout the life cycle and indicates that servlet
is being destroyed.
4. public ServletConfig getServletConfig() returns the object of ServletConfig.
5. public String getServletInfo() returns information about servlet such as writer, copyright,
version etc.
6. public void init() it is a convenient method for the servlet programmers, now there is no need
to call super.init(config)
7. public ServletContext getServletContext() returns the object of ServletContext.
8. public String getInitParameter(String name) returns the parameter value for the given
parameter name.
9. public Enumeration getInitParameterNames() returns all the parameters defined in the
web.xml file.
10. public String getServletName() returns the name of the servlet object.
11. public void log(String msg) writes the given message in the servlet log file.
12. public void log(String msg,Throwable t) writes the explanatory message in the servlet log
file and a stack trace.

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page 26


Servlet Example by inheriting the GenericServlet class:
import java.io.*;
import javax.servlet.*;

public class First extends GenericServlet{


public void service(ServletRequest req,ServletResponse res)
throws IOException,ServletException{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
out.print("<html><body>");
out.print("<b>hello generic servlet</b>");
out.print("</body></html>");

}
}
3.By extending HttpServlet class:
The HttpServlet class extends the GenericServlet class and implements Serializable interface. It
provides http specific methods such as doGet, doPost, doHead, doTrace etc.

Methods of HttpServlet class:

There are many methods in HttpServlet class. They are as follows:

1. public void service(ServletRequest req,ServletResponse res) dispatches the request to the


protected service method by converting the request and response object into http type.
2. protected void service(HttpServletRequest req, HttpServletResponse res) receives the
request from the service method, and dispatches the request to the doXXX() method
depending on the incoming http request type.
3. protected void doGet(HttpServletRequest req, HttpServletResponse res) handles the GET
request. It is invoked by the web container.
4. protected void doPost(HttpServletRequest req, HttpServletResponse res) handles the
POST request. It is invoked by the web container.
5. protected void doHead(HttpServletRequest req, HttpServletResponse res) handles the
HEAD request. It is invoked by the web container.
6. protected void doOptions(HttpServletRequest req, HttpServletResponse res) handles the
OPTIONS request. It is invoked by the web container.
7. protected void doPut(HttpServletRequest req, HttpServletResponse res) handles the PUT
request. It is invoked by the web container.
8. protected void doTrace(HttpServletRequest req, HttpServletResponse res) handles the
TRACE request. It is invoked by the web container.

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page 27


9. protected void doDelete(HttpServletRequest req, HttpServletResponse res) handles the
DELETE request. It is invoked by the web container.
10. protected long getLastModified(HttpServletRequest req) returns the time when
HttpServletRequest was last modified since midnight January 1, 1970 GMT.

Example: For extending HttpServlet class

import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;
public class DemoServlet extends HttpServlet{
public void doGet(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException
{
res.setContentType("text/html");//setting the content type
PrintWriter pw=res.getWriter();//get the stream to write the data

//writing html in the stream


pw.println("<html><body>");
pw.println("Welcome to servlet");
pw.println("</body></html>");

pw.close();//closing the stream


}}

Interfaces & classes in javax.servlet package:

Interfaces Classes
1. Servlet 1. GenericServlet
2. ServletRequest 2. ServletInputStream
3. ServletResponse 3. ServletOutputStream
4. RequestDispatcher 4. ServletRequestWrapper
5. ServletConfig 5. ServletResponseWrapper
6. ServletContext 6. ServletRequestEvent
7. SingleThreadModel 7. ServletContextEvent
8. Filter 8. ServletRequestAttributeEvent
9. FilterConfig 9. ServletContextAttributeEvent
10. FilterChain 10. ServletException

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page 28


11. ServletRequestListener 11. UnavailableException
12. ServletRequestAttributeListener
13. ServletContextListener
14. ServletContextAttributeListener

✓ Interfaces & classes in javax.servlet.Http package:

Interfaces Classes
1. HttpServletRequest 1. HttpServlet
2. HttpServletResponse 2. Cookie
3. HttpSession 3. HttpServletRequestWrapper
4. HttpSessionListener 4. HttpServletResponseWrapper
5. HttpSessionAttributeListener 5. HttpSessionEvent
6. HttpSessionBindingListener 6. HttpSessionBindingEvent
7. HttpSessionActivationListener 7. HttpUtils (deprecated now)
8. HttpSessionContext (deprecated
now)

1.6. Servlets - Form Data


You must have come across many situations when you need to pass some information from your
browser to web server and ultimately to your backend program. The browser uses two methods to
pass this information to web server. These methods are GET Method and POST Method.

GET Method :
✓ The GET method sends the encoded user information appended to the page request. The page
and the encoded information are separated by the ?(question mark) symbol as follows –

http://www.test.com/hello?key1 = value1&key2 = value2

✓ The GET method is the default method to pass information from browser to web server and it
produces a long string that appears in your browser's Location:box. Never use the GET
method if you have password or other sensitive information to pass to the server. The GET
method has size limitation: only 1024 characters can be used in a request string.

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page 29


✓ This information is passed using QUERY_STRING header and will be accessible through
QUERY_STRING environment variable and Servlet handles this type of requests
using doGet() method.

Anatomy of Get Request:

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

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's see what information is sent to the server.

POST Method :
✓ A generally more reliable method of passing information to a backend program is the POST
method. This packages the information in exactly the same way as GET method, but instead
of sending it as a text string after a ? (question mark) in the URL it sends it as a separate
message. This message comes to the backend program in the form of the standard input
which you can parse and use for your processing. Servlet handles this type of requests
using doPost() method.

Anatomy of Post Request

The query string (name/value pairs) is sent in HTTP message body for a POST request.As we know,
in case of post request original data is sent in message body.

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page 30


Difference between GET and POST requests:

GET Request POST Request

Data is sent in header to the server Data is sent in the request body

Get request can send only limited amount Large amount of data can be sent.
of data

Get request is not secured because data is Post request is secured because data is not
exposed in URL exposed in URL.

Get request can be bookmarked and is Post request cannot be bookmarked.


more efficient.

Reading Form Data using Servlet :


Servlets handles form data parsing automatically using the following methods depending on the
situation −
• getParameter() − You call request.getParameter() method to get the value of a form
parameter.
• getParameterValues() − Call this method if the parameter appears more than once and
returns multiple values, for example checkbox.
• getParameterNames() − Call this method if you want a complete list of all parameters in the
current request.

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page 31


Example: Get method:
P1.html:
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form method="GET" action="p2">
Name:<input type="text" name="t1"><br></br>
Password:<input type="password" name="t2"><br></br>
Male:<input type="radio" name="r1" value="male"><br></br>
Female:<input type="radio" name="r1" value="male"><br></br>
Hobbies:<br></br>
Listening Music<input type="checkbox" name="c1" value="music"><br></br>
Sports<input type="checkbox" name="c1" value="sports"><br></br>
Reading books<input type="checkbox" name="c1" value="reading books"><br></br>

Branch:<select name="dd1">
<option value="MCA">MCA</option>
<option value="MBA">MBA</option>
<option value="CS">CS</option>
</select>
<br></br>
Interested Fruit:<select multiple name="dd2">
<option value="Apple">Apple</option>
<option value="Mango">Mango</option>
<option value="Orange">Orange</option>
</select>
<br></br>
<input type="submit" name="btn" value="Save">

</form>
</body>
</html>
Servlet Programme: p2.java (doGet method):

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page 32


public class p2 extends HttpServlet {

protected void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet p2</title>");
out.println("</head>");
out.println("<body>");
String name=request.getParameter("t1");
out.println("name="+name);
String password=request.getParameter("t2");
out.println("password="+password);
String gender=request.getParameter("r1");
out.println("gender="+gender);
String hobbies[]=request.getParameterValues("c1");
for(String s:hobbies)
{
out.println("your hobbbies:"+s);
}
String branch=request.getParameter("dd1");
out.println("branch="+branch);
String fruits[]=request.getParameterValues("dd2");
for(String s:fruits)
{
out.println("Fruits selected:"+s);
}
out.println("<br></br>");
Enumeration<String> e=request.getParameterNames();
while(e.hasMoreElements())
{
out.println("Parameternames:"+e.nextElement());
}
out.println("</body>");
out.println("</html>");
}
}

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page 33


Example: Servlet Programme: p3.java (doPost method): (Change the method=”POST” in the
p1.html file)
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class p2 extends HttpServlet {

protected void doPost(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet p2</title>");
out.println("</head>");
out.println("<body>");
String name=request.getParameter("t1");
out.println("name="+name);
String password=request.getParameter("t2");
out.println("password="+password);
String gender=request.getParameter("r1");
out.println("gender="+gender);
String hobbies[]=request.getParameterValues("c1");
for(String s:hobbies)
{
out.println("your hobbbies:"+s);
}
String branch=request.getParameter("dd1");
out.println("branch="+branch);
String fruits[]=request.getParameterValues("dd2");
for(String s:fruits)
{
out.println("Fruits selected:"+s);
}
out.println("<br></br>");
Enumeration<String> e=request.getParameterNames();

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page 34


while(e.hasMoreElements())
{
out.println("Parameternames:"+e.nextElement());
}
out.println("</body>");
out.println("</html>");
}
}
}
1.7. Servlets - Client HTTP Request
✓ When a browser requests for a web page, it sends lot of information to the web server which
cannot be read directly because this information travel as a part of header of HTTP request.
You can check HTTP Protocol for more information on this.
✓ Following is the important header information which comes from browser side and you
would use very frequently in web programming.

Sl.No. Header & Description

Accept
1
This header specifies the MIME types that the browser or other clients can handle. Values
of image/png or image/jpeg are the two most common possibilities.

Accept-Charset
2 This header specifies the character sets the browser can use to display the information. For
example ISO-8859-1.

Accept-Encoding
3 This header specifies the types of encodings that the browser knows how to handle. Values
of gzip or compress are the two most common possibilities.

Accept-Language
4 This header specifies the client's preferred languages in case the servlet can produce results
in more than one language. For example en, en-us, ru, etc

Authorization
5 This header is used by clients to identify themselves when accessing password-protected
Web pages.

6 Connection

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page 35


This header indicates whether the client can handle persistent HTTP connections. Persistent
connections permit the client or other browser to retrieve multiple files with a single
request. A value of Keep-Alivemeans that persistent connections should be used.

Content-Length
7 This header is applicable only to POST requests and gives the size of the POST data in
bytes.

Cookie
8
This header returns cookies to servers that previously sent them to the browser.

Host
9
This header specifies the host and port as given in the original URL.

If-Modified-Since
This header indicates that the client wants the page only if it has been changed after the
10
specified date. The server sends a code, 304 which means Not Modified header if no newer
result is available.

If-Unmodified-Since
11 This header is the reverse of If-Modified-Since; it specifies that the operation should
succeed only if the document is older than the specified date.

Referer
This header indicates the URL of the referring Web page. For example, if you are at Web
12
page 1 and click on a link to Web page 2, the URL of Web page 1 is included in the
Referrer header when the browser requests Web page 2.

User-Agent
13 This header identifies the browser or other client making the request and can be used to
return different content to different types of browsers.

✓ Methods to read HTTP Header:


Sr.No. Method & Description

1 Cookie[] getCookies()

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page 36


Returns an array containing all of the Cookie objects the client sent with this request.

Enumeration getHeaderNames()
2
Returns an enumeration of all the header names this request contains.

HttpSession getSession()
3 Returns the current session associated with this request, or if the request does not have
a session, creates one.

HttpSession getSession(boolean create)


4 Returns the current HttpSession associated with this request or, if if there is no current
session and value of create is true, returns a new session.

String getParameter(String name)


5 Returns the value of a request parameter as a String, or null if the parameter does not
exist.

String[] getParameterValues(String name)


6 Returns an array of String objects containing all of the values the given request
parameter has, or null if the parameter does not exist.

Enumeration getParameterNames()
7 Returns an Enumeration of String objects containing the names of the parameters
contained in this request

String getMethod()
8 Returns the name of the HTTP method with which this request was made, for example,
GET, POST, or PUT.

String getContextPath()

9 Returns the portion of the request URI that indicates the context of the request.

int getServerPort()
10 Returns the port number on which this request was received.

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page 37


String getPathInfo()
11 Returns any extra path information associated with the URL the client sent when it
made this request

String getProtocol()
12 Returns the name and version of the protocol the request.

String getContentType()
13 Returns the MIME type of the body of the request, or null if the type is not known.

HTTP Header Request Example


✓ Following is the example which uses getHeaderNames()method of HttpServletRequest to
read the HTTP header information. This method returns an Enumeration that contains the
header information associated with the current HTTP request.
✓ Once we have an Enumeration, we can loop down the Enumeration in the standard manner,
using hasMoreElements() method to determine when to stop and
using nextElement()method to get each parameter name

//Import required java libraries


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

// Extend HttpServlet class


public class DisplayHeader extends HttpServlet {

// Method to handle GET method request.


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

// Set response content type


response.setContentType("text/html");

PrintWriter out = response.getWriter();


String title = "HTTP Header Request Example";
String docType =
"<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n";

out.println(docType +
"<html>\n" +

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page 38


"<head><title>" + title + "</title></head>\n"+
"<body bgcolor = \"#f0f0f0\">\n" +
"<h1 align = \"center\">" + title + "</h1>\n" +
"<table width = \"100%\" border = \"1\" align = \"center\">\n" +
"<tr bgcolor = \"#949494\">\n" +
"<th>Header Name</th><th>Header Value(s)</th>\n"+
"</tr>\n"
);

Enumeration headerNames = request.getHeaderNames();

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

// Method to handle POST method request.


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

doGet(request, response);
}
}

OutPut: HTTP Header Request Example

Header Name Header Value(s)

accept */*

accept-language en-us

user-agent Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0;


InfoPath.2; MS-RTC LM 8)

accept-encoding gzip, deflate

host localhost:8080

connection Keep-Alive

cache-control no-cache

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page 39


1.8.Servlets - Server HTTP Response
When a Web server responds to an HTTP request, the response typically consists of a status line,
some response headers, a blank line, and the document. A typical response looks like this −

HTTP/1.1 200 OK
Content-Type: text/html
Header2: ...
...
HeaderN: ...
(Blank Line)
<!doctype ...>
<html>
<head>...</head>
<body>
...
</body>
</html>
✓ The status line consists of the HTTP version (HTTP/1.1 in the example), a status code (200 in
the example), and a very short message corresponding to the status code (OK in the example).
✓ Following is a summary of the most useful HTTP 1.1 response headers which go back to the
browser from web server side and you would use them very frequently in web programming.
HTTP Response Headers:

Sr.No. Header & Description

Allow
1
This header specifies the request methods (GET, POST, etc.) that the server supports.

Cache-Control
This header specifies the circumstances in which the response document can safely be cached.
2 It can have values public, privateor no-cache etc. Public means document is cacheable,
Private means document is for a single user and can only be stored in private (non-shared)
caches and nocache means document should never be cached.

Connection
This header instructs the browser whether to use persistent in HTTP connections or not. A
3
value of close instructs the browser not to use persistent HTTP connections
and keepalive means using persistent connections.

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page 40


Content-Disposition
4 This header lets you request that the browser ask the user to save the response to disk in a file
of the given name.

Content-Encoding
5
This header specifies the way in which the page was encoded during transmission.

Content-Language
6 This header signifies the language in which the document is written. For example en, en-us,
ru, etc

Content-Length
7 This header indicates the number of bytes in the response. This information is needed only if
the browser is using a persistent (keep-alive) HTTP connection.

Content-Type
8 This header gives the MIME (Multipurpose Internet Mail Extension) type of the response
document.

Expires
9 This header specifies the time at which the content should be considered out-of-date and thus
no longer be cached.

Last-Modified

10 This header indicates when the document was last changed. The client can then cache the
document and supply a date by an If-Modified-Since request header in later requests.

Location
This header should be included with all responses that have a status code in the 300s. This
11 notifies the browser of the document address. The browser automatically reconnects to this
location and retrieves the new document.

Refresh

12 This header specifies how soon the browser should ask for an updated page. You can specify
time in number of seconds after which a page would be refreshed.

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page 41


Retry-After
13 This header can be used in conjunction with a 503 (Service Unavailable) response to tell the
client how soon it can repeat its request.

Set-Cookie
14
This header specifies a cookie associated with the page.

✓ Methods to Set HTTP Response Header:


There are following methods which can be used to set HTTP response header in your servlet
program. These methods are available with HttpServletResponse object.

Sr.No. Method & Description

String encodeRedirectURL(String url)


1 Encodes the specified URL for use in the sendRedirect method or, if encoding is not
needed, returns the URL unchanged.

String encodeURL(String url)


2 Encodes the specified URL by including the session ID in it, or, if encoding is not
needed, returns the URL unchanged.

boolean containsHeader(String name)


3
Returns a Boolean indicating whether the named response header has already been set.

boolean isCommitted()
4
Returns a Boolean indicating if the response has been committed.

void addCookie(Cookie cookie)


5
Adds the specified cookie to the response.

void addDateHeader(String name, long date)


6
Adds a response header with the given name and date-value.

void addHeader(String name, String value)


7
Adds a response header with the given name and value.

void addIntHeader(String name, int value)


8
Adds a response header with the given name and integer value.

void flushBuffer()
9
Forces any content in the buffer to be written to the client.

void reset()
10
Clears any data that exists in the buffer as well as the status code and headers.

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page 42


void resetBuffer()
11 Clears the content of the underlying buffer in the response without clearing headers or
status code.

void sendError(int sc)


12 Sends an error response to the client using the specified status code and clearing the
buffer.

void sendError(int sc, String msg)


13 Sends an error response to the client using the specified status.

void sendRedirect(String location)


14 Sends a temporary redirect response to the client using the specified redirect location
URL.

void setBufferSize(int size)


15 Sets the preferred buffer size for the body of the response.

void setCharacterEncoding(String charset)


16 Sets the character encoding (MIME charset) of the response being sent to the client, for
example, to UTF-8.

void setContentLength(int len)


17 Sets the length of the content body in the response In HTTP servlets, this method sets the
HTTP Content-Length header.

void setContentType(String type)


Sets the content type of the response being sent to the client, if the response has not been
18
committed yet.

void setDateHeader(String name, long date)


19 Sets a response header with the given name and date-value.

void setHeader(String name, String value)


20 Sets a response header with the given name and value.

void setIntHeader(String name, int value)


21 Sets a response header with the given name and integer value

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page 43


void setLocale(Locale loc)
22 Sets the locale of the response, if the response has not been committed yet.

void setStatus(int sc)


23
Sets the status code for this response

1.9. Servlets - Http Status Codes:


The format of the HTTP request and HTTP response messages are similar and will have following
structure.

Example, a server response header looks as follows −

HTTP/1.1 200 OK
Content-Type: text/html
Header2: ...
...
HeaderN: ...
(Blank Line)
<!doctype ...>
<html>
<head>...</head>
<body>
...
</body>
</html>
The status line consists of the HTTP version (HTTP/1.1 in the example), a status code (200 in the
example), and a very short message corresponding to the status code (OK in the example).
Following is a list of HTTP status codes and associated messages that might be returned from the
Web Server –

Code Message Description

Only a part of the request has been received by the server, but as long as it
100 Continue
has not been rejected, the client should continue with the request

200 OK The request is OK

201 Created The request is complete, and a new resource is created

202 Accepted The request is accepted for processing, but the processing is not complete.

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page 44


400 Bad Request The server did not understand the request

401 Unauthorized The requested page needs a username and a password

403 Forbidden Access is forbidden to the requested page

404 Not Found The server cannot find the requested page.

Unsupported The server will not accept the request, because the media type is not
415
Media Type supported.

Internal Server The request was not completed. The server met an unexpected condition.
500
Error

Service The request was not completed. The server is temporarily overloading or
503
Unavailable down.

504 Gateway Timeout The gateway has timed out.

✓ Methods to Set HTTP Status Code:


The following methods can be used to set HTTP Status Code in your servlet program. These
methods are available with HttpServletResponse object.

Sl.No. Method & Description

public void setStatus ( int statusCode )


This method sets an arbitrary status code. The setStatus method takes an int (the status
1 code) as an argument. If your response includes a special status code and a document,
be sure to call setStatus before actually returning any of the content with
the PrintWriter.

public void sendRedirect(String url)


2 This method generates a 302 response along with a Locationheader giving the URL of
the new document

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page 45


public void sendError(int code, String message)
This method sends a status code (usually 404) along with a short message that is
automatically formatted inside an HTML document and sent to the client.
3
Example: // Set error code and reason.
response.sendError(407, "Need authentication!!!" );

1.10. Servlet Request


True job of a Servlet is to handle client request. Servlet API provides two important
interfaces javax.servlet.ServletRequest and javax.servlet.http.HttpServletRequest to encapsulate
client request. Implementation of these interfaces provide important information about client request
to a servlet.
Some Important Methods of ServletRequest

Methods Description

Object getAttribute(String name) return attribute set on request object by name

Enumeration getAttributeName() return an Enumeration containing the names of the


attributes available inthis request

int getContentLength() return size of request body

int getContentType() return media type of request content

ServletInputStream getInputStream() returns a input stream for reading binary data

String getParameter(String name) returns value of parameter by name

String getLocalAddr() returns the Internet Protocol(IP) address of the


interface on which the request was received

Enumeration getParameterNames() returns an enumeration of all parameter names

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page 46


String[] getParameterValues(String returns an array of String objects containing all of the
name) values the given request parameter has, or null if the
parameter does not exist

ServletContext getServletContext() return the servlet context of current request.

String getServerName() returns the host name of the server to which the
request was sent

int getServerPort() returns the port number to which the request was sent

boolean isSecure() returns a boolean indicating whether this request was


made using a secure channel, such as HTTPS.

void removeAttribute(String name) removes an attribute from this request

void setAttribute(String name, Object stores an attribute in this request.


o)

✓ HttpServletRequest interface
HttpServletRequest interface adds the methods that relates to the HTTP protocol.

Some important methods of HttpServletRequest

Methods Description

String getContextPath() returns the portion of the request URI that indicates the
context of the request

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page 47


Cookies getCookies() returns an array containing all of the Cookie objects the
client sent with this request

String getQueryString() returns the query string that is contained in the request
URL after the path

HttpSession getSession() returns the current HttpSession associated with this request
or, if there is no current session and create is true, returns a
new session

String getMethod() Returns the name of the HTTP method with which this
request was made, for example, GET, POST, or PUT.

Part getPart(String gets the Part with the given name


name)

String getPathInfo() returns any extra path information associated with the
URL the client sent when it made this request.

String getServletPath() returns the part of this request's URL that calls the servlet

Example demonstrating Servlet Request


In this example, we will show how a parameter is passed to a Servlet in a request object from HTML
page.
index.html
<form method="post" action="MyServlet">
Name <input type="text" name="user" >
<input type="submit" value="submit">
</form>
web.xml
<servlet>
<servlet-name>MyServlet</servlet-name>
<servlet-class>MyServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MyServlet</servlet-name>
<url-pattern>/MyServlet</url-pattern>
</servlet-mapping>
MyServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class MyServlet extends HttpServlet {

protected void doPost(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page 48


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

String user=request.getParameter("user");
out.println("<h2> Welcome "+user+"</h2>");
} finally {
out.close();
}
}
}

1.11. Servlet Response


Servlet API provides two important interfaces ServletResponse and HttpServletResponse to assist
in sending response to client.
Some Important Methods of ServletResponse

Methods Description

PrintWriter getWriter() returns a PrintWriter object that can send character text to
the client.

void setBufferSize(int size) Sets the preferred buffer size for the body of the response

void setContentLength(int Sets the length of the content body in the response In
len) HTTP servlets, this method sets the HTTP Content-Length
header

void setContentType(String sets the content type of the response being sent to the
type) client before sending the respond.

void setBufferSize(int size) sets the preferred buffer size for the body of the response.

boolean isCommitted() returns a boolean indicating if the response has been


committed

void setLocale(Locale loc) sets the locale of the response, if the response has not been
committed yet.

HttpServletResponse Interface
HttpServletResponse interface adds the methods that relates to the HTTP response.

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page 49


Some Important Methods of HttpServletResponse

Methods Description

void addCookie(Cookie cookie) adds the specified cookie to the response.

void sendRedirect(String Sends a temporary redirect response to the client using the
location) specified redirect location URL and clears the buffer

int getStatus() gets the current status code of this response

String getHeader(String name) gets the value of the response header with the given name.

void setHeader(String name, sets a response header with the given name and value
String value)

void setStatus(int sc) sets the status code for this response

void sendError(int sc, String sends an error response to the client using the specified
msg) status and clears the buffer

1.12. Introduction to Request Dispatcher


RequestDispatcher is an interface, implementation of which defines an object which can dispatch
request to any resources(such as HTML, Image, JSP, Servlet) on the server.
Methods of RequestDispatcher
RequestDispatcher interface provides two important methods

Methods Description

void forward(ServletRequest request, forwards a request from a servlet to another


ServletResponse response) resource (servlet, JSP file, or HTML file) on the
server

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page 50


void include(ServletRequest request, includes the content of a resource (servlet, JSP
ServletResponse response) page, HTML file) in the response

How to get an Object of RequestDispatcher


getRequestDispatcher() method of ServletRequest returns the object of RequestDispatcher.
RequestDispatcher rs = request.getRequestDispatcher("hello.html");
rs.forward(request,response);

OR
RequestDispatcher rs = request.getRequestDispatcher("hello.html");
rs.include(request,response);

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page 51


forward() method:As you see in the above figure, response of second servlet is sent to the client.
Response of the first servlet is not displayed to the user.

include() method: As you can see in the above figure, response of second servlet is included in the
response of the first servlet that is being sent to the client.
Example demonstrating usage of RequestDispatcher
In this example, we will show you how RequestDispatcher is used to forward or include response of
a resource in a Servlet. Here we are using index.html to get username and password from the
user, Validate Servlet will validate the password entered by the user, if the user has entered
"studytonight" as password, then he will be forwarded to Welcome Servlet else the user will stay on
the index.html page and an error message will be displayed.

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page 52


Files to be created :

• index.html will have form fields to get user information.


• Validate.java will validate the data entered by the user.
• Welcome.java will be the welcome page.
• web.xml , the deployment descriptor.

index.html
<form method="post" action="Validate">
Name:<input type="text" name="user" /><br/>
Password:<input type="password" name="pass" ><br/>
<input type="submit" value="submit">
</form>
Validate.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class Validate extends HttpServlet {

protected void doPost(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
String name = request.getParameter("user");
String password = request.getParameter("pass");

if(password.equals("123") && name.equals(“rakesh”))

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page 53


{
RequestDispatcher rd = request.getRequestDispatcher("Welcome");
rd.forward(request, response);
}
else
{
out.println("<font color='red'><b>You have entered incorrect password</b></font>");
RequestDispatcher rd = request.getRequestDispatcher("index.html");
rd.include(request, response);
}
}finally {
out.close();
}

}
}
Welcome.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Welcome extends HttpServlet {

protected void doPost(HttpServletRequest request, HttpServletResponse response)


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

out.println("<h2>Welcome user</h2>");
} finally {
out.close();
}
}
}

web.xml
<web-app>
<servlet>
<servlet-name>Validate</servlet-name>
<servlet-class>Validate</servlet-class>
</servlet>
<servlet>
<servlet-name>Welcome</servlet-name>
<servlet-class>Welcome</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Validate</servlet-name>
<url-pattern>/Validate</url-pattern>
</servlet-mapping>
Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page 54
<servlet-mapping>
<servlet-name>Welcome</servlet-name>
<url-pattern>/Welcome</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>

1.13. sendRedirect() Method


sendRedirect() method redirects the response to another resource. This method actually makes the
client(browser) to create a new request to get to the resource. The client can see the new url in the
browser.
sendRedirect() accepts relative URL, so it can go for resources inside or outside the server.
Differences between sendRedirect() and Request Dispatcher:
✓ The main difference between a redirection and a request dispatching is that, redirection
makes the client(browser) create a new request to get to the resource, the user can see the new
URL while request dispatch get the resource in same request and URL does not changes.
✓ sendRedirect() works on response object while request dispatch work on request object.
Example demonstrating usage of sendRedirect():
Creating custom google search using sendRedirect
In this example, we are using sendRedirect method to send request to google server with the request
data.
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>sendRedirect example</title>
</head>
<body>
<form action="MySearcher">
<input type="text" name="name">
<input type="submit" value="Google Search">
</form>
</body>
</html>
MySearcher.java
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class MySearcher extends HttpServlet {


Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page 55
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

String name=request.getParameter("name");
response.sendRedirect("https://www.google.co.in/#q="+name);
}
}
Difference between forward() and sendRedirect() method
There are many differences between the forward() method of RequestDispatcher and sendRedirect()
method of HttpServletResponse interface. They are given below:

forward() method sendRedirect() method

The forward() method works at server side. The sendRedirect() method


works at client side.

It sends the same request and response objects to another It always sends a new request.
servlet.

It can work within the server only. It can be used within and
outside the server.

Example: Example:
request.getRequestDispacher("servlet2").forward(requ response.sendRedirect("servl
est,response); et2")

1.14. ServletConfig interface


When the Web Container initializes a servlet, it creates a ServletConfig object for the servlet.
ServletConfig object is used to pass information to a servlet during initialization by getting
configuration information from web.xml(Deployment Descriptor).
Methods of ServletConfig:

✓ String getInitParameter(String name): returns a String value initialized parameter, or NULL if


the parameter does not exist.
✓ Enumeration getInitParameterNames(): returns the names of the servlet's initialization
parameters as an Enumeration of String objects, or an empty Enumeration if the servlet has no
initialization parameters.
✓ ServletContext getServletContext(): returns a reference to the ServletContext
✓ String getServletName(): returns the name of the servlet instance

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page 56


How to Initialize a Servlet inside web.xml
Example demonstrating usage of ServletConfig
web.xml
<web-app...>
<servlet>
<servlet-name>MyServlet</servlet-name>
<servlet-class>MyServlet</servlet-class>
<init-param>
<param-name>email</param-name>
<param-value>[email protected] </param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>check</servlet-name>
<url-pattern>/check</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
MyServlet .java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class MyServlet extends HttpServlet {

protected void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {

response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
ServletConfig sc=getServletConfig();
out.println(sc.getInitParameter("email"));
}
}

1.15. ServletContext Interface


For every Web application a ServletContext object is created by the web container. ServletContext
object is used to get configuration information from Deployment Descriptor(web.xml) which will be
available to any servlet or JSPs that are part of the web app.
Some Important method of ServletContext

Methods Description

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page 57


Object getAttribute(String name) returns the container attribute with the given name,
or NULL if there is no attribute by that name.

String getInitParameter(String name) returns parameter value for the specified parameter
name, or NULL if the parameter does not exist

Enumeration getInitParameterNames() returns the names of the context's initialization


parameters as an Enumeration of String objects

void setAttribute(String name,Object set an object with the given attribute name in the
obj) application scope

void removeAttribute(String name) removes the attribute with the specified name from
the application context

How Context Parameter is Initialized inside web.xml

Advantages of ServletContext

• Provides communication between servlets


• Available to all servlets and JSPs that are part of the web app
• Used to get configuration information from web.xml

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page 58


Difference between Context Init Parameters and Servlet Init Parameter

Servlet Context Init parameters Servlet Init parameter/ServletConfig


Init parameters

Available to all servlets and JSPs that are part of web Available to only servlet for which the
<init-param> was configured

Context Init parameters are initialized within Initialized within the <servlet> for each
the <web-app> not within a specific servlet.
specific <servlet> elements

ServletContext object is used to get Context Init ServletConfig object is used to get Servlet
parameters Init parameters

Only one ServletContext object for entire web app Each servlet has its own ServletConfig
object

Example demonstrating usage of ServletContext


web.xml
<web-app ...>

<context-param>
<param-name>driverName</param-name>
<param-value>sun.jdbc.JdbcOdbcDriver</param-value>
</context-param>

<servlet>
<servlet-name> MyServlet </servlet-name>
<servlet-class>MyServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name> MyServlet </servlet-name>
<url-pattern>/MyServlet </url-pattern>
</servlet-mapping>

</web-app>
MyServlet class :
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class MyServlet extends HttpServlet {

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page 59


protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
ServletContext sc = getServletContext();
out.println(sc.getInitParameter("driverName"));
}
}

1.16. Introduction to Attributes


An attribute is an object that is used to share information in a web app. Attribute allows Servlets to
share information among themselves. Attributes can be SET and GET from one of the following
scopes :

1. request
2. session
3. application

How to SET an Attribute


public void setAttribute(String name, Object obj) method is used to SET an Attribute.
Example demonstrating Setting Attribute

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page 60


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

public class First extends HttpServlet {

protected void doPost(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
ServletContext sc = getServletContext();
sc.setAttribute("user","Abhi"); //setting attribute on context scope
}
}
How to GET an Attribute
Object getAttribute(String name) method is used to GET an attribute.
Example demonstrating getting a value of set Attribute
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class Second extends HttpServlet {

protected void doPost(HttpServletRequest request, HttpServletResponse response)


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

String str = sc.getAttribute("user"); //getting attribute from context scope

out.println("Welcome"+str); // Prints : Welcome Abhi


}
}

1.17. Managing Session in Servlets / Session Tracking in Servlets


We all know that HTTP is a stateless protocol. All requests and responses are independent. But
sometimes you need to keep track of client's activity across multiple requests. For eg. When a User
logs into your website, not matter on which web page he visits after logging in, his credentials will be
with the server, until he logs out. So this is managed by creating a session.
Session simply means a particular interval of time.
Session Tracking is a way to maintain state (data) of an user. It is also known as session
management in servlet.

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page 61


Http protocol is a stateless so we need to maintain state using session tracking techniques. Each time
user requests to the server, server treats the request as the new request. So we need to maintain the
state of an user to recognize to particular user.
HTTP is stateless that means each request is considered as the new request. It is shown in the figure
given below:

Session Management is a mechanism used by the Web container to store session information for a
particular user. There are four different techniques used by Servlet application for session
management. They are as follows:

1. Cookies
2. Hidden form field
3. URL Rewriting
4. HttpSession

Session is used to store everything that we can get from the client from all the requests the client
makes.

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page 62


How Session Works

The basic concept behind session is, whenever a user starts using our application, we can save a
unique identification information about him, in an object which is available throughout the
application, until its destroyed. So wherever the user goes, we will always have his information and
we can always manage which user is doing what. Whenever a user wants to exit from your
application, destroy the object with his information.

1. Cookies in Servlet

A cookie is a small piece of information that is persisted between the multiple client requests.

A cookie has a name, a single value, and optional attributes such as a comment, path and domain
qualifiers, a maximum age, and a version number.

How Cookie works


By default, each request is considered as a new request. In cookies technique, we add cookie with
response from the servlet. So cookie is stored in the cache of the browser. After that if request is sent
by the user, cookie is added with request by default. Thus, we recognize the user as the old user.

Types of Cookie
There are 2 types of cookies in servlets.
1. Non-persistent cookie
2. Persistent cookie

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page 63


Non-persistent cookie

It is valid for single session only. It is removed each time when user closes the browser.

Persistent cookie

It is valid for multiple session . It is not removed each time when user closes the browser. It is
removed only if user logout or signout.

Advantage of Cookies
1. Simplest technique of maintaining the state.
2. Cookies are maintained at client side.

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

Cookie class

javax.servlet.http.Cookie class provides the functionality of using cookies. It provides a lot of useful
methods for cookies.

Constructor of Cookie class

Constructor Description

Cookie() constructs a cookie.

Cookie(String name, String constructs a cookie with a specified name and


value) value.

Useful Methods of Cookie class

There are given some commonly used methods of the Cookie class.

Method Description

public void setMaxAge(int Sets the maximum age of the cookie in seconds.
expiry)

public String getName() Returns the name of the cookie. The name cannot be
changed after creation.

public String getValue() Returns the value of the cookie.

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page 64


public void setName(String changes the name of the cookie.
name)

public void setValue(String changes the value of the cookie.


value)

Other methods required for using Cookies

For adding cookie or getting the value from the cookie, we need some methods provided by other
interfaces. They are:
1. public void addCookie(Cookie ck):method of HttpServletResponse interface is used to
add cookie in response object.
2. public Cookie[] getCookies():method of HttpServletRequest interface is used to return all
the cookies from the browser.

How to create Cookie?

Let's see the simple code to create cookie.


Cookie ck=new Cookie("user","vinay");//creating cookie object
response.addCookie(ck);//adding cookie in the response

How to delete Cookie?

Let's see the simple code to delete cookie. It is mainly used to logout or signout the user.

Cookie ck=new Cookie("user","");//deleting value of cookie


ck.setMaxAge(0);//changing the maximum age to 0 seconds
response.addCookie(ck);//adding cookie in the response

How to get Cookies?

Let's see the simple code to get all the cookies.

Cookie ck[]=request.getCookies();
for(int i=0;i<ck.length;i++){
out.print("<br>"+ck[i].getName()+" "+ck[i].getValue());//printing name and value of c
ookie
}

Simple example of Servlet Cookies

In this example, we are storing the name of the user in the cookie object and accessing it in another
servlet. As we know well that session corresponds to the particular user. So if you access it from too
many browsers with different values, you will get the different value.

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page 65


index.html
<form action="FirstServlet" method="post">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>

FirstServlet.java

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

public class FirstServlet extends HttpServlet {

public void doPost(HttpServletRequest request, HttpServletResponse response){


try{

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

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

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


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

//creating submit button


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

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page 66


out.close();

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

SecondServlet.java

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

public class SecondServlet extends HttpServlet {

public void doPost(HttpServletRequest request, HttpServletResponse response){


try{

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

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

out.close();

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

}
web.xml
<web-app>

<servlet>
<servlet-name> FirstServlet </servlet-name>
<servlet-class>FirstServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name> FirstServlet </servlet-name>
<url-pattern>/ FirstServlet </url-pattern>
</servlet-mapping>

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

<servlet-mapping>
Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page 67
<servlet-name> SecondServlet </servlet-name>
<url-pattern> /SecondServlet </url-pattern>
</servlet-mapping>

</web-app>
2) Hidden Form Field
In case of Hidden Form Field a hidden (invisible) textfieldis 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.
Let's see the code to store value in hidden field.
<input type="hidden" name="uname" value="Vinay">
Here, uname is the hidden field name and Vinay is the hidden field value.

Real application of hidden form field

It is widely used in comment form of a website. In such case, we store page id or page name in the
hidden field so that each page can be uniquely identified.

Advantage of Hidden Form Field


1. It will always work whether cookie is disabled or not.
Disadvantage of Hidden Form Field:
1. It is maintained at server side.
2. Extra form submission is required on each pages.
3. Only textual information can be used.
Example of using Hidden Form Field

In this example, we are storing the name of the user in a hidden textfield and getting that value from
another servlet.

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page 68


index.html
<form action="FirstServlet">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>
FirstServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class FirstServlet extends HttpServlet {


public void doGet(HttpServletRequest request, HttpServletResponse response){
try{

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

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

//creating form that have invisible textfield


out.print("<form action='SecondServlet'>");
out.print("<input type='hidden' name='uname' value='"+n+"'>");
out.print("<input type='submit' value='go'>");
out.print("</form>");
out.close();

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

SecondServlet.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SecondServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();

//Getting the value from the hidden field


String n=request.getParameter("uname");
out.print("Hello "+n);

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page 69


out.close();
}catch(Exception e){System.out.println(e);}
}
}
web.xml
<web-app>

<servlet>
<servlet-name> FirstServlet </servlet-name>
<servlet-class>FirstServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name> FirstServlet </servlet-name>
<url-pattern>/ FirstServlet </url-pattern>
</servlet-mapping>

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

<servlet-mapping>
<servlet-name> SecondServlet </servlet-name>
<url-pattern> /SecondServlet </url-pattern>
</servlet-mapping>

</web-app>

3)URL Rewriting
In URL rewriting, we append a token or identifier to the URL of the next Servlet or the next resource.
We can send parameter name/value pairs using the following format:
url?name1=value1&name2=value2&??
A name and a value is separated using an equal = sign, a parameter name/value pair is separated from
another parameter using the ampersand(&). When the user clicks the hyperlink, the parameter
name/value pairs will be passed to the server. From a Servlet, we can use getParameter() method to
obtain a parameter value.

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page 70


Advantage of URL Rewriting

1. It will always work whether cookie is disabled or not (browser independent).


2. Extra form submission is not required on each pages.

Disadvantage of URL Rewriting

1. It will work only with links.


2. It can send Only textual information.

Example of using URL Rewriting


In this example, we are maintaning the state of the user using link. For this purpose, we are appending
the name of the user in the query string and getting the value from the query string in another page.
index.html
<form action="FirstServlet">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>

FirstServlet.java

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

public class FirstServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response){


try{

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page 71


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

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

//appending the username in the query string


out.print("<a href='servlet2?uname="+n+"'>visit</a>");

out.close();

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

public class SecondServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)


try{

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

//getting value from the query string


String n=request.getParameter("uname");
out.print("Hello "+n);

out.close();

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

}
web.xml
<web-app>
<servlet>
<servlet-name> FirstServlet </servlet-name>
<servlet-class>FirstServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name> FirstServlet </servlet-name>
<url-pattern>/ FirstServlet </url-pattern>

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page 72


</servlet-mapping>
<servlet>
<servlet-name> SecondServlet </servlet-name>
<servlet-class>SecondServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name> SecondServlet </servlet-name>
<url-pattern> /SecondServlet </url-pattern>
</servlet-mapping>

</web-app>

4.)HttpSession:
HttpSession object is used to store entire session with a specific client. We can store, retrieve and
remove attribute from HttpSession object. Any servlet can have access to HttpSession object
throughout the getSession() method of the HttpServletRequest object.
How HttpSession works

1. On client's first request, the Web Container generates a unique session ID and gives it back to the
client with response. This is a temporary session created by web container.
2. The client sends back the session ID with each request. Making it easier for the web container to
identify where the request is coming from.
3. The Web Container uses this ID, finds the matching session with the ID and associates the
session with the request.

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page 73


HttpSession Interface:

Some Important Methods of HttpSession

Methods Description

long getCreationTime() returns the time when the session was created,
measured in milliseconds since midnight January
1, 1970 GMT.

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page 74


String getId() returns a string containing the unique identifier
assigned to the session.

long getLastAccessedTime() returns the last time the client sent a request
associated with the session

int getMaxInactiveInterval() returns the maximum time interval, in seconds.

void invalidate() destroy the session

boolean isNew() returns true if the session is new else false

void setMaxInactiveInterval(int Specifies the time, in seconds,after servlet


interval) container will invalidate the session.

Example of using HttpSession

In this example, we are setting the attribute in the session scope in one servlet and getting that value
from the session scope in another servlet. To set the attribute in the session scope, we have used the
setAttribute() method of HttpSession interface and to get the attribute, we have used the getAttribute
method.

index.html

<form action="FirstServlet">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>

FirstServlet.java

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

public class FirstServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response){


try{

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

String n=request.getParameter("userName");
Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page 75
out.print("Welcome "+n);

HttpSession session=request.getSession();
session.setAttribute("uname",n);

out.print("<a href='SecondServlet'>visit</a>");

out.close();

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

SecondServlet.java

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

public class SecondServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)


try{

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

HttpSession session=request.getSession(false);
String n=(String)session.getAttribute("uname");
out.print("Hello "+n);

out.close();

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

}
web.xml
<web-app>
<servlet>
<servlet-name> FirstServlet </servlet-name>
<servlet-class>FirstServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name> FirstServlet </servlet-name>
<url-pattern>/ FirstServlet </url-pattern>
</servlet-mapping>
Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page 76
<servlet>
<servlet-name> SecondServlet </servlet-name>
<servlet-class>SecondServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name> SecondServlet </servlet-name>
<url-pattern> /SecondServlet </url-pattern>
</servlet-mapping>

</web-app>

1.18. SingleThreadModel interface

The servlet programmer should implement SingleThreadModel interface to ensure that servlet can
handle only one request at a time. It is a marker interface, means have no methods.

This interface is currently deprecated since Servlet API 2.4 because it doesn't solves all the thread-
safety issues such as static variable and session attributes can be accessed by multiple threads at the
same time even if we have implemented the SingleThreadModel interface. So it is recommended to
use other means to resolve these thread safety issues such as synchronized block etc.

Example of SingleThreadModel interface

Let's see the simple example of implementing the SingleThreadModel interface.

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

public class MyServlet extends HttpServlet implements SingleThreadModel{


public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();

out.print("welcome");
try{Thread.sleep(10000);}catch(Exception e){e.printStackTrace();}
out.print(" to servlet");
out.close();
}
}

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page 77


1.19. ServletInputStream class
ServletInputStream class provides stream to read binary data such as image etc. from the request
object. It is an abstract class.
The getInputStream() method of ServletRequest interface returns the instance of
ServletInputStream class. So can be get as:
ServletInputStream sin=request.getInputStream();

✓ Method of ServletInputStream class:

There are only one method defined in the ServletInputStream class.


int readLine(byte[] b, int off, int len) it reads the input stream.

1.20. ServletOutputStream class


ServletOutputStream class provides a stream to write binary data into the response. It is an abstract
class.
The getOutputStream() method of ServletResponse interface returns the instance of
ServletOutputStream class. It may be get as:
ServletOutputStream out=response.getOutputStream();
✓ Methods of ServletOutputStream class:
The ServletOutputStream class provides print() and println() methods that are overloaded.
1. void print(boolean b){}
2. void print(char c){}
3. void print(int i){}
4. void print(long l){}
5. void print(float f){}
6. void print(double d){}
7. void print(String s){}
8. void println{}
9. void println(boolean b){}
10. void println(char c){}
11. void println(int i){}
12. void println(long l){}
13. void println(float f){}
14. void println(double d){}
15. void println(String s){}

1.21. Deployment Descriptor (web.xml)


In a java web application a file named web.xml is known as deployment descriptor. It is a xml file
and <web-app> is the root element for it. When a request comes web server uses web.xml file to map
the URL of the request to the specific code that handle the request.
Sample code of web.xml file:
<web-app>

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page 78


<servlet>
<servlet-name>servletName</servlet-name>
<servlet-class>servletClass</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>servletName</servlet-name>
<url-pattern>*.*</url-pattern>
</servlet-mapping>

</web-app>

How web.xml works?:


When a request comes it is matched with url pattern in servlet mapping attribute. In the above
example all urls mapped with the servlet. You can specify a url pattern according to your need. When
url matched with url pattern web server try to find the servlet name in servlet attributes same as in
servlet mapping attribute. When match found control is goes to the associated servlet class.
How does the Container know which Servlet the client has requested for?
A Servlet can have 3 names:
✓ Client known URL name
✓ Deployer known secret internal name
✓ Actual file name

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page 79


Module-2
Introduction to JSP (Java Server Pages)
2.1. Overview of JSP
• JSP is a server-side programming technology that enables the creation of dynamic, platform-
independent method for building Web-based applications.
• JSP technology is used to create web application just like Servlet technology.
• Extension to servlet because it provides more functionality than servlet such as expression
language, jstl etc.
JSP Technology:
• A JSP page consists of HTML tags and JSP tags.
• JSP tags to write application logic using java
• JSP provides separation of HTML presentation logic from the application logic.
• Provides a way to combine the HTML and Java servlet programming.
• JSP specifications are built on the Java Servlet API.

Why JSP is preffered over Servlets? (Benefits of JSP over servlets):


➢ Extension to Servlet :
-Supports all features of servlets along with implicit objects, predefined tags, expression language
and Custom tags in JSP, that makes JSP development easy.
➢ Easy to maintain :
-easily separate our business logic with presentation logic. But servlet combines it.
➢ Fast Development:
No need to recompile and redeploy. But servlet code needs to be updated and recompiled if we
have to change the look and feel of the application.
➢ Less code than Servlet :
In JSP, we can use a lot of tags such as action tags, jstl, custom tags ,EL, implicit objects etc. that
reduces the code.

2.2. Advantage of JSP


✓ Easy to maintain and code.
✓ JSP is built on Java technology, so it is platform independent.
✓ Less code than servlets - lot of tags such as action tags, jstl, custom tags ,EL, implicit objects
etc. that reduces the code.
✓ Performance is significantly better because JSP allows embedding Dynamic Elements in
HTML Pages itself instead of having separate CGI files.
✓ JSP are always compiled before they are processed by the server unlike CGI/Perl which
requires the server to load an interpreter and the target script each time the page is requested.
✓ JavaServer Pages are built on top of the Java Servlets API, so like Servlets, JSP also has
access to all the powerful Enterprise Java APIs, including JDBC, JNDI, EJB, JAXP, etc.
✓ JSP pages can be used in combination with servlets that handle the business logic, the model
supported by Java servlet template engines.

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page 80


2.3. Life cycle of a JSP Page
A JSP page is transalated into Servlet in order to service requests. The translation of a JSP page to a
Servlet is called Lifecycle of JSP. JSP Lifecycle is exactly same as the Servlet Lifecycle, with one
additional first step, which is, translation of JSP code to Servlet code.
JSP Lifecycle steps:
1. Translation of JSP to Servlet code.
2. Compilation of Servlet to bytecode. (class files)
3. Loading Servlet class.
4. Creating servlet instance.
5. Initialization by calling jspInit() method
6. Request Processing by calling _jspService() method
7. Destroying by calling jspDestroy() method

The following diagrams depicts how a JSP page translated into servlets and how it executes.

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page 81


Following diagram shows during convertion of JSP into servlets how files translation happens
(Along with file extension):

Diagrammatic representation of seven-steps of JSP life cycle.

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page 82


2.4. JSP Scriptlet tag (Scripting elements)
Scripting elements provides the ability to insert java code inside the jsp.
There are three types of scripting elements:
✓ scriptlet tag
✓ expression tag
✓ declaration tag
➢ Scriptlet Tag:
A scriptlet tag is used to execute java source code in JSP.
Syntax:
<% java source code %>
Example:
<html>
<body>
<% out.print("welcome to jsp"); %>
</body>
</html>

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page 83


➢ expression Tag:
• Code placed within JSP expression tag is written to the output stream of the response.
• No need to write out.print() to write data.
• Used to print the values of variable or method.
• Syntax:
• <%= statement %>
• Example:
<html>
<body>
<%= "welcome to jsp" %>
</body>
</html>

➢ Declaration Tag:
• Used to declare fields and methods.
• Code written inside the jsp declaration tag is placed outside the service() method of auto
generated servlet.
• Syntax:
• <%! field or method declaration %>
• Example:
<html>
<body>
<%! int data=50; %>
<%= "Value of the variable is:"+data %>
</body>
</html>
Example of JSP declaration tag that declares method
<html>
<body>
<%!
int findcube(int n){
return n*n*n;
}
%>
<%= "Cube of 3 is:"+findcube(3) %>
</body> </html>

➢ Difference between JSP Scriptlet tag and Declaration tag


Jsp Scriptlet Tag Jsp Declaration Tag

can only declare variables not methods. can declare variables as well as methods.

The declaration of scriptlet tag is placed inside The declaration of jsp declaration tag is placed
the _jspService() method. outside the _jspService() method.

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page 84


2.5. Comparing JSP and Servlets
➢ JSP Supports all features of servlets along with implicit objects, predefined tags, expression
language and Custom tags in JSP, that makes JSP development easy than servlets.
➢ Easy to maintain :
JSP easily separate our business logic with presentation logic. But servlet combines it.
➢ Fast Development:
JSP No need to recompile and redeploy. But servlet code needs to be updated and recompiled
if we have to change the look and feel of the application.
➢ Less code than Servlet :
In JSP, we can use a lot of tags such as action tags, jstl, custom tags ,EL, implicit objects etc.
that reduces the code.

2.6. JSP Implicit Objects


• Objects are created by the web container that are available to all the jsp pages.
• JSP Implicit Objects are also called pre-defined variables.
• Developers can call/use these Objects directly without explicitly declaring in the JSP page.
• JSP supports 9 Implicit Objects.
Implicit Object TYPE

out JspWriter

request HttpServletRequest

response HttpServletResponse

config ServletConfig

session HttpSession

application ServletContext

pageContext PageContext

page Object

exception Throwable

1. out:
• It is the JspWriter object associated with the output stream of the response.
• Example:
<html>
<body>
<% out.print(“hello jsp”); %>

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page 85


</body>
</html>
2. request :
• The JSP request is an implicit object of type HttpServletRequest type.
• Created for each jsp request by the web container
• Used to get request information such as parameter, header information, remote address, server
name, server port, content type, character encoding etc.
• It can also be used to set, get and remove attributes from the jsp request scope.

• Example:
index.html
<form action=“display.jsp">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
display.jsp
<%
String name=request.getParameter("uname");
out.print("welcome "+name);
3. response :
• response is an implicit object of type HttpServletResponse.
• Response object is created by web container for each JSP request.
• Used to add or manipulate response such as redirect response to another resource, send error
etc.
• Example:
index.html
<form action=“display.jsp">
<input type="submit" value="go"><br/>
</form>
display.jsp
<%
response.sendRedirect("http://www.google.co.in");
%>

4. config:
• Config is an implicit object of type ServletConfig.
• Config object used to get initialization parameter for a particular JSP page
• Config object is created by the web container for each jsp page
• Example:
Index.html
<form action="welcome.jsp">
<input type="submit" value="go">
</form>
web.xml file
<init-param>
<param-name>dept</param-name>
Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page 86
<param-value>mca</param-value>
</init-param>
Welcome.jsp
<%
String value=config.getInitParameter("dept");
out.print("dept name is="+value);
%>
5. application object :
• application is an implicit object of type ServletContext.
• The instance of ServletContext is created only once by the web container when application or
project is deployed on the server.
• This object can be used to get initialization parameter from configuration file (web.xml).
• It can also be used to get, set or remove attribute from the application scope.
• This initialization parameter can be used by all jsp pages.
• Example:
index.html
<form action="welcome.jsp">
<input type="submit" value="go">
</form>
web.xml file
<context-param>
<param-name>place</param-name>
<param-value>mysore</param-value>
</context-param>
Welcome.jsp
<%
String value=application.getInitParameter(“place");
out.print("dept name is="+value);
%>
6. session object :
• session is an implicit object of type HttpSession.
• Developer can use this object to set,get or remove attribute or to get session information.
• Example:
<%
session.setAttribute("user",name);
%>
<%
session.getAttribute("user”);
%>
7. pageContext object :
• pageContext is an implicit object of type PageContext.
• pageContext object can be used to set,get or remove attribute from one of the following
scopes:
✓ Page : PAGE_SCOPE
✓ Request: REQUEST_SCOPE

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page 87


✓ Session:SESSION_SCOPE
✓ Application:APPLICATION_SCOPE
• page scope is the default scope.
• PAGE_SCOPE : Accessible only to the JSP page instance with which it is associated.
• REQUEST_SCOPE: Data is available in declared page and as well as in the forwarded page.
• SESSION_SCOPE: Data is available through out the session and lost once session is lost.
(data available from user Login to Logout)
• APPLICATION_SCOPE: Data is available even after session termination. Values set under
APPLICATION_SCOPE is available to all users.
• Example:
<%
pageContext.setAttribute("user",name,PageContext.SESSION_SCOPE);
%>
<%
String name=(String)pageContext.getAttribute("user",PageContext.SESSION_SCOPE);
%>

8. page object :
• page is an implicit object of type object class.
• This object is assigned to the reference of auto generated servlet class.
• This object is an actual reference to the instance of the page.
• It can be thought of as an object that represents the entire JSP page.
• The page object is really a direct synonym for the ”this” object.
• Example:
Object page=this;
<% (HttpServlet)page.log("message"); %>
OR
<% this.log("message"); %>
<%
out.println("servlet name="+page.getClass().getName());
%>
9. Exception handling in JSP or exception implicit object
• Exception- is an event that disrupts the normal flow of the program. It is an
object which is thrown at runtime.
• Example:
Statement1
Statement2
Statement3 //throws runtime error
Statement4
Statement5
Statement6
Statement7
statement8

exception object :

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page 88


• exception is an implicit object of type java.lang.Throwable class.
• The exception is normally an object that is thrown at runtime.
• Exception Handling is the process to handle the runtime errors.
• This object can be used to print the exception.
• It is typically used to generate an appropriate response to the error condition.
• The exception object is a wrapper containing the exception thrown from the previous page.

Three ways to perform exception handling:


1. By try…. Catch() block…
2. By ”errorPage” and ”isErrorPage” attributes of page directive
3. By <error-page> element in web.xml file
1. By try…. Catch() block…
Example:
index.html
<form action=“compute.jsp">
Nubmer1:<input type="text" name=“t1" /><br/><br/>
Number2:<input type="text" name=“t2" /><br/><br/>
<input type="submit" value="divide"/>
</form>

compute.jsp
<%
try{
String num1=request.getParameter("n1");
String num2=request.getParameter("n2");
int a=Integer.parseInt(num1);
int b=Integer.parseInt(num2);
int c=a/b;
out.print("division of numbers is: "+c); }
catch(Exception e){out.println(e); }
%>
2.By ”errorPage” and ”isErrorPage” attributes of page directive
Example:
index.html
<form action=“compute.jsp">
Nubmer1:<input type="text" name=“t1" /><br/><br/>
Number2:<input type="text" name=“t2" /><br/><br/>
<input type="submit" value="divide"/>
</form>
compute.jsp
<%@ page errorPage="error.jsp" %>
<%
String num1=request.getParameter(“t1");
String num2=request.getParameter(“t2");
int a=Integer.parseInt(num1);
int b=Integer.parseInt(num2);
int c=a/b;
out.print("division of numbers is: "+c);
%>
Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page 89
error.jsp
<%@ page iserrorPage=“true" %>
<%
out.println(“occurred exception➔”+exception);
%>

3.By <error-page> element in web.xml file:


• No need to specify “errorPage” attribute in each jsp page.
• Specifying the single entry in the web.xml file will handle the exception.
Example:
web.xml
<web-app>
<error-page>
<exception-type>java.lang.Exception</exception-type>
<location>/error.jsp</location>
</error-page> </web-app>
error.jsp
<%@ page iserrorPage=“true" %>
<%
out.println(“occurred exception➔”+exception);
%>

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page 90


Module-3
3. Controlling the Structure of generated servletsand Java Beans

3.1. Controlling the structure of generated servlets or JSP directives


• The jsp directives are messages that tells the web container how to translate a JSP page into
the corresponding servlet.
• Provides directions and instructions to web container in handling certain aspects of JSP
processing.
• A JSP directive affects the overall structure of the servlet class.
• There are 3 types of directives:
1. page directive
2. include directive
3. taglib directive

3.2. JSP page directive


• The page directive defines attributes that apply to an entire JSP page.
• Defines page-dependent attributes, such as scripting language, error page, and buffering
requirements.
• Syntax:
<%@ page attribute="value" %>
• Attributes of JSP page directive:
✓ import
✓ contentType
✓ extends
✓ info
✓ buffer
✓ language
✓ isELIgnored
✓ isThreadSafe
✓ autoFlush
✓ session
✓ pageEncoding
✓ errorPage
✓ isErrorPage

1.import attribute:
The import attribute is used to import class,interface or all the members of a package.
It is similar to import keyword in java class or interface.
Example of import attribute:
<html>
<body>
Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page 91
<%@ page import="java.util.Date" %>
<% out.println(“Today’s date is”+new Date()); %>
</body>
</html>
2.content Type attribute:
Defines the character encoding scheme.
The contentType attribute defines the MIME(Multipurpose Internet Mail Extension) type of the
HTTP response.The default value is "text/html;charset=ISO-8859-1".
MIME :It's a way of identifying files on the Internet according to their nature and format.
Example of content Type attribute:
<html>
<body>
<%@ page contentType=“application/msword" %>
<% out.println(“hello jsp”); %>
</body>
3.info attribute:
• Defines a string that can be accessed with the servlet's getServletInfo() method.
• Example of info attribute:
<html>
<body>
<%@ page info=“vtu mca 4th sem" %>
<% out.println(“hello jsp”); %>
</body>
</html>
The web container will create a method getServletInfo().
public String getServletInfo() {
return ” vtu mca 4th sem "; }

4. extends attribute:
• The extends attribute defines the parent class that will be inherited by the generated servlet. It
is rarely used.
• Example of extends attribute:
• Page1.jsp
• <form method="post" action="page2.jsp">
• <input type="text" name="t1"><br.</br>
• <input type="submit" name="t3" value="go">
• </form>
Page2.jsp
<%@page extends="package1.p3"%>
<%
package1.p3 obj=new package1.p3();
obj.service(request, response);
p3.java
public class p3 extends HttpServlet {

public final void service(HttpServletRequest request,HttpServletResponse response) throws


IOException
{
PrintWriter out=response.getWriter();
Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page 92
out.println(“Iam p3.java");
String s1=request.getParameter("t1");
String s2=request.getParameter("t2");
out.println("s1="+s1+"s2="+s2);
}
}

5. buffer attribute:
• The buffer attribute sets the buffer size in kilobytes to handle output generated by the JSP
page.
• The default size of the buffer is 8Kb.
Example:
<html>
<body>
<%@ page buffer="16kb" %>
Today is: <%= new java.util.Date() %>
</body>
</html>
6. autoFlush attribute:
• autoFlush attribute defines whether the buffered output is flushed automatically.
• The autoFlush attribute tells the JSP engine when buffer should be flushed.
• By default it is set to true. If you set it to false and the buffer becomes full, an exception will
be thrown.
• Syntax:
• <%@ page autoFlush=“true/false" %>
• Example:
<%@ page autoFlush=“true" %>
Today is: <%= new java.util.Date() %>

8. isThreadSafe attribute:
• Servlet and JSP both are multithreaded.
• To control this behaviour of JSP page, you can use isThreadSafe attribute of page directive.
• The default value of isThreadSafe is true.
• If you make it false, the web container will serialize the multiple requests, i.e. it will wait until
the JSP finishes responding to a request before passing another request to it.
Syntax:
• <%@ page isThreadSafe=“true/false" %>
• Example:
<%@ page isThreadSafe=“true" %>
<% out.println(“hello JSP”); %>

<%@ page isThreadSafe=“false" %>


<% out.println(“hello JSP”); %>
• When it is set to “false” Webcontainer implements “SingleThreadModel” interface.
• Example : generated servlet:
public class SimplePage_jsp extends HttpJspBase
implements SingleThreadModel{
.......
Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page 93
}

10. iserrorPage attribute:


• It is used to declare that the current page is the error page. (i.e. Exception which occurred
during runtime are printed in this page ).
• Example:
• myerrorpage.jsp
<%@ page iserrorPage=“true" %>
<%
out.println(exception);
%>

11. pageEncoding attribute:


• It represents page encoding type
• JSP web container encoding types are
• ISO-8859-1
• UTF-8
• A file may contain only text. Even still, it is a sequence bytes. It should be informed to JSP in
what format the data is to be read from the file. It is denoted by pageEncoding.
• Example:
• <%@page pageEncoding =“UTF-8” %>

12. session attribute:


• Specifies whether or not the JSP page participates in HTTP sessions.
• If it is set to false then we can’t set any value in the session object.
Example:
<%@page session=“true” %>

13. isELIgnored Page attribute:


• we can ignore the Expression Language (EL) in jsp by the isELIgnored attribute.
• By default its value is false i.e. Expression Language is enabled by default.
• Example:
<%@ page isELIgnored="true" %>
//Now EL will be ignored

Expression language (EL)


• It was introduced in JSP 2.0.
• The Expression Language (EL) simplifies the accessibility of data stored in the Java Bean
component, and other objects like request, session, application etc.
• EL includes arithmetic, relational and logical operators too.
• Syntax
• ${ expression }
• Example:
• ${2<3} ${3+4+5} Welcome, ${ param.t1 }

3.3. Jsp include Directive


• The include directive is used to include the contents of any resource it may be jsp file, html
file or text file.

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page 94


• The include directive tells the Web Container to copy everything in the included file and paste
it into current JSP file.
• Includes resource at page translation time.
• The jsp page is translated only once so it will be better to include static resource.
• The include directive includes the original content, so the actual page size grows at runtime.
• Syantax:
• <%@ include file="filename.jsp" %>

3.4. jsp taglib directives

• The taglib directive is used to define tag library that the current JSP page uses.
• A JSP page might include several tag library.
• JavaServer Pages Standard Tag Library (JSTL), is a collection of useful JSP tags.
• It provides many commonly used core functionalities such as:
Iteration and conditionals, readymade tags for manipulating XML documents and performing
SQL operations.
• Syntax:
<%@ taglib prefix="prefixOfTag" uri="uriOfTagLibrary" %>
Example:
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
//Example: printing something
<c:out value="our java" />
//Example: Initializing variable printing its value
<c:set var="i" value="vinay kumar"></c:set>
<c:out value="${i}"/>
Example: Looping
<c:forEach var="k" begin="1" step=“1" end="10">
${k} <c:out value="hello"></c:out>

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page 95


</c:forEach>
Example: if statement
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:set var="age" value="10"></c:set>
<c:if test="${age<18}">
<c:out value="Not eligible for voting"></c:out>
</c:if>
<c:if test="${age>18}">
<c:out value=“ Eligible for voting"></c:out>
</c:if>
Example: choose statement (SWITCH statement)
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:set var="age" value="100"></c:set>
<c:choose>
<c:when test="${age<18}">
<c:out value="age is less than 18"></c:out>
</c:when>
<c:when test="${age>18 && age<60}">
<c:out value="age is more than 18 and less than 60"></c:out>
</c:when>
<c:otherwise>
<c:out value="Invlid age"></c:out>
</c:otherwise>
</c:choose>

3.5. JSP Action Tags


✓ Called as “Standard Actions”, because tags are predefined and logic also predefined no need
to implement.
✓ JSP Actions are used to perform some specific action/tasks.
✓ It is loaded during “Runtime”.
✓ The action tags are used to control the flow between pages and to use Java Bean.
✓ There are many JSP Action tags/Elements.
✓ JSP actions use constructs in XML syntax to control the behavior of the servlet engine.
✓ We can dynamically insert a file, reuse JavaBeans components, forward the user to another
page, or generate HTML for the Java plugin.
General syntax:
<jsp:action_name attribute=“value”/>
Common Attributes:
✓ Id attribute: Uniquely identifies the action element.
✓ Scope attribute: This attribute identifies the lifecycle of the Action element
JSP Action Tags Description
jsp:forward forwards the request and response to another
resource.
jsp:include includes another resource.
jsp:param sets the parameter value. It is used in forward and
include mostly.
jsp:useBean creates or locates bean object.
Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page 96
jsp:setProperty sets the value of property in bean object.
jsp:getProperty prints the value of property in the bean object.
jsp:plugin embeds another components such as applet.
jsp:fallback can be used to print the message if plugin is
working. It is used in jsp:plugin.

1. <jsp:forward> Action tag


➢ Attributes:
• Page: Should consist of a relative URL of another resource such as a static page, another JSP page, or
a Java Servlet.
• Example: first.jsp
<html> <head> </head>
<body> Iam first .jsp
<jsp:forward page="second.jsp">
<jsp:param name="t1" value=“ Harsha"></jsp:param>
</jsp:forward>
</body>
</html>
• second.jsp
<html> <head> </head> <body> Iam second .jsp
<%
String s=request.getParameter(“t1”);
out.println(“s=‘+s); %>
</body> </html>

2. <jsp:include> Action tag:


✓ Includes the runtime response of a JSP page into the current page.
✓ The jsp:include action tag is used to include the content of another resource it may be jsp,
html or servlet.
✓ Syntax of jsp:include action tag without parameter:
✓ <jsp:include page=“Relative URL" />
✓ Syntax of jsp:include action tag with parameter:
<jsp:include page=“RelativeURL">
<jsp:param name="parametername" value="parametervalue | <%=expression%>" />
</jsp:include>
➢ Attributes:
• page :The relative URL of the page to be included.
• flush : The boolean attribute determines whether the included resource has its buffer flushed
before it is included.
• Example:
<html> <head> </head>
<body> Iam first .jsp
<jsp:include page="second.jsp">
<jsp:param name="t1" value=“ veersh"></jsp:param>
</jsp:include>

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page 97


</body>
</html>
• second.jsp
<html> <head> </head> <body> Iam second .jsp
<%
String s=request.getParameter(“t1”);
out.println(“s=‘+s); %>
</body> </html>

Differences between include directive and include action tag:

Include directive Include action tag

Includes specified Resourse Includes Resource during Runtime/Request time


during Translation time

Copies the included file References to the included file


Used for including static content. Used for both static and dynamic content.

Can’t pass Parameters along with Can pass Parameters along with include action tag
include directive tag

<%@include file=“page URL” <jsp:include page=“RelativeURL">


%> <jsp:param name="parametername" value="parametervalue ”/>
</jsp:include>

Example: Eaxmple:
<%@include file=“second.jsp” <jsp:include page=“second.jsp">
%> <jsp:param name=“t1” value=“Harsha”/>
</jsp:include>

3. <jsp:param> Action tag:


✓ Adds parameters to the request object.
✓ Useful for passing the parameters to Other JSP action tags such as JSP include & JSP forward
tag.
✓ Syntax:
✓ <jsp: param name="param_name_here" value="value_of_parameter_here" />
✓ Example:
<jsp:include page=“p2.jsp">
<jsp:param name=“uid" value=“rajath" />
</jsp:include>
➢ Attributes:
• name :The name of the passing parameter.
• value :The value of the defined parameter.

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page 98


3.6. Using java beans components in JSP documents
• A Java Bean is a java class that should follow following conventions:
• It should have a no-arg constructor.
• It should be Serializable.
• It should provide methods to set and get the values of the properties, known as getter and
setter methods.
• Why to use Java Bean?
• It is a reusable software component. A bean encapsulates many objects into one object, so
we can access this object from multiple places.
• It’s easy to maintain.

4. <jsp:useBean> Action tag:


• creates or locates bean object.
• This action is useful to use Beans in a JSP page, through this tag we can easily invoke a bean.
• It first searches for an existing object utilizing the id and scope variables. If an object is not
found, it then tries to create the specified object.
• Once a bean class is loaded, we can use <jsp:setProperty> and <jsp:getProperty> actions to
modify and retrieve the bean properties.
Syntax:
<jsp:useBean id = "name" class = "package.class“ scope=“scopetype” />
➢ Attributes:
✓ id: contains var name or contains instance / object.
✓ class:Designates the full package name of the bean.
✓ Scope: Represents bean instance access location and the values are :
❖ page: represents within JSP page
❖ request: represents within same JSP page
❖ session: represents Entire session
❖ application: It exist to entire web application
✓ beanName:Gives the name of the bean as specified by the instantiate () method of the
java.beans.Beans class.
✓ type: Specifies the type of the variable that will refer to the object.
✓ Example:
P1.jsp
<form method="post" action="load.jsp">
usn:<input type="text" name="usn"><br>
Name:<input type="text" name="name"><br>
<input type="submit" value="save“>
</form>

• Example: student.java
package pack1;
public class student {
private int usn; private String name;
public int getUsn() {

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page 99


return usn;
}
public String getName() {
return name;
}
public void setUsn(int usn) {
this.usn = usn;
}
public void setName(String name) {
this.name = name;
}}
• Example: load.jsp
<jsp:useBean id="st" class="pack1.student" scope="request">
<jsp:setProperty name="st“ property="*“ > </jsp:setProperty>
</jsp:useBean>
<jsp:getProperty name="st" property="usn"> </jsp:getProperty>
<jsp:getProperty name="st" property="name"> </jsp:getProperty>

5. <jsp:setProperty> Action tag:

✓ The setProperty action sets the properties of a Bean. The Bean must have been previously
defined before this action.
✓ Two ways of defining it:
❖ outside <jsp:useBean> tag:
jsp:setProperty is executed regardless of whether a new bean was instantiated or an existing
bean was found.
❖ inside the <jsp:useBean> tag:
jsp:setProperty is executed only if a new object was instantiated, not if an existing one was
found.
• Example:
<jsp:useBean id="st" class="pack1.student" scope="request">
<jsp:setProperty name="st“ property="*“ > </jsp:setProperty>
</jsp:useBean>
• (OR)
<jsp:useBean id="st" class="pack1.student" scope="request">
<jsp:setProperty name="st“ property=“usn“ value=“100” > </jsp:setProperty>
</jsp:useBean>

6. <jsp:getProperty> Action tag:


• The getProperty action is used to retrieve the value of a given property and converts it to a
string, and finally inserts it into the output.
• Example:
• <jsp:useBean id="st" class="pack1.student" scope="request">
• <jsp:getProperty name = “st” property = “usn"/>
• <jsp:getProperty name = “st” property = “name"/>
Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page
100
• Attributes:
• name:contains Bean Id
• property :Contains property name / setter method name.
• The getProperty action is used to retrieve the value of a given property and converts it to a
string, and finally inserts it into the output.
• Example:
<jsp:useBean id="st" class="pack1.student" scope="request">
<jsp:getProperty name = “st” property = “usn"/>
<jsp:getProperty name = “st” property = “name"/>

7. <jsp:plugin> Action tag:


• The jsp:plugin action tag is used to embed applet in the jsp file. The jsp:plugin action tag
downloads plugin at client side to execute an applet or bean.
• Syntax of jsp:plugin action tag
<jsp:plugin type= "applet | bean" code= "nameOfClassFile"
codebase= "directoryNameOfClassFile"
</jsp:plugin>
• Example: p1.jsp page
<jsp:plugin type="applet" archive="kapplet.jar" code="p1.applet1" width="500"
height="600">

<jsp:params>
<jsp:param name="user" value="vinay"></jsp:param>
<jsp:param name="city" value="mysore"></jsp:param>
</jsp:params>
<jsp:fallback>unable to load applet</jsp:fallback>
</jsp:plugin>

• Example: applet1.java
package p1;
import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
public class applet1 extends Applet {
public void init() { }
public void paint(Graphics g)
{ setBackground(Color.GREEN);
setForeground(Color.BLUE);
g.drawString(“Welcome to MCA",100,100);
g.drawString("name="+getParameter("user")+"city="+getParameter("city"),150,150);

}
}

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page


101
3.7. Introduction to Java Beans

• Software components are self-contained software units, developed according to the motto
“Develop them once, run and reuse them everywhere”.
Or
in other words, “reusability” is the main concern behind the component model
• A software component is a reusable object that can be plugged into any target software
application.
• We can develop software components using various programming languages, such as C, C++,
Java, and Visual Basic.
• A “Bean” is a reusable software component model based on sun’s java bean specification that
can be manipulated visually in a builder tool.
• Builder tool : is nothing but an application development tool which lets you both to create
new beans or use existing beans to create an application.
• Java provides the facility of creating some user defined components by means of Bean
programming.
• We can directly embed these beans into the software.
Advantages of Java Beans:
• The java beans posses the property of “Write once and run anywhere”.
• Beans can work in different local platforms.
• Beans have the capability of capturing the events sent by other objects and vice versa enabling
object communication.
• The properties, events and methods of the bean can be controlled by the application
developer.(ex. Add new properties)
• Beans can be configured with the help of auxiliary software during design time.(no hassle at
runtime)
• The configuration setting can be made persistent.(reused)
• Configuration setting of a bean can be saved in persistent storage and restored later.
What can we do/create by using JavaBean?
• There is no restriction on the capability of a Bean.
• Example:
✓ Checking the spelling of a document
✓ forecasting the performance of a stock portfolio.
✓ Generate a pie chart from a set of data points
Builder Tool:
• Builder tools allow a developer to work with JavaBeans in a convenient way by examining a
JavaBean by a process known as Introspection.
• A builder tool exposes the discovered features of the JavaBean for visual manipulation.
• A builder tool maintains a list of all JavaBeans available.
• It allows you to compose the Bean into applets, application, servlets and composite
components (e.g. a JFrame), customize its behavior and appearance by modifying its
properties and connect other components to the event of the Bean or vice versa.
Why builder tool?
• It provides the feature of:

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page


102
✓ Compose beans
✓ Customize bean properties
✓ Connect other components to the events
• It allows you to compose the Bean into applets, application, servlets and composite
components (e.g. a JFrame), customize its behavior and appearance by modifying its
properties and connect other components to the event of the Bean or vice versa.
BDK (Bean Development Kit)
The below fig shows the Builder Tool Image

JavaBeans basic rules


A JavaBean should:
✓ be public
✓ implement the Serializable interface
✓ have a no-arg constructor
✓ be derived from javax.swing.JComponent or java.awt.Component if it is visual
Java beans supports:
• It supports the standard component architecture features like
✓ Properties
✓ Events
✓ Methods
✓ Persistence.
• In addition Java Beans provides support for

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page


103
✓ Introspection: Allows Automatic Analysis of a java beans
✓ Customization: To make it easy to configure a java beans component
Phases of Java Beans
• The Java Bean components can exist in one of the following three phases of development:
✓ Construction phase
✓ Build phase
✓ Execution phase

3.8. Elements of a JavaBean


✓ Properties
✓ Methods
✓ Events

➢ Properties:
• Similar to instance variables.
• A bean property is a named attribute of a bean that can affect its behavior or appearance.
• Examples of bean properties include
color, label, font, font size, and display size.
➢ Methods:
• Same as normal Java methods.
• Every property should have accessor (get) and mutator (set) method.
• All Public methods can be identified by the introspection mechanism.
• There is no specific naming standard for these methods.
➢ Events:
• Similar to Swing/AWT event handling.
Example:
✓ KeyBoardEvents –Key Listeners
✓ Mouse Events- Mouse Listeners
✓ Button Event- Action Listeners

3.9. The JavaBean Component Specification


• Customization: Is the ability of JavaBean to allow its properties to be changed in build and
execution phase.
• Persistence:- Is the ability of JavaBean to save its state to disk or storage device and restore
the saved state when the JavaBean is reloaded.
• Communication:-Is the ability of JavaBean to notify change in its properties to other
JavaBeans or the container.
• Introspection:- Is the ability of a JavaBean to allow an external application to query the
properties, methods, and events supported by it.

3.10. Services of JavaBean Components


• Builder support:- Enables you to create and group multiple JavaBeans in an application.
• Layout:- Allows multiple JavaBeans to be arranged in a development environment.

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page


104
• Interface publishing: Enables multiple JavaBeans in an application to communicate with each
other.
• Event handling:- Refers to firing and handling of events associated with a JavaBean.
• Persistence:- Enables you to save the last state of JavaBean.

3.11. Features of a JavaBean


✓ “introspection” - so that a builder tool can analyze how a bean works.
✓ “customization” - to allow the customisation of the appearance and behaviour of a bean.
✓ “events” - as a simple communication metaphor that can be used to connect up beans.
✓ “properties”- both for customization and for programmatic use.
✓ “persistence” -so that a bean can save and restore its customized state

Pictorial representation of Java bean component

3.12. Steps to Develop a User-Defined JavaBean


• Create a directory for the new bean
• Create the java bean source file(s)
• Compile the source file(s)
• Create a manifest file
• Generate a JAR file
• Start BDK
• Load Jar file
• Test.
1. Create a directory for the new bean
Create a directory/folder like C:\Beans
2. Create bean source file - MyBean.java
import java.awt.*;
public class MyBean extends Canvas
Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page
105
{
public MyBean()
{
setSize(70,50);
setBackground(Color.green);
}
}
3. Compile the source file(s)
• C:\Beans >Javac MyBean.java
4. Create a manifest file
• Manifest File
• The manifest file for a JavaBean application contains a list of all the class files that make up a
Java Bean.
• · The entry in the manifest file enables the target application to recognize the JavaBean
classes for an application.
• Its having the extension of .mf
• Example : MyBean.mf contains
• Manifest-Version: 1.0
• Name: MyBean.class
• Java-Bean: true
5. Generate a JAR file
• JAR File:
✓ Whenever a developer wants to distribute a version of his software, then all he want is to
distribute a single file and not a directory structure filled with class files.
✓ A JAR file can contain both class files and other file types like sound and image files which
may be included in the project.
✓ All the files in a JAR file are compressed using a format similar to zip.
✓ JAR file allows you to efficiently deploy a set of classes and their associated resources.
✓ JAR file makes it much easier to deliver, install, and download.
✓ It is a compressed format of our complete java application to be deployed.
Example:
✓ C:\Beans >jar cfm MyBean.jar MyBean.mf MyBean.class
✓ The files of a JavaBean application are compressed and grouped as JAR files to reduce the
size and the download time of the files.
✓ The syntax to create a JAR file from the command prompt is:
✓ jar <options> <file_names>
✓ The file_names is a list of files for a JavaBean application that are stored in the JAR file.
✓ The various options that you can specify while creating a JAR file are:
• c: Indicates the new JAR file is created.
• f: Indicates that the first file in the file_names list is the name of the JAR file. (Jar file
name)
• m: Indicates that the second file in the file_names list is the name of the manifest file.
• t: Indicates that all the files and resources in the JAR file are to be displayed in a tabular
format.
• v: Indicates that the JAR file should generate a verbose output.
Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page
106
• x: Indicates that the files and resources of a JAR file are to be extracted.
• o: Indicates that the JAR file should not be compressed
6. Start BDK:
• Using run.bat file.
7. Load Jar file:
• Go to Beanbox->File->Load jar. Here we have to select our created jar file when we click
on ok, our bean(userdefined) MyBean appear in the ToolBox.
8. Test our created user defined bean
• Select the MyBean from the ToolBox when we select that bean one + simple appear then
drag that Bean in to the Beanbox.
• If you want to apply events for that bean, now we apply the events for that Bean.

3.13. Introspection
• Introspection can be defined as the technique of obtaining information about bean properties,
events and methods.
• Basically introspection means analysis of bean capabilities.
• Introspection is the automatic process by which a builder tool finds out which properties,
methods and events a bean supports.
• Introspection describes how methods, properties, and events are discovered in the beans that
you write.
• This process controls the publishing and discovery of bean operations and properties
• Without introspection, the JavaBeans technology could not operate.
• BDK Introspection:
• Allows automatic analysis of a java beans component
• Enables a builder tool to analyze how a bean works
(OR)
• A mechanism that allows classes to publish the operations and properties they support.
• To support the discovery of such mechanism.
• Introspection can be defined as the technique of obtaining information about bean properties,
events and methods.
• Basically introspection means analysis of bean capabilities
• There are two ways in which the developer of a Bean can indicate which are all its properties,
events, and methods
• 1st way:
Should be exposed by an builder tool. With the first method, simple naming conventions
are used.
These allow the introspection mechanisms to infer information about a Bean.
• 2 way:
nd

Using an additional class is provided that explicitly supplies this information.

3.14. Design patterns for JavaBean Properties


• A property is a subset of a Bean’s state.
• A bean property is a named attribute of a bean that can affect its behavior or appearance.
• Examples of bean properties:

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page


107
• color, label, font, font size, and display size.
• Properties are the private data members of the JavaBean classes.
• Properties are used to accept input from an end user in order to customize a JavaBean.
• Properties can retrieve and specify the values of various attributes, which determine the
behavior of a JavaBean.

Types of JavaBeans Properties


✓ Simple properties
✓ Boolean properties
✓ Indexed properties
✓ Constrained Properties
✓ Bound Properties

➢ Simple properties:
• Simple properties refer to the private variables of a JavaBean that can have only a single
value.
• Simple properties are retrieved and specified using the get and set methods respectively.
• A read/write property has both of these methods to access its values.
• The get method used to read the value of the property
• The set method that sets the value of the property.
• The setXXX() and getXXX() methods are the heart of the java beans properties mechanism.
• This is also called getters and setters. These accessor methods are used to set and read the
property .
• The syntax of get method is:
• public return_type get<PropertyName>()
• Example:
public String getColor()
{
return color;
}
• Read only property has only a get method.
• The syntax of set method is:
• public void set<PropertyName>(data_type value)
• Example:
public void setColor(String color)
{
this.color=color;
}
Write only property has only a set method
➢ Boolean properties:
• Example:
Private boolean dotted=false;
public boolean isDotted()
{

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page


108
return dotted;
}
public void setDotted(boolean dotted)
{
this.dotted=dotted;

➢ Indexed Properties:
• Syntax for get the value of the required index:
• public property_datatype get<PropertyName>(int index)
• Example:
private double data[];
public double getData(int index)
{
return data[index];
}

✓ To get all the values from the indexed property:


✓ Example:
public double[] getData()
{
return data;
}
✓ Example: To set the value of the required Index.
public void setData(int index,double value)
{
data[index]=value;
}
✓ Example: To set array of values.
public void setData(double[] values)
{
}

➢ Bound Properties:
• A bean that has a bound property generates an event when the property is changed.
• Bound Properties are the properties of a JavaBean that inform its listeners about changes in its
values.
• Bound Properties are implemented using the PropertyChangeSupport class and its methods
• Bound Properties are always registered with an external event listeners.
• PropertyChangeEvent object is send to the beans which are registered to listen this Event.
• Bean with bound property - Event source
• Bean implementing listener -- event target
• Uses PropertyChangeSupport Class object to intimate all Registered Listeners by using the
method
• firePropertyChange("name", this.name, name)

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page


109
• The ProperyChangeListener interface object will take care of informing to all implemented
bean classes who are registered to it.
• With the help of PropertyChangeEvent object target bean can access the old value, changed
value (new vlaue) of the property/attribute.
• Bound Properties: Example:
public class bean1 {
private int price;
PropertyChangeSupport changeSupport = new PropertyChangeSupport(this);
public void setPrice(int price) {
changeSupport.firePropertyChange(“Price", this.price, price);
this.name = name;
}
public String getPrice() {
return name;
}
public void addPropertyChangeListener(PropertyChangeListener p) {
changes.addPropertyChangeListener(p);
}
}

public class bean2 implements PropertyChangeListener {


@Override
public void propertyChange(PropertyChangeEvent evt) {
System.out.println("Hey Iam Bean2 Receiver, I had received msg ha ha ha!...");
System.out.println("Property Name : " + evt.getPropertyName());
System.out.println("Old Value : " + evt.getOldValue());
System.out.println("New Value : " + evt.getNewValue());
}
}

➢ Constrained Properties:
• It generates an event when an attempt is made to change its value
• Constrained Properties are implemented using the PropertyChangeEvent class.
• The event is sent to objects that previously registered.
• The received bean objects have the ability to veto the proposed change.
• This allows a bean to operate differently according to the runtime environment.
• A bean property for which a change to the property results in validation by another bean.
• The other bean may accept or reject the change if it is not appropriate.
• It uses the object of VetoableChangeSupport class.
• Syntax: get method:
• public string get<ConstrainedPropertyName>()
• Syntax :set method:
• public string set<ConstrainedPropertyName>(String str)throws PropertyVetoException

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page


110
• Before making any changes to the Constrined property it intimates to all its registerd
VetoableChangeListeners.
• If none of the VetoableChangeListeners is throwig an Exception then only it proceed with the
change.

3.15. Design Patterns for Events


• Event means any activity that interrupts the current ongoing activity.
• Event Enables Beans to communicate and connect together.
• Example: mouse clicks, pressing key…
• Event Source: generator of the event
• Event Listener: receiver of the event
• Event Object: Type of the generated by the event Source.
• Creating Custom Events: using extending EventObject class.
• Creating Custom Listeners interface By extending EventListener interface.
• Creating Event Handler:
✓ Should Implement following methods:
❖ addXXListener(): Registers listeners of a JavaBean event.
❖ fireXX(): Notifies the listeners of the occurrence of a JavaBean event.
❖ removeXXListener(): Removes a listener from the list of registered listeners of
a JavaBean

3.16. Persistence
• Persistence means an ability to save properties and events of our beans to non-volatile storage
and retrieve it later.
• It has the ability to save a bean to storage and retrieve it at a later time Configuration settings
are saved.
• It is implemented by Java serialization.
• Java Beans supports two forms of persistence:
✓ Automatic persistence-Using java’s built-in serialization mechanism
✓ External persistence- in user defined bean, by building an applet

3.17. Customizers

• The Properties window of the BDK allows a developer to modify appearance and behaviour
of several properties of the Bean.
• A Bean developer can provide a customizer that helps another developer configure the Bean.
A customizer can provide a step-by-step guide through the process that must be followed to
use the component in a specific context. Online documentation can also be provided. A Bean
developer has great flexibility to develop a customizer that can differentiate his or her product
in the marketplace.

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page


111
3.18. The Java Beans API
• The Java Beans functionality is provided by a set of classes and interfaces in the java.beans
package
• Classes present in the java.beans package:
Class Name Purpose
BeanDescriptor Global Information about the Class

Beans Contains general purpose bean methods

EventHandler The EventHandler class provides support for


dynamically generating event
listeners

EventSetDescriptor Describes a group of events that a given Java


bean fires

PropertyChangeSupport It is used with Bound properties

VetoableChangeSupport used by beans that support constrained properties

PropertyChangeEvent This calss object is used, whenever a bean


changes a "bound" or "constrained" property

Introspector provides information about the properties,


events, and methods supported by a target Java
Bean.

• Interfaces present in the java.beans package:


Interface Name Purpose
AppletInitializer Contains method to initialize bean applet

BeanInfo provide explicit information about their bean like


Methods, Properties, Events
Customizer provides a complete custom GUI for customizing
a target Java Bean.
PropertyChangeListener A "PropertyChange" event gets fired whenever a
bean changes a "bound" property.
VetoableChangeListener A VetoableChange event gets fired whenever a
bean changes a "constrained" property

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page


112
3.19. The BeanInfo Interface
• The BeanInfo interface provides the methods that enable you to specify and retrieve the
information about a JavaBean.
• By default an Introspector uses the Reflection API to determine the features of a JavaBean.
• Even without using Interospector class, we can additional information about the methods and
properties of the bean using BeanInfo Interface.
• Methods provided by BeanInfo Interface:
✓ MethodDescriptor[] getMethodDescriptors()
✓ EventDescriptor[] getEventDescriptors()
✓ PropertyDescriptor[] getPropertyDescriptors()

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page


113
Module-4
Annotations and JDBC

4.1. Java Annotations


• Java Annotation is a tag that represents the ”metadata”.
• It is “attached with class, interface, methods or fields” to indicate some “additional
information”
• It can be used by java compiler and JVM.
• it is an “alternative option for XML and java marker interfaces”.
• Built-In Java Annotations used in java code
✓ @Override
✓ @SuppressWarnings
✓ @Deprecated
• Built-In Java Annotations used in other annotations (for creating custom annotations)
✓ @Target
✓ @Retention
✓ @Inherited
✓ @Documented
➢ Built-In Java Annotations used in java code
• @Override:
✓ @Override annotation assures that the subclass method is overriding the parent class
method.
✓ If it is not so, compile time error occurs.
✓ silly mistake such as spelling mistakes are identified through @Override annotation that
provides assurity that method is overridden.
✓ @Override:Example:
class A{
void myMethod(){System.out.println("eating something");}
}
class B extends A{
@Override
void mymethod(){System.out.println("eating foods");}
//should be myMethod()
}
class TestAnnotation1{
public static void main(String args[]){
A a=new B();
a.myMethod();
}}

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page


114
• @SuppressWarnings:
✓ It is used to suppress warnings issued by the compiler.
✓ If you remove the @SuppressWarnings("unchecked") annotation, it will show warning at
compile time because we are using non-generic collection.
✓ @SuppressWarnings: Example
import java.util.*;
class Test{
@SuppressWarnings("unchecked")
public static void main(String args[]){
ArralList list=new ArrayList();
list.add(“a”);
System.out.println(list);
}
}

• @Deprecated:
✓ @Deprecated annoation marks that this method is deprecated so compiler prints warning.
✓ It informs user that it may be removed in the future versions. So, it is better not to use
such methods.
✓ @Deprecated : Example
class A{
void m(){System.out.println("hello m");}

@Deprecated
void n(){System.out.println("hello n");}
}

class TestAnnotation3{
public static void main(String args[]){

A a=new A();
a.n();
}}
4.2. Java Custom Annotation
• Custom annotations means Java User-defined annotations which are easy to create and use.
• The @interface element is used to declare an annotation.
• Example:
• @interface MyAnnotation{}
❖ Types of Custom Annotation:
• 3 types of Custom annotations.
1. Marker Annotation
2. Single-Valued Annotation
3. Multi-Valued Annotation

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page


115
1. Marker Annotation:
✓ An annotation that has no members, is called marker annotation.
Example:
@interface MyAnnotation{}
2. Single-Value Annotation:
✓ An annotation that has one member, is called single-value annotation.
✓ Example: with no default values
@interface MyAnnotation{
int value();
}
✓ Example: with default values
@interface MyAnnotation{
int value() default 10;
}
3. Multi-Value Annotation:
✓ An annotation that has more than one member, is called Multi-Value annotation.
• Example:1
@interface MyAnnotation{
int value1();
String value2();
String value3();
}
• Example:2
@interface MyAnnotation{
int value1() default 1;
String value2() default “ab”;
String value3() default ““;
}

4.3. Built-in Annotations used in custom annotations in java


• @Target
• @Retention
• @Inherited
• @Documented
➢ @Target
• @Target tag is used to specify ElementType which denotes where to apply annotations such
as TYPE, METHOD, FIELD,CONSTRUCTOR etc
• Example:
• @Target({ElementType.TYPE, ElementType.FIELD, ElementType.METHOD})
(OR)
@Target(ElementType.TYPE)
@interface MyAnnotation{

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page


116
int value1();
String value2();
}

➢ @Retention:
• @Retention annotation is used to specify to what level annotation will be available.
• RetentionPolicies:
❖ RetentionPolicy.SOURCE - Refers to the source code, discarded during compilation. It will not be
available in the compiled class.
❖ RetentionPolicy.CLASS - Refers to the .class file, available to java compiler but not to JVM . It is
included in the class file.
❖ RetentionPolicy.RUNTIME - Refers to the runtime, available to java compiler and JVM .

• Example:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@interface MyAnnotation{
int value1();
String value2();
}

@Target({ElementType.METHOD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@interface studentinfo
{
int usn() default 10;
String name() default "vinay";
}

@studentinfo //@studentinfo(usn=100,name="rajath")
public class p2 {
public static void main(String args[])
{
p2 obj=new p2();
Annotation an=obj.getClass().getAnnotation(studentinfo.class);
studentinfo s=(studentinfo)an;
System.out.println("usn="+s.usn()+"name="+s.name());
}}

➢ @Inherited:
• By default, annotations are not inherited to subclasses.
• The @Inherited annotation marks the annotation to be inherited to subclasses.

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page


117
• Example:
• @Inherited
• @interface ForEveryone { }//Now it will be available to subclass also
• @interface ForEveryone { }
• class Superclass{}
• class Subclass extends Superclass{}

✓ By default, annotations are not inherited to subclasses.


✓ The @Inherited annotation marks the annotation to be inherited to subclasses.
Example:
@Inherited
@interface ForEveryone { }//Now it will be available to subclass also

@interface ForEveryone { }
class Superclass{}

class Subclass extends Superclass{}

➢ @Documented:
✓ The @Documented Marks the annotation for inclusion in the documentation.
✓ It tells the tool that annotation to be documented. (In javadoc).
✓ It is designed to be used as an annotation to annotation.
✓ Example:
@Documented
@interface studentinfo
{
}
4.4. JDBC
• JDBC is a Java API for executing SQL statements
• JDBC stands for “Java Database Connectivity”.
• It consists of a set of classes and interfaces written in the Java programming language.
• JDBC provides a standard API tool for database application developers and makes it possible
to write database applications using a pure Java API.
• JDBC Definition: “An API that lets you access virtually any tabular data source from the Java
programming language”
• What’s a tabular data source?
• “Access virtually any data source, from relational databases to spreadsheets and flat files.”

4.5. JDBC Architecture


• Java code calls JDBC library
• JDBC loads a driver
• Driver talks to a particular database

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page


118
General Architecture of JDBC

1. Application: It is a java applet or a servlet which communicates with a data source.


2. The JDBC API: The JDBC API allows Java programs to execute SQL statements and retrieve
results. Some of the important classes and interfaces defined in JDBC API are as follows:
DriverManager
Driver
Connection
Statement
PreparedStatement
CallableStatement
ResultSet
SQL data
3. DriverManager: It plays an important role in the JDBC architecture.It uses some database-
specific drivers to effectively connect enterprise applications to databases.
4. JDBC drivers: To communicate with a data source through JDBC, you need a JDBC driver
that intelligently communicates with the respective data source.
Types of JDBC Architecture(2-tier and 3-tier)
The JDBC architecture consists of two-tier and three-tier processing models to access a database.
1. Two-tier model: A java application communicates directly to the data source. The JDBC driver
enables the communication between the application and the data source. When a user sends a
query to the data source, the answers for those queries are sent back to the user in the form of
Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page
119
results.
The data source can be located on a different machine on a network to which a user is
connected. This is known as a client/server configuration, where the user’s machine acts as a
client and the machine having the data source running acts as the server.
2. Three-tier model: In this, the user’s queries are sent to middle-tier services, from which the
commands are again sent to the data source. The results are sent back to the middle tier, and
from there to the user.
This type of model is found very useful by management information system directors.

4.6. JDBC Driver


❖ JDBC drivers created by DBMS manufacturers have to :
✓ Open a connection b/w the DBMS and J2EE component.
✓ Translate low-level equivalents of SQL statements sent by the j2EE component into
messages that can be processed by DBMS.
✓ Return data that conforms to the JDBC specification to the JDBC driver.
✓ Return info such as error messages that conforms to the JDBC specification to the JDBC
driver.
✓ Provide transaction management routines that conform to the JDBC specification.
✓ Close the connection b/w DBMS and the J2EE component
• JDBC Driver is a software component that enables java application to interact with the
database.
• Types of JDBC Drivers:
✓ JDBC-ODBC bridge driver (Type-1 Driver)
✓ Native-API driver (partially java driver) (Type2-Driver)
✓ Network Protocol driver (fully java driver) (Type-3 driver)
✓ Thin driver (fully java driver) (Type-4 Driver
➢ JDBC-ODBC bridge driver:
✓ The JDBC-ODBC bridge driver uses ODBC driver to connect to the database.
✓ The JDBC-ODBC bridge driver converts JDBC method calls into the ODBC function
calls.
✓ This is now discouraged because of thin driver.
✓ Microsoft created ODBC (Open Database Connection), which is the basis from which Sun
created JDBC.
✓ MS Access and SQL Server contains ODBC driver written in C language using pointers,
but java does not support the mechanism to handle pointers.
✓ So JDBC-ODBC Driver is created as a bridge between the two so that JDBC-ODBC
bridge driver translates the JDBC API to the ODBC API.

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page


120
➢ Working Process:
• Java Code converted to JDBC format.
• JDBC format converted to ODBC format.
• ODBC format converted to specific DBMS format.
• DBMS processes the query and sends results to ODBC format.
• ODBC format converted to JDBC format.
• JDBC format converted to specific java format.
✓ Advantages:
• easy to use.
• can be easily connected to any database.
✓ Disadvantages:
• Performance degraded because JDBC method call is converted into the ODBC function
calls.
• The. ODBC driver needs to be installed on the client machine
• Platform dependent (Available only for windows)
➢ Native-API driver (partially java driver) :
• The Native API driver uses the client-side libraries of the database.
• The driver converts JDBC method calls into native calls of the database API.
• The Java/Native Code driver uses Java classes to generate platform- specific code that is
code only understood by a specific DBMS.

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page


121
• It is not written entirely in java.
• Ex: Driver for DB2, Informix, Intersoly, Oracle Driver, WebLogic drivers

✓ Working Process:
• Java Code converted to Java native API format.
• Java native API is specific DBMS format.
• DBMS processes the query and sends results to java format.
• J2EE COMPONENT <->JAVA NATIVE API<--> DBMS
✓ Advantage:
• performance upgraded than JDBC-ODBC bridge driver.
✓ Disadvantage:
• The Native driver needs to be installed on the each client machine.
• The Vendor client library needs to be installed on client machine.

➢ Network Protocol driver (fully java driver)


• The Network Protocol driver uses middleware (application server) that converts JDBC
calls directly or indirectly into the vendor-specific database protocol.
• It is fully written in java.

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page


122
✓ Working Process:
• Java Code converted to JDBC format.
• JDBC format converted to Middleware server format(calls).
• Then Middleware internally uses either Type1,2,3 or 4 drivers to convert Middleware call
to DBMS calls (DBMS format)
• DBMS processes the query and sends results to DBMS format.
• DBMS format converted to JDBC format.
• JDBC format converted to specific java format.
• J2EE COMPONENT <->JDBC FORMAT <->Middleware Server calls<->DBMS
FORMAT
• Advantage:
• No client side library is required because of application server that can perform
many tasks like auditing, load balancing, logging etc.
• Disadvantages:
• Network support is required on client machine.
• Requires database-specific coding to be done in the middle tier.
• Maintenance of Network Protocol driver becomes costly because it requires
database-specific coding to be done in the middle tier.

➢ Thin driver (fully java driver):


• The thin driver converts JDBC calls directly into the vendor-specific database
protocol.That is why it is known as thin driver.
• It is fully written in Java language.

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page


123
✓ Working Process:
• Java Code converted to DBMS format.
• DBMS processes the query and sends results to DBMS format.
• DBMS format converted to specific java format
• J2EE COMPONENT <-> DBMS FORMAT <->DBMS
• Advantage:
• Better performance than all other drivers.
• No software is required at client side or server side.
• Disadvantage:
• Drivers depends on the Database.

4.7. JDBC Packages


• The JDBC API is contained in two packages.
• The first package is called java.sql and contains core Java data objects of the JDBC API.
java.sql is part of the J2SE (Java2 Standard Edition)
• These include Java data objects that provide the basic for connecting to the DBMS and
interacting with data stored in the DBMS.
• The second package is javax.sql, which extends java.sql and is in J2EE. (Java2 Enterprise
Edition)
• javax.sql includes the data objects that interact with Java Naming and Directory Interface
(JNDI) and Java data objects that manage connection pooling, among other advanced JDBC
features related to Transaction management.

4.8. Talking to Database (JDBC Process Steps/A Brief Overview of the JDBC Process)
• Seven Basic Steps used in JDBC :

1. Load the Driver


2. Define the Connection URL
3. Establish the Connection
4. Create a Statement Object

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page


124
5. Execute a query
6. Process the results
7. Close the Connection

✓ Load the Driver


• When a driver class is first loaded, it registers itself with the driver Manager .
• Example:
• Class.forName(sun.jdbc.odbc.JdbcOdbcDriver);
• OR
• Class.forName(com.mysql.jdbc.Driver);

✓ Define the Connection URL :


• It contains the connection string / path to the database for communication.
• Syntax:
• jdbc:msql://host[:port]/database
• Example:
• jdbc:mysql://localhost:3306/db1

✓ Establish the Connection


• It establishes the connection with the database for communication.
• DriverManager Connects to given JDBC URL with given user name and password
• Throws java.sql.SQLException
• returns a Connection object
• A Connection represents a session with a specific database.
• The connection to the database is established by getConnection(),
Example:
try{
String url = “jdbc:mysql://localhost:3306/db1";
String userName = "root";
String password = "";
Connection con =DriverManager.getConnection(url, userName,
password);
con.close();
}catch(ClassNotFoundException e){
System.out.println("Class.forName = " + e);
}catch(SQLException e){
System.out.println("Driver.Manager = " + e);
}
✓ Create a Statement Object :
• It creates object to for query execution.
Example:
import java.sql.*;
Statement stat = con.createStatement();
✓ .Execute a query

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page


125
• It executes the query for update or to fetch data from database.
• The Statement methods are
❖ executeQuery() :for select query.
❖ executeUpdate () :for insert, update, delete queries.
❖ executeBatch() : is to execute set of queries
Example:
import java.sql.*;
Statement stat = con.createStatement();
String query = "select * from STD1";
ResultSet rs = stat.executeQuery(query);

✓ Process the results : (ResultSet)


• It retrieves data from database and displays data with the methods.
Example:
import java.sql.*;
Statement stat = con.createStatement();
String query = "select * from student";
ResultSet rs = stat.executeQuery(query);
while(rs.next()){
System.out.println("USN = " + rs.getInt(1));
// col number in select query
System.out.println("NAME=" + rs.getString(2));
}
• The ResultSet methods are
• - next/previous methods moves cursor from current row to
• next row or to previous row.
• - relative/absolute methods moves cursor to specific row
• from current row either upward or downward direction.
• But absolute moves to specific row from the 1st row.
• - getXxx ()are database column methods to retrieve data.
• Xxx represents column types like int, float etc
• - wasNull()- checks for column null and returns true.
• - findColumn()- returns column number.
• - getRow()- returns the row number.
✓ The ResultSet Meta data is to get description about database columns,
• The methods are
• getMetaData() returns about database.
• getColumnCount()- returns number of columns in a table.
• getColumnName ()-returns column name
• getColumnType()- returns column type
• isReadOnly()- returns true if column non editable.
• isSearchable()- returns true if column data be searched.
• isNullable()- returns true if column accepts null value.

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page


126
✓ Close the Connection:
It closes the connection to database.
Example:
import java.sql.*;
Connection con =
DriverManager.getConnection(url, userName,password);
con.close();

4.9. Statement object to executes the SQL Queries


• There are three types of Statement Objects.
1. Statement
2. Prepared Statement
3. Callable Statement

➢ Statement:
• The “SQL Query is compiled to DBMS FORMAT”.
• Each time query compiled and executed.
• The methods are:
✓ createStatement():
• It returns Statement object
• Syntax:
• Statement createStatement();
• Ex: Statement st = con.createStatement();
• The methods are:
✓ executeQuery():
• It executes select query(i.e. for Data retrieval)
• Syntax:
• ResultSet executeQuery(String query)
• Example:
• ResultSet rs=st.executeQuery(“selec * from student”);

✓ The methods are:


• executeUpdate():
• It executes insert, update, delete query.
• i.e. used for DML operations.
• Syntax:
• int executeUpdate(String query)
• Ex: String query=“insert into student values(1,’vinay’)”;
• int rowsaffected=st.executeQuery(query);
• It returns the number of rows affected after the execution of the query.
• Example Table: student
• executeUpdate(insert query): inserts tuples to the student table.
• executeQuery(select query): Retrieves values from the student table.
Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page
127
➢ PreparedStatement interface
• The PreparedStatement interface is a subinterface of Statement.
• It is used to execute parameterized query.
• String sql="insert into emp values(?,?,?)";
• Passing parameter for ? Positions.
• Its value will be set by calling the setter methods of PreparedStatement.
Why use PreparedStatement?
• Improves performance: The performance of the application will be faster, because query is
compiled only once.
How to get the instance of PreparedStatement?
• The prepareStatement() method of Connection interface is used.
• Class.forName(com.mysql.jdbc.Driver);
Connection con =DriverManager.getConnection(“jdbc:mysql://localhost:3306/dbname,
“root”,””);
• PreparedStatement stmt=con.prepareStatement("insert into student values(?,?)");
• stmt.setInt(1,100);
• stmt.setString(2,"Raghu");
• int i=stmt.executeUpdate();

➢ Callble Statement

• CallableStatement interface is used to call the stored procedures and functions.


• We can have business logic on the database by the use of stored procedures and functions
that will make the performance better because these are precompiled.
• Suppose to get the age of the studentbased on the date of birth, you may create a function
that receives date as the input and returns age of the student as the output.
• The prepareCall() method of Connection interface returns the instance of
• Syntax :
• public CallableStatement prepareCall("{ call procedurename(?,?...?)}");
• Example:
Creating stored procedure p1(): For inserting tuple into student table:
delimiter $$
create procedure p1(IN usn int,IN name varchar(20))
begin
insert into student values(usn,name);
end; $$

Creating stored procedure p2(): For Retrieving tuples from student table:
delimiter $$
create procedure p2()
begin
select * from student;
end; $$

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page


128
import java.sql.*;
public class JdbcDemo {
public static void main(String args[]){
try{

Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql:localhost:3306/db1”,”root”,"");

CallableStatement cs;
//For insertion
String sql=”call p1(?,?)”;
cs= con.prepareCall(sql);
cs.setInt(1,”10”);
cs.setString(2,”pavan”);
int row=cs.equecuteUpdate();
if(row==1)
{
System.out.println(“Row inserted successfully”);
}
else{
System.out.println(“Unable to insert row”);
}

//For Retreving all tuples from student table


String sql2=”call p2()”;
cs=con.prepareCall(sql2);
ResultSet rs1=cs.executeQuery(sql2);
while(rs1.next()){
System.out.println(“USN=”+rs1.getInt(1));
System.out.println(“Name=”+rs1.getString(2));
}

4.10. ResultSet

✓ The ResultSet object contains methods that are used to copy data from the ResultSet into a
Java collection object or variable for further processing.
✓ Data in a ResultSet is logically organized into a virtual table consisting of rows and columns.
✓ The ResultSet uses a virtual cursor to point to a row of the virtual table.
✓ The virtual cursor is positioned above the first row of data when the ResultSet is returned by
the executeQuery(). This means the virtual cursor must be moved to the first row using the
next() method.
✓ The next() returns a boolean true if the row contains data, else false.
✓ Once the virtual cursor points to a row, the getxxx() is used to copy data from the row to a
collection, object or a variable.
Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page
129
✓ Example:

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

Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql:localhost:3306/db1”,”root”,"");
PreparedStatement pstmt;

pstmt= con.prepareStatement("select * from student");


ResultSet rs1=pstmt.executeQuery();
while(rs1.next()){
System.out.println(“USN=”+rs1.getInt(1));
System.out.println(“Name=”+rs1.getString(2));
}
} // end of try
catch(Exception e){System.out.println("exception"); }
} //end of main
} // end of class

➢ Scrollable ResultSet:
✓ In JDBC 2.1 API the virtual cursor can be moved backwards or positioned at a specific
row.
✓ Six methods are there for Resultset object.
✓ They are first(), last(), previous(), absolute(), relative() and getrow().
✓ first() Moves the virtual cursor to the first row in the Resultset.
✓ last() Positions the virtual cursor at the last row in the Resultset
✓ previous() Moves the virtual cursor to the previous row.
✓ absolute() Positions the virtual cursor to a specified row by the an integer value
passed to the method.
✓ relative() Moves the virtual cursor the specified number of rows contained in the
parameter. The parameter can be positive or negative integer.
✓ getRow() Returns an integer that represents the number of the current row in the
Resultset.
✓ To handle the scrollable ResultSet , a constant value is passed to the Statement object that
is created using the createStatement(). Three constants.
✓ TYPE_FORWARD_ONLY restricts the virtual cursor to downward movement
✓ TYPE_SCROLL_INSENSITIVE and TYPE_SCROLL_SENSITIVE (Permits the
virtual cursor to Move in any direction)
Example:

try {
Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page
130
String query = "select * from student";
Statement stmt;
ResultSet rs;
stmt = con.createStatement();
rs = stmt.executeQuery (query);

rs.first();
System.out.println(“USN=>”+rs.getInt(1) +”Name=>”+ rs. getString (2)+”Row
Number=>”+rs.getRow());

rs.previous();
System.out.println(“USN=>”+rs.getInt(1) +”Name=>”+ rs. getString (2)+”Row
Number=>”+rs.getRow());

rs.absolute(10);
System.out.println(“USN=>”+rs.getInt(1) +”Name=>”+ rs. getString (2)+”Row
Number=>”+rs.getRow());

rs.relative(-2);
System.out.println(“USN=>”+rs.getInt(1) +”Name=>”+ rs. getString (2)+”Row
Number=>”+rs.getRow());

rs.relative(2);
System.out.println(“USN=>”+rs.getInt(1) +”Name=>”+ rs. getString (2)+”Row
Number=>”+rs.getRow());

stmt.close();}catch ( Exception e ){}

➢ Update ResultSet :
Updatable ResultSet methods are
a. updateRow()
b. insertRow()
c. deleteRow()

a. updateRow in ResultSet:
✓ Once the executeQuery() of the Statement object returns a ResultSet, the updatexxx()
is used to change the value of column in the current row of the ResultSet.
✓ The xxx in the updatexxx() is replaced with the data type of the column that is to be
updated. Note: updatexxx() updateString(), updateInt()
✓ The updatexxx() requires two parameters. The first is either the number or name of the
column of the ResultSet that is being updated and the second is the value that will
replace the value in the column of the ResultSet.
✓ A value in a column of the ResultSet can be replaced with a NULL value by using the
updateNull().
✓ It requires one parameter, which is the number of column in the current row of the
ResultSet. The updateNull() don‟t accept name of the column as a parameter.

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page


131
✓ Note: The updateRow() is called after all the updatexxx() are called.
✓ Example:
ResultSet rs=cs.executeQuery(sql);
rs.next();
rs.updateString(2,"Harsha");
rs.updateRow();

Delete Row in the ResultSet :


✓ The deleteRow() is used to remove a row from a ResultSet.
✓ The deleteRow() is passed an integer that contains the number of the row to be
deleted.
✓ First use the absolute() method to move the virtual cursor to the row in the Resultset
that should be deleted.
✓ The value of that row should be examined by the program to assure it is the proper row
before the deleteRow() is called.
✓ The deleteRow() is then passed a zero integer indicating that the current row must be
deleted.
Example:
✓ rs.deleteRow();

Insert Row in the ResultSet :


✓ Inserting a row into the ResultSet is accomplished using basically the same technique
as is used to update the ResultSet.
✓ The updatexxx() is used to specify the column and value that will place into the
column of the ResultSet.
✓ The insertRow() is called after the updatexxx(), which causes a new row to be inserted
into the ResultSet.
✓ Example:

rs.updateInt(1,10);
rs.updateString(2,"abhi");
rs.updateInt(3, 99);
rs.insertRow();

✓ Example:
public class demo_updatable_Resultset {
public static void main(String args[]) throws ClassNotFoundException,
SQLException{

Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/stfdb","root","");

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page


132
//For updateRow() demo
String sql="select * from student where name='vinay'";
Statement
cs=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR
_UPDATABLE);

ResultSet rs=cs.executeQuery(sql);
rs.next();
System.out.println("Before updating Name in the ResultSet object:"+rs.getString(2));

rs.updateString(2,"Harsha");
rs.updateRow();
System.out.println("After updating Name in the ResultSet object:"+rs.getString(2));

//For deleteRow() demo


sql="select * from student where name='Harsha'";
rs=cs.executeQuery(sql);
rs.next();
System.out.println("Before updating Name in the ResultSet object:"+rs.getString(2));
rs.deleteRow();
//System.out.println("After updating Name in the ResultSet object:"+rs.getString(2));
}
}

4.11. JDBC - Data Types


The JDBC driver converts the Java data type to the appropriate JDBC type, before sending it to the
database. It uses a default mapping for most data types. For example, a Java int is converted to an
SQL INTEGER. Default mappings were created to provide consistency between drivers.

The following table summarizes the default JDBC data type that the Java data type is converted to,
when you call the setXXX() method of the PreparedStatement or CallableStatement object or the
ResultSet.updateXXX() method.

SQL JDBC/Java setXXX getXXX

VARCHAR java.lang.String setString getString

CHAR java.lang.String setString getString

LONGVARCHAR java.lang.String setString getString

BIT boolean setBoolean getBoolean

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page


133
NUMERIC java.math.BigDecimal setBigDecimal getBigDecimal

TINYINT byte setByte getByte

SMALLINT short setShort getShort

INTEGER int setInt getInt

BIGINT long setLong getLong

REAL float setFloat getFloat

FLOAT float setFloat getFloat

DOUBLE double setDouble getDouble

VARBINARY byte[ ] setBytes getBytes

BINARY byte[ ] setBytes getBytes

DATE java.sql.Date setDate getDate

TIME java.sql.Time setTime getTime

TIMESTAMP java.sql.Timestamp setTimestamp getTimestamp

CLOB java.sql.Clob setClob getClob

BLOB java.sql.Blob setBlob getBlob

ARRAY java.sql.Array setARRAY getARRAY

REF java.sql.Ref SetRef getRef

STRUCT java.sql.Struct SetStruct getStruct

4.12. Advanced JDBC data types


JDBC 3.0 has enhanced support for BLOB, CLOB, ARRAY, and REF data types. The ResultSet
object now has updateBLOB(), updateCLOB(), updateArray(), and updateRef() methods that enable
you to directly manipulate the respective data on the server.

The setXXX() and updateXXX() methods enable you to convert specific Java types to specific
JDBC data types. The methods, setObject() and updateObject(), enable you to map almost any Java
type to a JDBC data type.

ResultSet object provides corresponding getXXX() method for each data type to retrieve column
value. Each method can be used with column name or by its ordinal position.

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page


134
4.13. Transaction Processing
(Explain Transaction processing or Batch processing with examples including I/O table.)

A transaction may involve several tasks.


A database transaction consists of a set of SQL statements, each of which must be successfully
completed for the transaction to be completed. If anyone fails, then the transaction must be rolled
back.
The database transaction is not completed until the J2EE component calls the commit() method of the
Connection object.
The commit() method must be called regardless if the SQL statement is part of a transaction or not.
The commit() method was automatically called in the previous examples because the DBMS has an
AutoCommit feature that is by default set to true.
If a J2EE component is processing a transaction, the AutoCommit feature must be deactivated by
calling the setAutoCommit() method and passing it a false parameter.
Once the transaction is completed, the setAutoCommit() method is called again by passing a true
parameter
The J2EE component can control the number of tasks that are rolled back by using savepoints.
There can be many savepoints used in transactions. Each savepoint is identified by a unique name.
The savepoint name is then passed to the rollback() method to specify the point within the
transaction where the rollback is to stop.
executeBatch: Executes more than one Query.
int executeBatch()
BatchUpdateException: handles BatchUpdate Exception
Rollback: Un does the transaction from current to previous or starting point
(or Savepoint mark)
Syntax: rollback(String savepointmark)
clearBatch: Removes set of queries
syntax: clearBatch()

Example:student2
Usn name
1 aaa

public class transaction_batch_processing {


public static void main(String args[]) throws ClassNotFoundException, SQLException{
Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/stfdb","root","");

String query1="insert into student2 values(2,'rajath')";


String query2="insert into student2 values(3,'abhishek')";
Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page
135
con.setAutoCommit(false);

Savepoint sp=con.setSavepoint("sp1");
PreparedStatement ps=con.prepareStatement(query1);
ps.addBatch(query1);

ps.addBatch(query2);
ps.executeBatch();

String query3="select * from student2";


ps=con.prepareStatement(query3);
ResultSet rs=ps.executeQuery();
System.out.println("After 2 insert Query Execution but before commit--- Table Contents
are:");
while(rs.next())
{
System.out.println("USN=>:"+rs.getInt(1)+"Name=>"+rs.getString(2));
}

con.rollback(sp);

String query4="select * from student2";


ps=con.prepareStatement(query4);
rs=ps.executeQuery();
System.out.println("After Rollback Table Contents are:");
while(rs.next())
{
System.out.println("USN=>:"+rs.getInt(1)+"Name=>"+rs.getString(2));
}

}
}

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page


136
Module-5
EJB and Server Side Component Models

5.1. Introduction to EJB


• Problem Domain: A good software must possess following charfacteristics.
✓ Secure
✓ Maintains integrity
✓ Scalable
✓ Interoperable
✓ Robust
✓ Correct/functions as specified

Breakingup Responsibilities:
1.Core concerns:
• Represents application’s business logic
• The set of rules that dictate its expected behavior.
• Ex: Interest calculation in banking domain
2.Cross-cutting concerns:
• Represents secondary operations necessary to keep things running correctly and efficiently.
• Ex: Security assertions, transactional boundaries, concurrency policies
3.Plumbing:
• Deals with Routing the request from one point to other point. (Component to component)
• Ex 1.Forwarding control from an HTTP request to some action handler
• Ex2:Obtaining a JDBC connection.

5.2. The Enterprise JavaBeans (EJB)


• EJB stands for Enterprise Java Beans.
• EJB is an essential part of a J2EE platform.
• It is an architecture for the development and deployment of component-based busines
applications .
• Applications developed using Enterprise JavaBeans architecture are scalable, transactional,
and multi-user secure.
• These applications may be written once, and then deployed on any server platform that
supports the Enterprise JavaBeans specification.
• The EJB supports the philosophy of “write once, run anywhere”.
• “Enterprise JavaBeans is a standard server-side component model for distributed business
applications”.
• Package used is: - javax.ejb
• EJB provides an architecture to develop and deploy component based enterprise applications
considering robustness, high scalability, and high performance.

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page


137
Benefits/Advantages of EJB:
• Simplified development of large-scale enterprise level application.
• Application Server/EJB container provides most of the system level services like transaction
handling, logging, load balancing, persistence mechanism, exception handling, and so on.
• Developer has to focus only on business logic of the application.
• EJB container manages life cycle of EJB instances, thus developer needs not to worry about
when to create/delete EJB objects.
✓ EJBs are reusable components.
Component Types
• Each component contains the business logic developed with the intention of “reusability and
extensibility”.
• These business components/objects developed with the help of POJO (Plain Old Java Objects)
classes.
• POJO class is just like any other class, it does not become an EJB until it’s:
✓ Assembled/packaged
✓ Deployed
✓ Accessed via the Container

5.3. Server-Side Component Types (or) (Types of EJB’s)

1. Session Bean:
✓ Stateless Session Bean
✓ Statefull Session Bean
✓ Singleton Session Bean
2. Message Driven Bean:
✓ Component Managed Message Driven Bean (CMP)
✓ Bean Managed Message Driven Bean (BMP)
3. Entity Bean
Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page
138
➢ Session Bean:
• It is Short lived object.
• Session bean instance not shared between multiple clients.
• Data is not maintained in the DataBase.
• It is Non persistence.
• Session bean stores data of a particular user for a single session.
• Session bean gets destroyed as soon as user session terminates.
• It is less resource intensive as compared to entity bean.
• Session bean fig:

✓ Declaration:
• public interface SessionBean extends EnterpriseBean { ... }
✓ Methods:
• void ejbActivate() throws EJBException,java.rmi.RemoteException
• The Session Object / instance Acquires / reacquires resources.
• void ejbPassivate()throws EJBException,java.rmi.RemoteException
• The Session Object / instance
❖ Releases resources
❖ State Stored by container
• void ejbRemove()throws EJBException,java.rmi.RemoteException
• Session Object / instance
❖ Terminated / removed when Invoked Client (manually) after Time out
(Automatic)
❖ Instance removed by the container
• void setSessionContext(SessionContext ctx)
throws EJBException,java.rmi.RemoteException
• Sets SessionContext reference, Called after Instance created
• ejbCreate() :ejbCreate() methods are called by the container when a client invokes the
corresponding create() method on the bean’s home

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page


139
✓ First time Client’s Requests:
❖ Create bean
❖ Activate bean
❖ Process bean
❖ Passivate bean
✓ Second time if same Client’s Requests, logs out:
❖ Activate bean
❖ Process bean
❖ Passivate bean
❖ Remove bean

5.4. Stateless session bean


• It is a business object that represents business logic only. It doesn't have state (data).
• conversational state between multiple method calls is not maintained by the EJB container
• The stateless bean objects are pooled by the EJB container to service the request on demand.
• It can be accessed by one client at a time.
• In case of concurrent access, EJB container routes each request to different instance.

An SLSB Instance Selector picking an instance at random

✓ Stateless Beans Random assignment of a bean object for every Client request

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page


140
✓ Callback Annotaions Used in Stateless Session Bean
@PostConstruct: Invoked when a bean is created for the first time.
@PostDestroy: Invoked when a bean is removed from the bean pool or destroyed.

✓ Stateless session bean-Life cycle


• It Doesn’t preserve the conversational state with client.
• No instance variables present, only methods and local variables are present.
• State not maintained between the multiple clients.
• Single bean object processes more than one client’s request.
• No dedicated object for same client’s requests.
• State not persistent across the client’s request process
• Bean pool available.
• Requires less memory.
• Requires less bean objects.
• State cannot be persisted in database.

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page


141
5.5. Statefull Session Bean
• It preserve the conversational state with client.
• State maintained using “instance variables”.
• State maintained between the multiple clients.
• Single bean object processes only one client’s request.
• Dedicated object for same client’s requests.
• Persistent state across the client’s request process
• Bean pool not available.
• Requires more memory.
• Requires more bean objects.
• Bean objects are limited due to availability of memory.
• State can be persisted in database.

✓ Statefull Session Bean-Life cycle


The following figure illustrates the stages that a session bean passes through during its
lifetime. The client initiates the lifecycle by obtaining a reference to a stateful session bean.
The container performs any dependency injection and then invokes the method annotated
with @PostConstruct, if any. The bean is now ready to have its business methods invoked by
the client.

Fig:Statefull Session bean life cycle

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page


142
Statefull session bean one bean instance is dedicatedly assigned to each client

Sateful session bean instance selection by session Id:

✓ Stateful Session Bean-Life cycle (Fig. with callback methods)

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page


143
✓ Callback Annotations used in Statefull session bean
@PostConstruct-Invoked when a bean is invoked for the first time.
@PreDestroy-Invoked when a bean is removed from the bean pool or is destroyed.
@PostActivate-Invoked when a bean is loaded to be used
@PostPassivate-Invoked when a bean is put back to bean pool.

5.6. Singleton session bean


• One instance per application, it is shared between clients and supports concurrent access.
• A Singleton Session Bean maintains the state of the bean for the complete lifecycle of the
application.
• Only one instance of the Singleton Session Bean is created in the whole application and does
not terminates until the application is shut down.
• Singleton session – only one bean instance accessed by all Clients.
Fig. Singleton session bean:

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page


144
5.7. Message Driven Bean
• A message driven bean (MDB) is a bean that contains business logic.
• It is invoked by passing the message. So, it is like JMS Receiver.
• MDB asynchronously receives the message and processes it.
• Message driven bean receives message from queue or topic.
• Fig. Message driven bean:

• To create the message driven bean-


✓ Declare @MessageDriven annotation and implement MessageListener interface.

➢ JMS (Java Messaging Service)


• JMS (Java Message Service) is an API that provides the facility to create, send and read
messages.
• It provides reliable and asynchronous communication.
• Messaging is a technique to communicate applications or software components.
• JMS is mainly used to send and receive message from one application to another.
Advantage of JMS
• Asynchronous: To receive the message, client is not required to send request. Message will
arrive automatically
• Reliable: It provides assurance that message is delivered. to the client.
• There are two types of messaging domains in JMS.
• Point-to-Point Messaging Domain
• Publisher/Subscriber Messaging Domain
✓ Point-to-Point Messaging Domain
▪ In PTP model, one message is delivered to one receiver only.
▪ Queue is used as a message oriented middleware (MOM).
▪ The Queue is responsible to hold the message until receiver is ready.
▪ In PTP model, there is no timing dependency between sender and receiver.

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page


145
Fig. Point-to-Point Messaging Domain

✓ Publisher/Subscriber (Pub/Sub) Messaging Domain


In Pub/Sub model, one message is delivered to all the subscribers. It is like broadcasting.
Topic is used as a message oriented middleware that is responsible to hold and deliver
messages.
Fig. Publisher/Subscriber (Pub/Sub) Messaging Domain

✓ Life cycle of Message Driven Bean

The EJB container usually creates a pool of message-driven bean instances. For each instance, the
EJB container performs these tasks.

• If the message-driven bean uses dependency injection, the container injects these references
before instantiating the instance.
• The container calls the method annotated @PostConstruct, if any.

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page


146
Like a stateless session bean, a message-driven bean is never passivated and has only two states:
nonexistent and ready to receive messages.At the end of the lifecycle, the container calls the method
annotated @PreDestroy, if any. The bean’s instance is then ready for garbage collection.

Fig. Life cycle of Message Driven Bean

5.8. EJB and Persistence or (Entity Bean)


• Enetrprise bean which represent persistent data stored in a storage medium, such as a
relational database.
• Persistence across multiple sessions and can be accessed by multiple clients.
• Each instance of an entity eban represent a row in the table.
• EJB container creates the instance of an entity bean and is reponsible for loading data in an
instance and storing the information i.e. data back into the database.
• Entity bean is a simple POJO having mapping with table.
• Persistence:
❖ Persistence implies its state exists even after Client stops accessing an application.
❖ The persistent data remain intact even after storage shuts down.
❖ The persistence mechanism helps to perform database manipulations,such as
serialization,ORM (Object to Relationship mapping to Relational database) and
support for JDBC.
Following are the key actors in persistence API
❖ Entity − A persistent object representing the data-store record. It is good to be serializable.
❖ EntityManager − Persistence interface to do data operations like add/delete/update/find on
persistent object(entity). It also helps to execute queries using Query interface.
❖ Persistence unit − Persistence unit describes the properties of persistence mechanism.
❖ Data Source − Data Source describes the data-store related properties like connection url.
user-name,password etc

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page


147
• Life cycle of an Entity Bean
An entity bean has the following three states:
▪ Does not exist. In this state, the bean instance simply does not exist.
▪ Pooled state . When WebLogic server is first started, several bean instances are
created and placed in the pool. A bean instance in the pooled state is not tied to
particular data, that is, it does not correspond to a record in a database table.
Additional bean instances can be added to the pool as needed, and a maximum number
of instances can be set.
▪ Ready state. A bean instance in the ready state is tied to particular data, that is, it
represents an instance of an actual business object.

Fig. Life cycle of an Entity Bean

✓ EJB Entity Relationships

EJB 3.0 provides option to define database entity relationships/mappings like one-to-one, one-to-
many, many-to-one, and many-to-many relationships.
Following are the relevant annotations −
• One-to-One − Objects have one-to-one relationship. For example, a student having only one
library card.
• One-to-Many − Objects have one-to-many relationship. For example, a course can have
multiple subjects.

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page


148
• Many-to-One − Objects have many-to-one relationship. For example, many students joins
for a course.
• Many-to-Many − Objects have many-to-many relationship. For example, a book can have
multiple authors and an author can write multiple books.

5.9. Container services


While server-side component types handle business logic and entities address state, the EJB
Container can continue to make our jobs easier by providing a wide range of generic and configurable
services. Enterprise applications generally handle a large number of concurrent users, and each
request might need to be handled carefully so it does not violate the security or integrity of the
application. Additionally, we shouldn’t waste our time wiring our modules together; the container can
do this for us.
EJB offers a range of container services
Security - addresses the need to authorize and authenticate users uniformly across the application.
Not all requests should be given carte blanche access to the whole application, and this is EJB’s
mechanism to declaratively or programmatically restrict access.
Injection -allows our modules to communicate with one another without
the explicit need to perform service lookups. We can also use injection to define dependency
relationships between resources.
Transactions - ensure that our application’s state maintains its integrity while under load from
concurrent use. Although traditionally this is a very difficult paradigm to achieve manually. EJB
provides us with a declarative syntax to guard our business logic methods and, by extension,
associated resources such as the EntityManager.
Interceptors - are a generic utility for defining your own application logic to be applied in a cross-
cutting manner. This is a powerful way to promote code reuse, and it’s built into the platform.

Maharaja Institute of Technology Mysore Department of Master of Computer Applications Page


149

You might also like