ADWT
ADWT
J2EE Platform
J2EE Components J2EE applications are made up of components. A J2EE component
is a self-contained functional software unit that is assembled into a J2EE application with its
related classes and files and that communicates with other components. The J2EE
specification defines the following J2EE components:
Application clients and applets are components that run on the client.
• Java Servlet and JavaServer Pages™ (JSP™) technology components are Web
components that run on the server.
• Enterprise JavaBeans™ (EJB™) components (enterprise beans) are business
components that run on the server.
J2EE components are written in the Java programming language and are compiled in
the same way as any program in the language.
The difference between J2EE components and “standard” Java classes is that J2EE
components are assembled into a J2EE application, verified to be well formed and in
compliance with the J2EE specification.
The J2EE platform uses a set of defined roles to conceptualize the tasks related to the various
workflows in the development and deployment life cycle of an enterprise application. These
role definitions provide a logical separation of responsibilities for team members involved in
the development, deployment, and management of a J2EE application
Implementation in Java
What is IDE?
• An integrated development environment (IDE) is a software application that provides
comprehensive facilities to computer programmers for software development.
• An IDE normally consists of at least a source code editor, build automation tools and
a debugger.
• Some IDEs, such as NetBeans and Eclipse, contain the
necessary compiler, interpreter, or both
J2EE Platform
• A distributed application sever environment
• Provides
➢ APIs– Programming model
➢ Runtime Infrastructure-For hosting and managing applications
Enterprise Architecture Styles:
• Two-Tier Architecture
• Three-Tier Architecture
• Multitier Architecture
• J2EE Architecture
Two Tier Architecture
• The two-tier architecture is also known as the client/server architecture.
• It consists mainly of two tiers:
data & client (GUI).
• The application logic can be located in:
➢ client tier which results in a fat client or
➢ in the data tier which results in a fat server
Two Tier Architecture
3- tier schema is an extension of the 2-tier architecture. 3-tier architecture has following layers
The first tier is referred to as the presentation layer, and consists of the application
GUI.The middle tier, or the business layer, consists of the business logic to retrieve data
for the user requests.The back-end tier, or data layer, consists of the data needed by the
application.
This DBMS architecture contains an Application layer between the user and the DBMS,
which is responsible for communicating the user's request to the DBMS system and send the
response from the DBMS to the user.The application layer(business logic layer) also
processes functional logic, constraint, and rules before passing data to the user or down to the
DBMS.Three tier architecture is the most popular DBMS architecture.
as such, these services are delivered at top capacity. The “N” in the name n-tier architecture
refers to any number from 1.
N-tier architecture would involve dividing an application into three different tiers. These
would be the
1. logic tier,
2. the presentation tier, and
3. The data tier.
Enterprise Architecture:
• Generic interfaces are used
• Only objects are modified not the interface
J2EE Architecture
Cookie
• An HTTP cookie (also called web cookie, Internet cookie, browser cookie, or
simply cookie) is a small piece of data stored on the user's computer by the web
browser while browsing a website.
• Cookies were designed to be a reliable mechanism for websites to
remember stateful information (such as items added in the shopping cart in an online
store) or to record the user's browsing activity
J2EE Runtime
• Applications use interfaces to interact with the runtime. There is a clear demarcation
between applications and runtime infrastructure
• Long Term and Short term demands:
– Short term demands ->Short lived internet designs
– Long term demands->Maintainable and reusable
• J2EE is more flexible to build applications including long term and short term
demands
• Layers in J2EE architecture are loosely coupled
• Highly extendable implementation
• J2EE architecture provides uniform means of accessing platform level services via its
runtime environment
• Before J2EE distributed computing was client-server based.
– Server-> implements the interface
– Client->Connect to server
– Eg. CORBA is a distributed application (IDL generates stubs on the client side
and skeletons on the server side)
J2EE Runtime
Enterprise services
• Transaction processing
• Database access
• Messaging
• Multithreading
Distributed transactions needs these services
• To access the above services we need plumbing code or middleware solutions using
APIs
• Server side resources are scarce. We need to concentrate on server side resources:
threads, security, transactions, and database connections
• J2EE is the solution that meets all the above requirements
• It is a platform having built-in solution to meet all the needs
• J2EE does not specify the nature and structure of runtime instead it introduces the
container
6. Java Transaction API (JTA): The Java™ Transaction API (JTA) allows
applications to perform distributed transactions, that is, transactions that access and
update data on two or more networked computer resources.
7. Java Mail : The JavaMail API provides a platform-independent and protocol-
independent framework to build mail and messaging applications.
8. JavaBeans Activation Framework: The JavaBeans Activation Framework (JAF)
is used by the JavaMail API. JAF provides standard services to determine the type of
an arbitrary piece of data, encapsulate access to it, discover the operations available
on it, and create the appropriate JavaBeans component to perform those operations.
9. Java API for XML parsing(JAXP): Java API for XML Processing. Java API for
XML Processing (JAXP) enables applications to parse, transform, validate and query
XML documents using an API that is independent of a particular XML processor
implementation.
10. Java Connector Architecture(JCA): The Java EE Connector Architecture (JCA)
defines a standard architecture for Java EE systems to external heterogeneous
Enterprise Information Systems (EIS). Examples of EISs include Enterprise Resource
Planning (ERP) systems, mainframe transaction processing (TP), databases and
messaging systems.
11. Java Authentication and Authorization service(JAAS): JAAS provides subject-
based authorization on authenticated identities.
J2SE APIs
• Java IDL API: Java IDL technology adds CORBA (Common Object Request Broker
Architecture) capability to the Java platform, providing standards-based
interoperability and connectivity. Java IDL enables distributed Web-enabled Java
applications to transparently invoke operations on remote network services using the
industry standard IDL (Object Management Group Interface Definition Language)
and IIOP (Internet Inter-ORB Protocol) defined by the Object Management Group.
Runtime components include a Java ORB for distributed computing using IIOP
communication.
• JDBC Core API: Provides the API for accessing and processing data stored in a data
source (usually a relational database) using the Java programming language.
• RMI-IIOP API: Java Remote Method Invocation over Internet Inter-ORB Protocol
technology ("RMI-IIOP") is part of the Java Platform, Standard Edition (Java SE).
The RMI Programming Model enables the programming of CORBA servers and
applications via the rmi API
• JNDI API: The Java Naming and Directory Interface (JNDI) provides naming and
directory functionality to applications written in the Java programming language. It is
designed to be independent of any specific naming or directory service
implementation.
Container Architecture
Application Components:
• Servlets
• JSP
• EJB
•
Deployment Descriptors
• Component contract
• Container service APIs
• Declarative services
• Other container services
Application Components:
• Servlets
• JSP
• EJB
Deployment Descriptors
• It is an XML file that describes application components
Architecture Container: can be divided into 4 parts
• Component contract
• Container service APIs
• Declarative services
• Other container services
Component contract:
• A set of APIs specified by the container which are commonly required to extend or
implement
• Basic purpose of container is to provide a runt time for application clients
• Instance of application components are created and invoked within JVM of the
container
• This makes container responsible for managing life cycle of application components
and they are required to abide by certain contracts specified by the container.
• Eg. Java applet downloaded by browser and instantiated and initialized in browser’s
JVM
• However the components are required to implement certain interfaces or classes,
• Eg. Java.applet.Applet(Class)->init(),start(), stop(), destroy() methods
J2EE application components are remote to clients. Client can’t directly call methods
on components
Client makes request to application server and it is container that actually invokes
methods. Application components are required to follow contract specified by the container
Goals of RMI
• To minimize the complexity of the application.
• To preserve type safety.
• Distributed garbage collection.
• Minimize the difference between working with local and remote objects.
• Get the RMI registry using the getRegistry() method of the LocateRegistry class
which belongs to the package java.rmi.registry.
• Fetch the object from the registry using the method lookup() of the
class Registry which belongs to the package java.rmi.registry.
• To this method, you need to pass a string value representing the bind name as a
parameter. This will return you the remote object.
• The lookup() returns an object of type remote, down cast it to the type Hello.
• Finally invoke the required method using the obtained remote object.
RMI Client code:
Step 2: Compile all the java files in the RMI directory (*.java)
Step 3: Start the rmi registry
JNDI Overview:
• The Java Naming and Directory Interface (JNDI) is an application programming
interface (API) that provides naming and directory functionality to applications
written using the Java programming language.
• It is defined to be independent of any specific directory service implementation.
• Thus a variety of directories--new, emerging, and already deployed--can be accessed
in a common way.
What is a Naming Service?
• Naming service is a service that enables the creation of standard name for given set of
data
• On internet each host has a Fully Qualified domain Name (FQDN)
• Eg. www. apress.com
➢ Host name: www
➢ Domain name: apress.com
What is a Directory Service?
• In computing, directory service or name service maps the names of network
resources to their respective network addresses.
• It is a shared information infrastructure for locating, managing, administering and
organizing everyday items and network resources, which can include volumes,
folders, files, printers, users, groups, devices, telephone numbers and other objects.
• A directory service is a critical component of a network operating system.
• A directory server or name server is a server which provides such a service.
• Each resource on the network is considered an object by the directory server.
Information about a particular resource is stored as a collection
of attributes associated with that resource or object.
Directory Service
• A directory service defines a namespace for the network.
• The namespace is used to assign a name (unique identifier) to each of the objects.
• Directories typically have a set of rules determining how network resources are
named and identified, which usually includes a requirement that the identifiers be
unique and unambiguous.
• When using a directory service, a user does not have to remember the physical
address of a network resource; providing a name locates the resource.
• Some directory services include access control provisions, limiting the availability of
directory information to authorized users.
General Purpose Directory Services:
• Novell Directory Service(NDS)-file and print server
• Network information Service (NIS)-email in Linux
• Active Directory Service(ADS)-file encryption, remote desktop service, sharepoint
service
• Windows NT Domain-MS office
Drawbacks:
• Used only for specific purpose
• Lack of security
• No standard API
JNDI Architecture:
• The JNDI architecture consists of an API and a service provider interface (SPI).
• Java applications use the JNDI API to access a variety of naming and directory
services.
• The SPI enables a variety of naming and directory services to be plugged in
transparently, thereby allowing the Java application using the JNDI API to access
their services.
• 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. It is not written
entirely in java.
Native API Driver Architecture
• Example:
• Class.forName("com.mysql.jdbc.Driver");
DriverManager class
• can manage multiple drivers
• Each driver has to register with DriverManager class
• In JDBC we load database driver using java.lang.Class loader object
• At runtime classloader locates and loads the driver from the class path using bootstrap
class loader
Step 2: Create the connection object
• The getConnection() method of DriverManager class is used to establish connection
with the database.
• Syntax:
1) public static Connection getConnection(String url)throws SQLException
2) public static Connection getConnection(String url,String name,String password) throws
SQLException
• Example
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/stud","root","");
Establishing a Connection: java.sql.Connection interface:
• getArray()
• getBlob()
• getBoolean()
• getInt()
• getDate()
• getByte()
• getLong()
• getString()
• getDouble()
• getObject()
getTime
Step 5 :Close the connection object
• By closing connection object statement and ResultSet will be closed automatically.
• The close() method of Connection interface is used to close the connection.
• Syntax: public void close()throws SQLException
• Example: con.close()
JDBC Connectivity using Type 1 – JDBC ODBC Driver
Create a database Student
JDBC Connectivity using Type 1 – JDBC ODBC DriverCreate new data source
4. Select the Libraries folder and right click and select Add Jar/folder and browse the path:
A dialog box opens Navigate to the path mentioned above and select mysql-connector-java-
5.1.23-bin
5. Now press F6 and run the project. Output will be displayed in the console output
window
Prepared statements
• Creating parameterized statement such that data for parameters can be substituted
dynamically
• Creating statement involving data values that can always be represented as character
strings
• Pre-compiling SQL statement to avoid repeated compiling of same SQL statement
• Eg. Select * from <tab> where user_id=?
• If the value is not known then it is replaced by ‘?’ during runtime
• A PreparedStatement object can hold precompiled SQL statements
• Syntax:
public PreparedStatement prepareStatement(String query)throws SQLException{}
Java Script
JavaScript is a lightweight, interpreted programming language. It is designed for
creating network-centric applications. It is complimentary to and integrated with
Java. JavaScript is very easy to implement because it is integrated with HTML. It is open and
cross-platform.
Embedding Java Script In HTML:
JavaScript is embedded into HTML and XHTML documents using the <script> element. This
element can be used to embed the JavaScript directly into the web page (also known
as inline), or to specify an external file that contains the JavaScript.
The <script> element is used with a number of attributes:
• defer - used to inform the browser that the script associated with this <script> element
generates content (in other words the document.write() method is used). This can be
either true or false. The default setting (i.e. if this is not specified) is false.
• language - This argument is used to announce the version of JavaScript that is contained
within the corresponding <script> elements. This argument is now deprecated.
• src- Specifies URL of an external file containing the JavaScript. This argument overrides
any JavaScript contained within the body of this <script> element.
• type - Indicates to the browser the type of content contained within the <script> body.
This is typically be set to "text/javascript".
As with most HTML elements the <script> body must always be terminated with
the </script> element.
Example:
<script type="text/javascript">
// JavaScript code goes here
</script>
Example Program:
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Today's Date</title>
<script>
let d = new Date();
alert("Today's date is " + d);
</script>
</head>
<body>
</body>
</html>
Example Program:
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Today's Date</title>
</head>
<body>
<script>
let d = new Date();
document.body.innerHTML = "<h1>Today's date is " + d + "</h1>"
</script>
</body> </html>
Variables:
Variables in JavaScript are containers which hold reusable data. It is the basic unit of storage
in a program.
• The value stored in a variable can be changed during program execution.
• A variable is only a name given to a memory location, all the operations done on the
variable effects that memory location.
• In JavaScript, all the variables must be declared before they can be used.
Before ES2015, JavaScript variables were solely declared using the var keyword followed by
the name of the variable and semi-colon. Below is the syntax to create variables in
JavaScript:
var var_name;
var x;
The var_name is the name of the variable which should be defined by the user and should be
unique. These type of names are also known as identifiers. The rules for creating an
identifier in JavaScript are, the name of the identifier should not be any pre-defined
word(known as keywords), the first character must be a letter, an underscore (_), or a dollar
sign ($). Subsequent characters may be any letter or digit or an underscore or dollar sign.
We can initialize the variables either at the time of declaration or also later when we want to
use them. Below are some examples of declaring and initializing variables in JavaScript:
// declaring single variable
var name;
// declaring multiple variables
var name, title, num;
// initializng variables
var name = "Harsh";
name = "Rakesh";
console.log(globalVar);
console.log(localVar);
}
fun();
When we execute the function fun(), the output shows that both global as well as local
variables are accessible inside the function as we are able to console.log them. This shows
that inside the function we have access to both global variables (declared outside the
function) and local variables (declared inside the function).
let globalVar = "This is a global variable";
function fun() {
let localVar = "This is a local variable";
}
fun();
console.log(globalVar);
console.log(localVar);
JavaScript Literals:
// code here
}
};
Type Conversion
Most of the time, operators and functions automatically convert a value to the correct type.
That’s called “type conversion”.For example, alert automatically converts any value to a
string to show it. Mathematical operations convert values to numbers.There are also cases
when user need to explicitly convert a value to put things right.
For example, alert(value) does it to show the value. The conversion here is done
automatically. We can also use a call String(value) function for that conversion manually.
Number Conversion
We can use a Number(value) function to explicitly convert a value to Number. Like below:
If the string to be converted is not a valid number, the result of such conversion is NaN, for
example:
console.log(num); //NaN
Some other numeric conversion rules for explicit conversation are below
let str;
console.log(str); //undefined
console.log(num); //NaN
//null becomes 0
console.log(str); //null
console.log(num); //0
console.log(str1); //true
console.log(num1); //1
console.log(str2); //false
console.log(num2); //0
//In strings whitespaces from the start and the end are removed. Then, if //the remaining strin
g is empty, the result is 0. Otherwise, the number is //“read” from the string. An error gives N
aN if the string cannot be //converted.
console.log(num1); //0
console.log(num2); //123
console.log(num3); //NaN
Array:
JavaScript arrays are used to store multiple values in a single variable. An array is a special
variable, which can hold more than one value at a time.
Creating an Array
Syntax:
Example
var cars = ["Saab", "Volvo", "BMW"];
Example
var cars=[
"Saab",
"Volvo",
"BMW"
];
Using the JavaScript Keyword new
The following example also creates an Array, and assigns values to it:
Example
var cars = new Array("Saab", "Volvo", "BMW");
Access the Elements of an Array
cars[0] = "Opel";
Example
var cars=["Saab", "Volvo", "BMW"];
cars[0]= "Opel";
document.getElementById("demo").innerHTML = cars[0];
Access the Full Array
With JavaScript, the full array can be accessed by referring to the array name:
Example
var cars=["Saab", "Volvo", "BMW"];
document.getElementById("demo").innerHTML = cars;
Java Script Statements:
JavaScript statements are the commands to tell the browser to what action to perform.
Statements are separated by semicolon (;).
Example of JavaScript statement:
document.getElementById("demo").innerHTML = "Welcome";
Script Statements
2. If else The if statement is the fundamental control statement that allows JavaScript
to make decisions and execute statements conditionally.
4. do while Block of statements that are executed at least once and continues to be
executed while condition is true.
7. continue The continue statement tells the interpreter to immediately start the next
iteration of the loop and skip remaining code block.
8. break The break statement is used to exit a loop early, breaking out of the enclosing
curly braces.
9. function A function is a group of reusable code which can be called anywhere in your
programme. The keyword function is used to declare a function.
13. catch A block of statements that are executed when an error occur.
if statement
The if statement is the fundamental control statement that allows JavaScript to make
decisions and execute statements conditionally.
Syntax
The syntax for a basic if statement is as follows −
if (expression) {
Statement(s) to be executed if expression is true
}
Here a JavaScript expression is evaluated. If the resulting value is true, the given
statement(s) are executed. If the expression is false, then no statement would be not
executed. Most of the times, you will use comparison operators while making decisions.
<html>
<body>
Output
Qualifies for driving
Set the variable to different value and then try...
if...else statement
The 'if...else' statement is the next form of control statement that allows JavaScript to
execute statements in a more controlled way.
Syntax
if (expression) {
Statement(s) to be executed if expression is true
} else {
Statement(s) to be executed if expression is false
}
<html>
<body>
<script type = "text/javascript">
<!--
var age = 15;
The if...else if... statement is an advanced form of if…else that allows JavaScript to make a
correct decision out of several conditions.
Syntax
Switch statement
Syntax
The objective of a switch statement is to give an expression to evaluate and several different
statements to execute based on the value of the expression. The interpreter checks
each case against the value of the expression until a match is found. If nothing matches,
a default condition will be used.
switch (expression) {
case condition 1: statement(s)
break;
default: statement(s)
}
Example:
<html>
<body>
<script type = "text/javascript">
<!--
var grade = 'A';
document.write("Entering switch block<br />");
switch (grade) {
case 'A': document.write("Good job<br />");
break;
While Loop
Syntax
<html>
<body>
document.write("Loop stopped!");
//-->
</script>
ADVANCE JAVA PROG. RINKAL SARVAIYA
ADVANCE JAVA
Example:
<html>
<body>
<script type = "text/javascript">
<!--
var count = 0;
JavaScript Functions
JavaScript functions are used to perform operations. We can call JavaScript function many
times to reuse the code.
Function Example
<script>
function msg(){
alert("hello! this is message");
}
</script>
<input type="button" onclick="msg()" value="call function"/>
<script>
var add=new Function("num1","num2","return num1+num2");
document.writeln(add(2,5));
</script>
• Event Handling is a software routine that processes actions, such as keystrokes and mouse
movements.
• It is the receipt of an event at some event handler from an event producer and subsequent
processes.
Event Handlers
<html>
<head>
<scripttype="text/javascript">
functiontime()
{
vard=newDate();
var ty = d.getHours() + ":"+d.getMinutes()+":"+d.getSeconds();
document.frmty.timetxt.value=ty;
setInterval("time()",1000)
}
</script>
</head>
<bodyonload="time()">
<center><h2>DisplayingTime</h2>
<formname="frmty">
<inputtype=textname=timetxtsize="8">
</form>
</center>
</body>
</html>
<html>
<body>
<script>
functionvalidateform()
{
varuname=document.myform.name.value;
varupassword=document.myform.password.value;
if(uname==null||uname=="")
{
alert("Namecannotbeleftblank");
returnfalse;
}
elseif(upassword.length<6)
{
alert("Password must be at least 6 characters long.");
returnfalse;
}
}
functionemailvalidation()
{
vara=document.myform.email.value
if(a.indexOf("@")==-1)
{
alert("Pleaseentervalidemailaddress")
ADVANCE JAVA PROG. RINKAL SARVAIYA
ADVANCE JAVA
document.myform.email.focus()
}
}
</script>
<body>
<form name="myform" method="post" action="validpage.html" onsubmit="return
validateform()">
Email: <inputtype="text"size="20" name="email" onblur="emailvalidation()"><br>
UserName:<inputtype="text"name="name"><br>
Password:<inputtype="password"name="password"><br>
<inputtype="submit"value="Submit">
</form>
</body>
</html>
validpage.html //Filename
<html>
<body>
<scripttype="text/javascript">
alert("YouareaValidUser!!!");
</script>
</body>
</html>
Built-in Objects
• Built-in objects are not related to any Window or DOM object model.
• These objects are used for simple data processing in the JavaScript.
1. Math Object
<html>
<head>
<title>JavaScriptMathObjectMethods</title>
</head>
<body>
<scripttype="text/javascript">
varvalue=Math.abs(20);
document.write("ABSTestValue:"+value+"<br>");
varvalue=Math.acos(-1);
document.write("ACOSTestValue:"+value+"<br>");
varvalue=Math.asin(1);
document.write("ASINTestValue:"+value+"<br>");
varvalue=Math.atan(.5);
document.write("ATANTestValue:"+value+"<br>");
</script>
</body>
</html>
Output
ABSTestValue:20
ACOSTestValue:3.141592653589793
ASINTestValue:1.5707963267948966
ATAN Test Value : 0.4636476090008061
new Date()
new Date(year, month, day, hours, minutes, seconds, milliseconds)
new Date(milliseconds)
new Date(date string)
new Date()
new Date() creates a new date object with the current date and time:
Example
var d = new Date();
new Date(year, month, ...) creates a new date object with a specified date and time.
7 numbers specify year, month, day, hour, minute, second, and millisecond (in that order):
Example
var d = new Date(2018, 11, 24, 10, 33, 30, 0);
Example
var d = new Date(2018, 11, 24, 10, 33, 30);
Example
var d = new Date(2018, 11, 24, 10, 33);
Example
var d = new Date(2018, 11, 24, 10);
Example
var d = new Date(2018, 11, 24);
Example
var d = new Date(2018);
new Date(dateString)
Example
var d = new Date("October 13, 2014 11:13:00");
new Date(milliseconds)
new Date(milliseconds) creates a new date object as zero time plus milliseconds:
Example
var d = new Date(0);
1. Crawling
2. Rendering
3. Indexing
When Googlebot fetches a URL from the crawling queue by making an HTTP request it first
checks if you allow crawling. Googlebot reads the robots.txt file. If it marks the URL as
disallowed, then Googlebot skips making an HTTP request to this URL and skips the URL.
Googlebot then parses the response for other URLs in the href attribute of HTML links and
adds the URLs to the crawl queue. To prevent link discovery, use the nofollow mechanism.
Crawling a URL and parsing the HTML response works well for classical websites or server-
side rendered pages where the HTML in the HTTP response contains all content. Some
JavaScript sites may use the app shell model where the initial HTML does not contain the
actual content and Googlebot needs to execute JavaScript before being able to see the actual
page content that JavaScript generates.
Googlebot queues all pages for rendering, unless a robots meta tag or header tells Googlebot
not to index the page. The page may stay on this queue for a few seconds, but it can take
longer than that. Once Googlebot's resources allow, a headless Chromium renders the page
and executes the JavaScript. Googlebot parses the rendered HTML for links again and queues
the URLs it finds for crawling. Googlebot also uses the rendered HTML to index the page.
Servlets
Servlet technology is used to create a web application (resides at server side and generates a
dynamic web page).
Servlet technology is robust and scalable because of java language. Before Servlet, CGI
(Common Gateway Interface) scripting language was common as a server-side programming
language. However, there were many disadvantages to this technology. We have discussed
these disadvantages below.
There are many interfaces and classes in the Servlet API such as Servlet, GenericServlet,
HttpServlet, ServletRequest, ServletResponse, etc.
1. Better performance: because it creates a thread for each request, not process.
2. Portability: because it uses Java language.
3. Robust: JVM manages Servlets, so we don't need to worry about the memory
leak, garbage collection, etc.
4. Secure: because it uses java language.
The web container maintains the life cycle of a servlet instance. Let's see the life cycle of the
servlet:
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.
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.
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
HTTP is a protocol which allows the fetching of resources, such as HTML documents. It is the
foundation of any data exchange on the Web and it is a client-server protocol, which
HTTP protocol
HTTP is a protocol which allows the fetching of resources, such as HTML documents. It is the
foundation of any data exchange on the Web and it is a client-server protocol, which means
requests are initiated by the recipient, usually the Web browser. A complete document is
reconstructed from the different sub-documents fetched, for instance text, layout description,
images, videos, scripts, and more.
Basic Features
There are three basic features that make HTTP a simple but powerful protocol:
• HTTP is connectionless: The HTTP client, i.e., a browser initiates an HTTP request
and after a request is made, the client waits for the response. The server processes the
request and sends a response back after which client disconnect the connection. So
client and server knows about each other during current request and response only.
Further requests are made on new connection like client and server are new to each
other.
• HTTP is media independent: It means, any type of data can be sent by HTTP as
long as both the client and the server know how to handle the data content. It is
required for the client as well as the server to specify the content type using
appropriate MIME-type.
• HTTP is stateless: As mentioned above, HTTP is connectionless and it is a direct
result of HTTP being a stateless protocol. The server and client are aware of each
other only during a current request. Afterwards, both of them forget about each
other. Due to this nature of the protocol, neither the client nor the browser can retain
information between different requests across the web pages.
HTTP Servlet
If you creating Http Servlet you must extend javax.servlet.http.HttpServlet class, which is an
abstract class. Unlike Generic Servlet, the HTTP Servlet doesn’t override the service()
method. Instead it overrides one or more of the following methods. It must override at least
one method from the list below:
• doGet() – This method is called by servlet service method to handle the HTTP GET
request from client. The Get method is used for getting information from the server
• doPost() – Used for posting information to the Server
• doPut() – This method is similar to doPost method but unlike doPost method where we
send information to the server, this method sends file to the server, this is similar to the
FTP operation from client to server
• doDelete() – allows a client to delete a document, webpage or information from the
server
• init() and destroy() – Used for managing resources that are held for the life of the
servlet
• getServletInfo() – Returns information about the servlet, such as author, version, and
copyright.
In Http Servlet there is no need to override the service() method as this method dispatches the
Http Requests to the correct method handler, for example if it receives HTTP GET Request it
dispatches the request to the doGet() method.
Basic Architecture
The following diagram shows a very basic architecture of a web application and depicts
where HTTP sits:
Client
The HTTP client sends a request to the server in the form of a request method, URI, and
protocol version, followed by a MIME-like message containing request modifiers, client
information, and possible body content over a TCP/IP connection.
Server
The HTTP server responds with a status line, including the message's protocol version and a
success or error code, followed by a MIME-like message containing server information,
entity meta information, and possible entity-body content.
The Servlet API:
The javax.servlet and javax.servlet.http packages represent interfaces and classes for servlet
api.
The javax.servlet package contains many interfaces and classes that are used by the servlet
or web container. These are not specific to any protocol.
The javax.servlet.http package contains interfaces and classes that are responsible for http
requests only.
1. Servlet
2. ServletRequest
3. ServletResponse
4. RequestDispatcher
5. ServletConfig
6. ServletContext
7. SingleThreadModel
8. Filter
9. FilterConfig
10. FilterChain
11. ServletRequestListener
12. ServletRequestAttributeListener
13. ServletContextListener
14. ServletContextAttributeListener
1. GenericServlet
2. ServletInputStream
3. ServletOutputStream
4. ServletRequestWrapper
5. ServletResponseWrapper
6. ServletRequestEvent
7. ServletContextEvent
8. ServletRequestAttributeEvent
9. ServletContextAttributeEvent
10. ServletException
11. UnavailableException
1. HttpServletRequest
2. HttpServletResponse
3. HttpSession
4. HttpSessionListener
5. HttpSessionAttributeListener
6. HttpSessionBindingListener
7. HttpSessionActivationListener
8. HttpSessionContext (deprecated now)
1. HttpServlet
2. Cookie
3. HttpServletRequestWrapper
4. HttpServletResponseWrapper
5. HttpSessionEvent
6. HttpSessionBindingEvent
7. HttpUtils (deprecated now)
An object of ServletConfig is created by the web container for each servlet. This object can
be used to get configuration information from web.xml file. If the configuration information
is modified from the web.xml file, we don't need to change the servlet. So it is easier to
manage the web application if any specific content is modified from time to time.
Advantage of ServletConfig
The core advantage of ServletConfig is that you don't need to edit the servlet file if
information is modified from the web.xml file.
The init-param sub-element of servlet is used to specify the initialization parameter for a
servlet.
<web-app>
<servlet>
......
<init-param>
<param-name>parametername</param-name>
<param-value>parametervalue</param-value>
</init-param>
......
</servlet>
</web-app>
ServletContext::
object of ServletContext is created by the web container at time of deploying the project. This
object can be used to get configuration information from web.xml file. There is only one
ServletContext object per web application. If any information is shared to many servlet, it is
better to provide it from the web.xml file using the <context-param> element.
Advantage of ServletContext
Easy to maintain if any information is shared to all the servlet, it is better to make it
available for all the servlet. We provide this information from the web.xml file, so if the
information is changed, we don't need to modify the servlet. Thus it removes
maintenance problem.
There can be a lot of usage of ServletContext object. Some of them are as follows:
1. The object of ServletContext provides an interface between the container and servlet.
2. The ServletContext object can be used to get configuration information from the
web.xml file.
3. The ServletContext object can be used to set, get or remove attribute from the
web.xml file.
4. The ServletContext object can be used to provide inter-application communication.
HTTP Requests
The request sent by the computer to a web server, contains all sorts of potentially interesting
information; it is known as HTTP requests.
The HTTP client sends the request to the server in the form of request message which
includes following information:
o The Request-line
The HTTP request method indicates the method to be performed on the resource identified by
the Requested URI (Uniform Resource Identifier). This method is case-sensitive and
should be used in uppercase.
There are two ways the browser client can send information to the web server.
exit();
}
?>
<html>
<body>
</body>
</html>
It will produce the following result –
exit();
}
?>
<html>
<body>
</body>
</html>
It will produce the following result
UNIT- 4
Advanced Servlets
Approach to Session Tracking
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.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:
1. Cookies
2. Hidden Form Field
3. URL Rewriting
4. HttpSession
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.
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.
Types of Cookie
1. Non-persistent cookie
2. Persistent cookie
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
There are given some commonly used methods of the Cookie class.
Example:
index.html
<form action="servlet1" method="post">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>
FirstServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
out.close();
}catch(Exception e){System.out.println(e);}
}
}
SecondServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
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>s1</servlet-name>
<servlet-class>FirstServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>s2</servlet-name>
<servlet-class>SecondServlet</servlet-class>
</servlet>
servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>
</web-app>
In case of Hidden Form Field a hidden (invisible) textfield is used for maintaining the state
of an user.In such case, we store the information in the hidden field and get it from another
servlet. This approach is better if we have to submit form in all the pages and we don't want
to depend on the browser.
Here, uname is the hidden field name and Vimal Jaiswal is the hidden field value.
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.
index.html
<form action="servlet1">
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.*;
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
}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();
out.close();
}catch(Exception e){System.out.println(e);}
}
}
web.xml
<web-app>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>FirstServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>s2</servlet-name>
<servlet-class>SecondServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>
</web-app>
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.
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="servlet1">
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.*;
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
out.close();
}catch(Exception e){System.out.println(e);}
}
SecondServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.close();
}catch(Exception e){System.out.println(e);}
}
}
web.xml
<web-app>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>FirstServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>s2</servlet-name>
<servlet-class>SecondServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>
</web-app>
4) HttpSession interface
In such case, container creates a session id for each user.The container uses this id to identify
the particular user.An object of HttpSession can be used to perform two tasks:
1. bind objects
2. view and manipulate information about a session, such as the session identifier,
creation time, and last accessed time.
The HttpServletRequest interface provides two methods to get the object of HttpSession:
4. public void invalidate():Invalidates this session then unbinds any objects bound to it.
index.html
<form action="servlet1">
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.*;
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
HttpSession session=request.getSession();
session.setAttribute("uname",n);
out.print("<a href='servlet2'>visit</a>");
out.close();
}catch(Exception e){System.out.println(e);}
}
SecondServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
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>s1</servlet-name>
<servlet-class>FirstServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>s2</servlet-name>
<servlet-class>SecondServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>
</web-app>
• The GenericServlet class also provides the getServletContext( ) method to return the object
of ServletContext.
Example
If you want to listen to both lifecycle events, leave out the qualifiers on the observer method:
If you are interested in only a particular lifecycle phase, use one of the provided qualifiers:
Event Handling :
Events are basically occurrence of something. Changing the state of an object is known as an
event.
We can perform some important tasks at the occurrence of these exceptions, such as counting
total and current logged-in users, creating tables of the database at time of deploying the
project, creating database connection object etc.
There are many Event classes and Listener interfaces in the javax.servlet and
javax.servlet.http packages.
Event classes
1. ServletRequestEvent
2. ServletContextEvent
3. ServletRequestAttributeEvent
4. ServletContextAttributeEvent
5. HttpSessionEvent
6. HttpSessionBindingEvent
Event interfaces
1. ServletRequestListener
2. ServletRequestAttributeListener
3. ServletContextListener
4. ServletContextAttributeListener
5. HttpSessionListener
6. HttpSessionAttributeListener
7. HttpSessionBindingListener
8. HttpSessionActivationListener
Servlet Collaboration:
The Servlet collaboration is all about sharing information among the servlets. Collaborating
servlets is to pass the common information that is to be shared directly by one servlet to
another through various invocations of the methods. To perform these operations, each
servlet need to know the other servlet with which it is collaborated. Here are several ways to
communicate with one another:
res.setContentType("text/html");
PrintWriter out = response.getWriter();
// fetches username
String n = request.getParameter("userName");
// fetches password
String p = request.getParameter("userPass");
if(p.equals("Thanos"){
RequestDispatcher rd = request.getRequestDispatcher("servlet2");
// Getting RequestDispatcher object
rd.include(request, response);
}
}
Welcome.java
response.setContentType("text/html");
// fetches username
String n = request.getParameter("userName");
<web-app>
<servlet>
<servlet-name>Login</servlet-name>
<servlet-class>Login</servlet-class>
</servlet>
<servlet>
<servlet-name>WelcomeServlet</servlet-name>
<servlet-class>Welcome</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Login</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>WelcomeServlet</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
Servlet Chaining
Servlet Chaining means the output of one servlet act as a input to another servlet. Servlet
Aliasing allows us to invoke more than one servlet in sequence when the URL is opened with
a common servlet alias. The output from first Servlet is sent as input to other Servlet and so
on. The Output from the last Servlet is sent back to the browser. The entire process is called
Servlet Chaining.
Example
res.setContentType("text/plain");
if(name!=null) {
request.setAttribute("MyName",name);
rd.forward(req , res);
// Forward this value to another Servlet
} else {
res.sendError(res.SC_BAD_REQUEST,
"MyName Required");
}
}
}
res.setContentType("text/plain");
PrintWriter out = res.getWriter();
String myname = (String)req.getAttribute("MyName");
Servlet chaining
Request Dispatching. :
The RequestDispatcher interface provides the facility of dispatching the request to another
resource it may be html, servlet or jsp. This interface can also be used to include the content
of another resource also. It is one of the way of servlet collaboration.
Response of second servlet is sent to the client. Response of the first servlet is not displayed
to the user.
In this example, we are validating the password entered by the user. If password is servlet, it
will forward the request to the WelcomeServlet, otherwise will show an error message: sorry
username or password error!. In this program, we are cheking for hardcoded information
index.html
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
String p=request.getParameter("userPass");
if(p.equals("servlet"){
RequestDispatcher rd=request.getRequestDispatcher("servlet2");
rd.forward(request, response);
}
else{
out.print("Sorry UserName or Password Error!");
RequestDispatcher rd=request.getRequestDispatcher("/index.html");
rd.include(request, response);
}
}
WelcomeServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
}
}
web.xml
<web-app>
<servlet>
<servlet-name>Login</servlet-name>
<servlet-class>Login</servlet-class>
</servlet>
<servlet>
<servlet-name>WelcomeServlet</servlet-name>
<servlet-class>WelcomeServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Login</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>WelcomeServlet</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
web-app>
JSP technology is used to create web application just like Servlet technology. It can be
thought of as an extension to Servlet because it provides more functionality than servlet such
as expression language, JSTL, etc.
A JSP page consists of HTML tags and JSP tags. The JSP pages are easier to maintain than
Servlet because we can separate designing and development. It provides some additional
features such as Expression Language, Custom Tags, etc.
There are many advantages of JSP over the Servlet. They are as follows:
1) Extension to Servlet
JSP technology is the extension to Servlet technology. We can use all the features of the
Servlet in JSP. In addition to, we can use implicit objects, predefined tags, expression
language and Custom tags in JSP, that makes JSP development easy.
2) Easy to maintain
JSP can be easily managed because we can easily separate our business logic with
presentation logic. In Servlet technology, we mix our business logic with the presentation
logic.
If JSP page is modified, we don't need to recompile and redeploy the project. The Servlet
code needs to be updated and recompiled if we have to change the look and feel of the
application.
In JSP, we can use many tags such as action tags, JSTL, custom tags, etc. that reduces the
code. Moreover, we can use EL, implicit objects, etc.
Features of JSP
• Coding in JSP is easy :- As it is just adding JAVA code to HTML/XML.
• Reduction in the length of Code :- In JSP we use action tags, custom tags etc.
• Connection to Database is easier :-It is easier to connect website to database and
allows to read or write data easily to the database.
• Make Interactive websites :- In this we can create dynamic web pages which helps
user to interact in real time environment.
• Portable, Powerful, flexible and easy to maintain :- as these are browser and server
independent.
• No Redeployment and No Re-Compilation :- It is dynamic, secure and platform
independent so no need to re-compilation.
• Extension to Servlet :- as it has all features of servlets, implicit objects and custom tags
A JSP is just another servlet, and like HTTP servlets, a JSP is a server-side Web
component that can be used to generate dynamic Web pages. The fundamental difference
between servlets and JSPs is
JSP files typically have a .jsp extension, as in mypage.jsp. When a client requests the
JSP page for the first time, or if the developer precompiles the JSP the web container
translates the textual document into a servlet.
A JSP compiler (such as Tomcat's Jasper component) automatically converts the text-
based document into a servlet. The web container creates an instance of the servlet and makes
ADVANCE JAVA PROG. RINKAL SARVAIYA
ADVANCE JAVA
the servlet available to handle requests. These tasks are transparent to the developer, who
never has to handle the translated servlet source code
The developer focuses on the JSP's dynamic behavior and which JSP elements or
custom-designed tags she uses to generate the response.
<%-- use the 'jsp:useBean' standard action to create the Date object; the object is set as an
attribute in page scope --%>
<jsp:useBean id="date" class="java.util.Date" />
<html>
<head><title>First JSP</title></head>
<body>
<h2>Here is today's date</h2>
<c:out value="${date}" />
</body>
</html>
JSP Syntax and Structure
Before writing your first JSP, you need to gain an understanding of the syntax and the
structure of a JSP.
As you have seen, JSP elements are embedded in static HTML. Like HTML, all JSP
elements are enclosed in open and close angle brackets (< >). Unlike HTML, but like XML,
all JSP elements are case sensitive.
JSP elements are distinguished from HTML tags by beginning with either <% or
<jsp:.
JSPs follow XML syntax, they all have a start tag (which includes the element name)
and a matching end tag. Like XML tags, a JSP tag with an empty body can combine the start
and end tags into a single tag. The following is an empty body tag:
</jsp:useBean>
Optionally, a JSP element may have attributes and a body. You will see examples of
all these types during today’s lesson. See Appendix C, “An Overview of XML,” for more
information on XML and the syntax of XML elements.
JSP Elements
Actions are specific tags that affect the run-time behaviour of the JSP and affect the
response sent back to the client.
• <jsp:useBean>
• <jsp:param>
• <jsp:setProperty>
• <jsp:getProperty>
• <jsp:include>
• <jsp:forward>
• <jsp:plugin>
- jsp:setProperty:
This standard action is used in conjunction with the useBean action described in the
preceding section and sets the values of simple and included properties in a bean.
attribute name: The name of the bean instance defined by a <jsp:useBean> tag.
attribute property: The name of the bean property whose value is being set.
- jsp:include:
This action allows a static or dynamic remote to be included in the current jsp at
request time. The resource is specified using the URL format described in the earlier section
on the include directive.
- jsp:forward
<jsp:forward page=”URL”/>
- jsp:plugin
This action is used to generate client browser specific HTML tags that ensure the
JavaPlugin software in available, followed by execution of the applet or JavaBean component
specified in the tag.
Scripting Elements
Scripting elements contain the code logic. It is these elements that get translated into a
Java class and compiled. There are three types of scripting elements—declarations,
scriptlets, and expressions. They all start with <% and end with %>.
1. Expressions of the form <%= expression %>, which are evaluated and inserted into the
servlet’s output
2. Scriptlets of the form <% code %>, which are inserted into the servlet’s _jspService
method (called by service)
3. Declarations of the form <%! code %>, which are inserted into the body of the servlet
class, outside of any existing methodsDeclarations
Declarations are used to introduce one or more variable or method declarations, each
one separated by semicolons. A variable must be declared before it is used on a JSP page.
Declarations are differentiated from other scripting elements with a <%! start tag. An
example declaration that defines two variables is as follows:
You can have as many declarations as you need. Variables and methods defined in
declarations are declared as instance variables outside of any methods in the class.
Expressions
JSP expressions are single statements that are evaluated, and the result is cast into a
string and placed on the HTML page. An expression is introduced with <%= and must not be
terminated with a semi-colon. The following is an expression that will put the contents of the
i element in the items array on the output page.
JSP expressions can be used as values for attributes in JSP tags. The following
example shows how the i element in the items array can be used as the value for a submit
button on a form:
Scriptlets
Scriptlets contain code fragments that are processed when a request is received by the
JSP. Scriptlets are processed in the order they appear in the JSP. They need not produce
output. Scriptlets can be used to create local variables, for example
The difference between scriptlet variables and declarations is that scriptlet variables
are scoped for each request. Variables created in declarations can retain their values between
requests (they are instance variables).
JSP scriptlets let you insert arbitrary code into the servlet’s _jspService method
(which is called by service). Scriptlets have the following form:
<%
%>
In this particular instance, you could have accomplished the same effect more easily
by using the following JSP expression:
JSP Comments
There are three types of comments in a JSP page. The first type is called a JSP
comment. JSP comments are used to document the JSP page. A JSP comment is completely
ignored; it is not included in the generated code. A JSP comment looks like the following:
This comment will be placed in the generated Java code. The third mechanism for
adding comments to a JSP is to use HTML comments.
HTML comments are passed through to the client as part of the response. As a result,
this form can be used to document the generated HTML document. Dynamic information can
be included in HTML comments as shown in the following:
JSP Declarations
A JSP declaration lets you define methods or fields that get inserted into the main
body of the servlet class (outside of the _jspService method that is called by service to
process the request). A declaration has the following form:
Since declarations do not generate any output, they are normally used in conjunction
with JSP expressions or scriptlets. For example, here is a JSP fragment that prints the number
of times the current page has been requested since the server was booted (or the servlet class
was changed and reloaded). Recall that multiple client requests to the same servlet result only
in multiple threads calling the service method of a single servlet instance.
They do not result in the creation of multiple servlet instances except possibly when
the servlet implements SingleThreadModel. For a discussion of SingleThreadModel,
JSP Directives
Directives are used to define information about your page to the translator, they do
not produce any HTML output. All directives have the following syntax:
If the include file is itself a JSP, it is standard practice to use .jsf or .jspf, as suggested
in the JSP specification, to indicate that the file contains a JSP fragment. These extensions
show that the file is to be used in an include directive (and does not create a wellformed
HTML page). “.jsp” should be reserved to refer to standalone JSPs.
dateBanner.jsp
<HTML> <HEAD>
</HEAD> <BODY>
</BODY> </HTML>
banner.html
</TABLE> <BR>
javax.servlet.*,
javax.servlet.jsp.*, and
javax.servlet.http.*.
isThreadSafe <%@ page isThreadSafe=”true” %> If set to true, this indicates that
<%@ page isThreadSafe=”false” %> this page can be run multithreaded.
This is the default, so you should ensure that access to shared objects (such as
<%@ page isErrorPage=”false” %> the target URL for an errorPage directive. If true, an
implicit scripting variable called “exception” is defined and references the exception
name.jsp
ic = new InitialContext();
</BODY> </HTML>
These implicit objects can be used on any JSP page. Using the date JSP shown in
Listing 13.3 as an example, an alternative way of writing the date to the page is as follows:
Predefined Variables
To simplify code in JSP expressions and scriptlets, you are supplied with eight
automatically defined variables, sometimes called implicit objects. Since JSP declarations
(see Section 10.4) result in code that appears outside of the _jspService method, these
variables are not accessible in declarations. The available variables are request, response, out,
session, application, config, pageContext, and page. Details for each are given below.
request
This variable is the HttpServletRequest associated with the request; it gives you
access to the request parameters, the request type (e.g., GET or POST), and the incoming
HTTP headers (e.g., cookies). Strictly speaking, if the protocol in the request is something
other than HTTP, request is allowed to be a subclass of ServletRequest other than
HttpServletRequest. However, few, if any, JSP servers currently support non-HTTP servlets.
response
This variable is the HttpServletResponse associated with the response to the client.
Note that since the output stream (see out) is normally buffered, it is legal to set HTTP status
codes and response headers in JSP pages, even though the setting of headers or status codes is
not permitted in servlets once any output has been sent to the client.
out
This is the PrintWriter used to send output to the client. However, to make the
response object useful, this is a buffered version of Print-Writer called JspWriter. You can
adjust the buffer size through use of the buffer attribute of the page directive that out is used
almost exclusively in scriptlets, since JSP expressions are automatically placed in the output
stream and thus rarely need to refer to out explicitly.
session
This variable is the HttpSession object associated with the request. Recall that
sessions are created automatically, so this variable is bound even if there is no incoming
session reference. The one exception is if you use the session attribute of the page directive
(see Section 11.4) to turn sessions off. In that case, attempts to reference the session variable
cause errors at the time the JSP page is translated into a servlet.
application
getServletConfig().
getContext().
Servlets and JSP pages can store persistent data in the ServletContext object rather
than in instance variables. ServletContext has setAttribute and getAttribute methods that let
you store arbitrary data associated with specified keys. The difference between storing data in
instance variables and storing it in the Servlet-Context is that the ServletContext is shared by
all servlets in the servlet engine (or in the Web application, if your server supports such a
capability).
config
pageContext
JSP introduced a new class called PageContext to give a single point of access to
many of the page attributes and to provide a convenient place to store shared data. The
pageContext variable stores the value of the PageContext object associated with the current
page.
page
This variable is simply a synonym for this and is not very useful in the Java
programming language. It was created as a place holder for the time when the scripting
language could be something other than Java.
The first step is to define a simple form to allow the user to select the table to display.
tableForm.jsp
<FORM action=table>
<SELECT name=table>
You will need to add this JSP to the simple Web application and define an alias of
/tableForm to use it. The actual JSP to display the table is shown in Listing 13.8. LISTING
13.8 Full Text of table.jsp
<TABLE border=1>
<%InitialContext ic = null;
ic = new InitialContext();
Iterator it = rows.iterator();
while (it.hasNext()) {
out.print(“<TR>”);
out.print(“<TD>”+row[i]+”</TD>”);
out.print(“</TR>”);
} %>
JSP Problems
There are three types of errors you can make with JSP pages:
Finding and correcting these errors can be quite problematic because the information
you need to discover the error is not readily available. Before looking at resolving errors, you
will need to understand the JSP lifecycle.
JSP Lifecycle
As has already been stated, JSPs go through a translation and compilation phase prior
to processing their first request.
The Web server automatically translates and compiles a JSP; you do not have to
manually run any utility to do this. JSP translation and compilation can occur at any time
prior to the JSP first being accessed. It is implementation dependent when this translation and
compilation occurs but it is usually either
• On deployment
If the latter strategy is used, not only is there a delay in processing the first request
because the page is translated and compiled, but if the compilation fails, the client will be
presented with some unintelligible error. If your server uses this strategy, ensure that you
always force the translation and compilation of your JSP, either by making the first page
request after it has been deployed or by forcing the page to be pre-compiled. With J2EE RI,
the translation and compilation only takes place when the page is first accessed. You can find
the translated JSP in <J2EE installation>\repository\ <machine name>\web\<context root>\.
You may find it useful to refer to the translated
difficult to comprehend because of the way they are detected and reported. There are three
categories of error:
• JSP translation
• Servlet compilation
• HTML presentation
The first two categories of error are detected by the Web server and sent back to the client
browser instead of the requested page. The last type of error (HTML) is detected by the Web
browser. Correcting each category of error requires a different technique
Translation Errors
If you mistype the JSP tags or fail to use the correct attributes for the tags, you will
get a translation error returned to your browser. With the simple date example, missing the
closing % sign from the JSP expression, as in the following code
It will generate a translation error. Using the Web browser to report errors is an
expedient solution to the problem of reporting errors, but this approach is not used by all Web
servers. Some simply write the error to a log file and return an HTTP error to the browser.
The JSP specification simply requires the Web server to report an HTTP 500 problem if there
is an error on the JSP.
This shows all of the useful information for determining the error. The first part of the
line tells you the exception that occurred:
org.apache.jasper.compiler.ParseException:
In this case, a generic parsing exception reported by the JSP translator. The J2EE RI
includes a version of the Apache Tomcat Web server and it is the Jasper parser of Tomcat
that has reported the error.
The second part of the error identifies the JSP page: /date.jsp and the third part
specifies the line and column number: (8,0)
You know that the error is on line 8 of the date.jsp page. The column number is often
misleading and is best ignored when looking for the error. The final part of the error message
is a brief description of the problem:
The rest of the error information returned to the Web browser is a stack trace of where
the exception occurred in the Jasper translator. This is of no practical use to you and can be
ignored. From the error information you should be able to identify the problem on the
original JSP. Depending on the nature of the error, you may need to look at JSP lines prior to
the one with the reported error. Sometimes errors are not reported until much later in the JSP.
The worst scenario is when the error is reported on the very last line because this means the
error could be practically anywhere in the JSP.
Compilation Errors
Compilation errors can occur when you mistype the Java code in a Java scripting
element or when you omit necessary page directives, such as import package lists.
Compilation errors are shown on the page returned to the browser and show the line
number in error in the generated file. Figure 13.7 shows compilation error that occurs if you
mistype Date as Datex in the date example show in Listing 13.3. The following is the error
line:
The information provided identifies the line in error in the JSP file and the
corresponding line in error in the generated Java file. If you cannot determine the error from
the JSP file, you will need to examine the generated file.
As stated earlier, the J2EE RI saves the generated Java file in the repository directory
in the J2EE installation directory. The actual location is in a directory hierarchy named after
the current workstation, the application name, and the Web application name. The filename is
generated from the original JSP name.
In the example error, if the current host is ABC123, the file will be stored as <J2EE
home>\repository\ABC123\web\simple\0002fdate_jsp.java The following code fragment
shows the generated code containing the Java error:
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
out = pageContext.getOut();
// end
// begin [file=”/date.jsp”;from=(4,23);to=(4,46)]
// end
out.write(“\r\n </BIG>\r\n</BODY>\r\n</HTML>\r\n”);
// end
As you can see, comments are inserted into the generated code to tie the Java code
back to the original JSP code.
Session Tracking
Scope
1 Pages scope
2 Request scope
It is bounded to javax.servlet.ServletRequest
3 Session scope
4 Application scope
EJB(Enterprise JavaBeans)
Server-Side Components
A server-side component model may define an architecture for developing distributed
business objects. They combine the accessibility of distributed object systems with the
fluidity of objectified business logic. Server-side component models are used on the middle-
tier application servers, which manage the components at runtime and make them available to
remote clients. They provide a baseline of functionality that makes it easy to develop
distributed business objects and assemble them into business solutions.
Server-side components can also be used to model other aspects of a business system,
such as presentation and routing. The Java Servlet for example is a server-side component
that is used to generate HTML and XML data for presentation layer of a three-tier
architecture. The EJB 2.0 message-driven beans, which are discussed later, are aserver-side
components that is used for routing asynchronous messages from one source to
a) Session beans
b) Entity beans
c) Message-driven beans
Thus , we have two interfaces and a class in any EJB program. The
'Remote Interface' for describing the job to be done. The 'Home Interface '
for locating the manager for creating the bean
The 'bean' class which provides the object for carrying out the job. EJB
can be thought of as Enterprise-level RMI/RMI-IIOP. If the EJB is invoked by
using a servlet and the end-user is using a browser , there are no questions
about platform and language of the client, because the client for the EJB is only
the servlet.
But, if the EJB is being invoked from a standalone program, the client
may be a java-program or non-java program.If the client is not a java program,
the question of lient's platform raises its head. So, once again we need the
OMG-IDL for our ejb service. incorporates concepts of RMI, Session-
tracking servlet and plain Javabean.
On the other hand, we also saw that a javabean may be simply a class
with some general functionality. That part of the bean is offered as 'Session
bean' in EJB. Session beans can be either Stateless beans or Stateful beans.
'Stateful session beans' are like session-tracking servlets but in RMI style.!
We will now consider simplest demo for the following types., one by
one.
====================================
*It should not have any general variables .All the data required for
the method should be passed as parameters only!
a) The Remote-Interface
b) The Home-interface
c) The Bean.
a) greeterRemote.java
b) greeterHome.java
c) greeterBean.java
greeterRemote.java
================
import javax.ejb.*;
import java.rmi.*;
greeterHome.java
==============
import java.io.*;
import java.rmi.*;
import javax.ejb.*;
greeterBean.java
===============
import java.rmi.*;
import javax.ejb.*;
public greeterBean( ) {}
greeterClient.java (CONSOLE-MODE)
================================
import javax.ejb.*;
import java.rmi.*;
import javax.rmi.*;
import javax.naming.*;
import java.util.*;
import helloRemote;
import helloHome;
import java.io.*;
try
System.out.println("please wait!");
props.put(Context.INITIAL_CONTEXT_FACTORY,
"weblogic.jndi.WLInitialContextFactory");
props.put(Context.PROVIDER_URL,
"t3://127.0.0.1:7001");
System.out.println(s1);
catch(Exception e1)
ENTITY BEANS
=============
Let us consider a simple Java class named 'customer'. Let this class have
just three attributes ,namely,'key', 'Name' and 'Place'. In a javabean, we
would provide accessor methods, such as 'getName()' & 'setName(String
s)etc. for each attribute. The same method is employed in Entity bean. (
Roughly).
Thus, we deal with Java idiom only and this is more intuitive.
n=n+400;
account1.setBalance(n);
Doubtless, this is much simpler and easier than writing sql code.
Entity beans 'persist' (ie) they are stored in Enterprise server's hard
disk and so even if there is a shutdown of the server, the beans 'survive' and
can be created again from the hard disk storage.[A session bean is not stored
in hard disk].
This database has a table known as 'table1'. The table has three columns .
a) 'key' ( primary key field)
b) 'name'
c) 'place'
( all of them are of String type)
We create a table like this without any entries and then register it in
ODBC. ( this is the most familiar and easy approach.We can also use other
types of jdbc drivers.)
In CMP, the bean designer does not have to write any sql-related code
atall. The necessary sql statements are automatically generated by the
container.
With CMP, the entity bean class does not contain the code that
connects to a database. . So, we are able to get flexibility by simply editing
the deployment descriptors and weblogic.properties files, without editing
and recompiling the java class files.
i) less code.
=================================
// **********customerRemote.java**********
import javax.ejb.*;
import java.rmi.*;
-----------------------------------------------------------------------------------------
// **********customerHome.java *******************
import javax.ejb.*;
import java.rmi.*;
RemoteException, CreateException;
RemoteException, FinderException;
// ********** customerBean.java**********
import javax.ejb.*;
import java.rmi.*;
return name;
return place;
//
name=b;
place=c;
//
this.key = a;
this.name= b;
this.place = c;
return null;
1) ejb-jar. xml
2) weblogic-ejb-jar.xml
3) weblogic-cmp-rdbms-jar.xml
These three files are very important and should be created with
utmost care. Remember that XML is case-sensitive and the DTD
(Deployment descriptor) for each file expects the correct structure of the
document. So type exactly as given.(No formatting..shown here for clarity
only)
// customerClient.java
import customerRemote;
import customerHome;
import javax.ejb.*;
import java.rmi.*;
import javax.rmi.*;
import javax.naming.*;
import java.util.*;
import java.io.*;
try
System.out.println("please wait!");
props.put(Context.INITIAL_CONTEXT_FACTORY,
"weblogic.jndi.WLInitialContextFactory");
props.put(Context.PROVIDER_URL,
"t3://127.0.0.1:7001");
customerHome home =
(customerHome)ctx.lookup("customerJndi");
DataInputStream ins =
new DataInputStream(System.in);
String s;
do
s=ins.readLine();
if(s.equals("add"))
System.out.println("what key");
String a=ins.readLine();
System.out.println("what name");
String b=ins.readLine();
System.out.println("what place");
String c=ins.readLine();
home.create(a,b,c);
System.out.println("record created");
System.out.println("=============");
if(s.equals("find"))
System.out.println("what key?");
String pk=ins.readLine();
customerRemote remote =
home.findByPrimaryKey(pk);
System.out.println(remote.getName());
System.out.println(remote.getPlace());
System.out.println("===============");
if(s.equals("update"))
System.out.println("what key?");
String pk=ins.readLine();
customerRemote remote=
home.findByPrimaryKey(pk);
String v=ins.readLine();
if(v.equals("name"))
String b = ins.readLine();
remote.setName(b);
if(v.equals("place"))
String c = ins.readLine();
remote.setPlace(c);
System.out.println("record updated!");
System.out.println("==============");
if(s.equals("delete"))
System.out.println("what key?");
String pk=ins.readLine();
customerRemote remote=
home.findByPrimaryKey(pk);
remote.remove();
System.out.println("record removed");
System.out.println("============");
}while(!s.equals("over"));
==========================================
Thus far, we acquainted ourselves with Sessionbeans ( both stateless & stateful) and
also CMP Entity bean.In this instalment, we take up the most difficult type, (ie) Bean-
Managed Persistent Entity bean.(BMP)
====================================
We have to write the SQL code for Persistence ,ourselves, in the case of Bean-Managed
persistence. In our example,If we consider a single instance of the bean, it exists as an object
in memory with 3 attributes (key,name,place) At the same time, it should also be persisted
as a row, with corresponding fields, in 'table1' of 'customer' database in hard disk.They
should match. This is known as 'Synchronization'.
However, the client cannot explicitly , call either 'load' or 'store' functions. This job is
taken care of by the Container.Depending on a number of factors such as Transaction
monitoring, the container chooses the appropriate moment to synchronize the data in
memory with the data in table of hard disk storage.
This process, is transparent ,(ie) the programmer need not know about it. The methods
are 'callback' methods. Such methods are called by the container by itself without explicit
user program or interaction.
In CMP, we just deal with the objects in memory. The task of persistence is automatically
done by the container, at the appropriate time. The container itself generates the required
SQL code to perform this task. But, in BMP , we should write the necessary SQL code for
Store and Load.
Which is better? Opinions differ.One camp claims that CMP is better because,it
abstracts the details about the underlying database and deals only with objects in memory.
The other camp feels that CMP is useful only for very simple cases and most of the
real life applications are complex, requiring joins from different tables and CMP is not
suitable for real life situations.
i) customerRemote.java
ii) customerHome.java
For our example, remember to register the database 'customer' with ODBC.Let us create
our source files in the following folder:
c:\weblogic\beans\bmpdemo
c:\weblogic\beans\bmpdemo>set JAVA_HOME=C:\JDK1.3
...bmpdemo>set WL_HOME=C:\WEBLOGIC
...bmpdemo>set path=c:\windows\command;
c:\jdk1.3\bin;
c:\weblogic\bin
...bmpdemo>set classpath=c:\weblogic\beans\bmpdemo;
c:\weblogic\classes;
c:\weblogic\lib\weblogicaux.jar;
customerRemote.java
===================
import javax.ejb.*;
import java.rmi.*;
customerHome.java
=================
import javax.ejb.*;
import java.rmi.*;
1) setName(
2) getName()
3) setPlace(
4) getPlace()
6) ejbCreate()
7) ejbFindByPrimaryKey()
8) ejbLoad()
9) ejbStore()
10) ejbRemove()
11) ejbPostCreate(
12) ejbSetEntityContext(
13) ejbUnsetEntityContext()
14) ejbActivate()
15) ejbPassivate()
It will necessary to give very brief note on the purpose of these various methods.
b) 'ejbCreate' method is called when the client invokes 'create' method. Its purpose is to
create a new object in memory with the parameters passed by the client and also create the
corresponding row in the database table.
c) 'ejbPostCreate' is called after 'ejbCreate' by the container.This can be used for any desired
tasks.It should have the same parameters as the 'ejbCreate' method.
d) 'ejbLoad' is meant for bringing a row from table into the memory.depending on the
primary key in the current context.
e) 'ejbStore' is meant for storing the state of the bean specified by the primary key in the
current context and updating the row in the table accordingly.This also is a callback method.
Distributed application
Rmi Architecture
Server object:
This distributed object model used by java allows objects that execute in JVM to
These other JVMS may execute as separate process on the same computer or other
remote computers. The object making the method invocation is referred to as client
application. The object whose methods are being invoked is referred as server object. The
client object is local object and remote object is called server object.
In this model a client object never references a remote object directly. Instead, it
references a remote interface i.e., implemented by the remote object. The use of remote
interface allows server objects to differentiate between their local and remote interfaces.
In addition to a remote interface this model makes use of stub and skeleton classes.
Stub class serves as local proxies for the remote object skeleton acts a remote proxies. Both
stub and skeleton implemented the remote interface the server object. The client interface
object invokes the methods of the local stub object. The local stub communicates this method
invocation to the skeleton via remote reference layer. The remote reference layer is used to
active the server object when they are invoked remotely. The remote reference layer on the
local host communicates with the remote reference layer on the remote host via the RMI
transport layer. The transport layer sets up & manages the connection between the address
spaces of the local & remote host, keeps track of object that can be accessed remotely &
determines when connections have been timed out. The transport layer uses the TCP Sockets
by default to communicate between local & remote host. The transport layer on the remote
host identifies the server object instance by using remote registry it forwards method
invocation to the skeleton via remote reference layer. Then the skeleton forwards this call to
the server object. The server object process the function and results back to the client object
via stub and skeletons.
The remote registry is process which maintains database objects and names by which
these objects can be referenced.
Courses.java
import java.rmi.*;
//Client.java
import java.rmi.*;
import java.rmi.server.*;
class Client
try
Courses c=(Courses)Naming.lookup("//Sunil/Courses");
catch(Exception e)
System.out.println(e);
//Server.java
import java.rmi.*;
import java.rmi.server.*;
implements Courses
super();
return "Ms-office\t C with DS, Java, VB, Oracle, Unix, Web Designing";
try
Naming.rebind("//Sunil/Courses",gs);
catch(Exception e)
{ System.out.println(e);