Unit4 Servlets, JSP
Unit4 Servlets, JSP
Unit4 Servlets, JSP
AND SERVLETS
CONTENTS
Introduction to Servlets
Lifecycle of a servlet
The servlet api
The javax.servlet package
The javax.servlet.http package
Handling http request & responses using cookies
Session tracking and security issues and servlets with database
connectivity
Introduction to model view controller (mvc): architecture, its structure
components.
INTRODUCTION TO SERVLETS
Servlets offer several advantages in comparison with CGI. First,
performance is significantly better. Servlets execute within the address
space of a web server. It is not necessary to create a separate process to
handle each client request. Second, servlets are platform-independent
because they are written in Java. Third, the Java security manager on the
server enforces a set of restrictions to protect the resources on a server
machine. Finally, the full functionality of the Java class libraries is available
to a servlet. It can communicate with applets, databases,or other software
via the sockets and RMI mechanisms that you have seen already.
58
GenericServlet Class
The GenericServlet class provides implementations of the basic life cycle
methods for a servlet. GenericServlet implements the Servlet and
ServletConfig interfaces. In addition, a method to append a string to the
server log file is available. The signatures of this method are shown here:
void log(String s)
void log(String s, Throwable e)
Here, s is the string to be appended to the log, and e is an exception that
occurred.
<html>
<body>
<center>
<form name="Form1" method="post" action="http://localhost:8080/servlets-
examples/ servlet/PostParametersServlet">
<table>
<tr><td><B>Employee</td><td><input type=textbox name="e"
size="25" value=""></td></tr>
<tr><td><B>Phone</td><td><input type=textbox name="p"
size="25" value=""></td> </tr>
</table>
<input type=submit value="Submit"> </body> </html>
The source code for PostParametersServlet.java is shown in the following
listing. The service( ) method is overridden to process client requests. The
getParameterNames( ) method returns an enumeration of the parameter
names. These are processed in a loop. The parameter value is obtained via
the getParameter( ) method.
Compile the servlet. Next, copy it to the appropriate directory, and update
the web.xml file, perform these steps to test this example:
CONTENTS
JavaServer Pages (JSP) technology enables you to mix regular, static HTML with
dynamically generated content. To simple write the regular HTML in the normal
manner, using familiar Web-page-building tools. You then enclose the code for the
dynamic parts in special tags, most of which start with <% and end with%>.
We can think of servlets as Java code with HTML inside; you can think of JSP as
HTML with Java code inside. Now, neither servlets nor JSP pages are restricted to
using HTML, but they usually do and this over-simplified description is a common
way to view the technologies. Now, despite the large apparent differences between
JSP pages and servlets, behind the scenes they are the same thing. JSP pages are
translated into servlets, the servlets are compiled, and at request time it is the
compiled servlets that execute. So, writing JSP pages is really just another way of
writing servlets.
Even though servlets and JSP pages are equivalent behind the scenes, they are not
equally useful in all situations. Separating the static HTML from the dynamic
content provides a number of benefits over servlets alone, and the approach used in
JavaServer Pages offers several advantages over competing technologies.
Benefits of JSP
JSP pages are translated into servlets. So, fundamentally, any task JSP pages can
perform could also be accomplished by servlets. However, this underlying
equivalence does not mean that servlets and JSP pages are equally appropriate in all
scenarios. The issue is not the power of the technology, it is the convenience,
productivity, and maintainability of one or the other. After all, anything you can do
on a particular computer platform in the Java programming language you could also
do in assembly language. But it still matters which you choose.
JSP provides the following benefits over servlets alone:
The visible elements that make up a JSP page can include the
following: Directive elements
Template data
Action
Scripting elements
A JSP page does not need to have all of these visible elements, but you will very
likely encounter all of them if you look into any moderately complex JSP project.
The following sections briefly describe each visible element.
Directives
Unlike other JSP elements, directives are not used to generate output directly.
Rather, they are used to control some characteristics of a JSP page. Directives may
be used to give special instructions to the JSP container about what to do during the
translation of the page. You can always tell a directive from other elements because
it is enclosed in a special set of braces: <%@ ... directive ... %>
Template data
Template data is static text. This static text is passed directly through the JSP
container unprocessed. For example, it may be text that provides static HTML. The
template data is the static HTML.
Although most JSP pages are used in generating HTML pages, JSP is not specific
to HTML generation. If a JSP page is expressed in XML syntax, typically
contained in a .jspx file, the template data portion may have characters that need to
be escaped. For example, the characters < and > are not allowed directly in an
XML document and must be expressed as < and >, respectively.
Action
Action elements are JSP elements that are directly involved in the processing of the
request. In most cases, action elements enable you to access data and manipulate or
transform data in the generation of the dynamic output. For example, an online store
may have a JSP page that displays a shopping cart. This cart JSP shows the products
that you have purchased. Action elements may be used to generate the listing of the
products (dynamic content) on the page and to calculate the cost and shipping
(dynamic content), while template data (static HTML) is used to display the logo and
shipping policy statements.
Action elements can be either standard or custom. A standard action is dependably
available in every JSP container that conforms to the JSP 2.0 standard.
A custom action is an action created using JSP’s tag extension mechanism. This
mechanism
enables developers to create their own set of actions for manipulating data or generating
dynamic output within the JSP page.
Every XML tag has a name, optional attributes, and an optional body. For example, the
standard
The name of this tag is jsp:include, the attributes are page and flush, and
this <jsp:include> instance does not have a body. The XML empty
notation is used.
An XML tag can also have a body containing other tags, of course:
<jsp:include page=”news.jsp” flush=”false”>
<jsp:param name=”user” value=”$,param.username-”/> </jsp:include>
In this tag, the name is still jsp:include and the attributes are still page and flush, but
now the body is no longer empty. Instead, the body contains a <jsp:param> standard
action. After template data, actions are the next most frequently used elements in JSP
coding. Actions are synonymous with tags because every action is an XML tag. The
terms are used interchangeably in this book, just as they are in the JSP developer
community.
Scripting elements
The practice of embedding code in another programming language within a JSP
page is called scripting. Scripting elements are embedded code, typically in the
Java programming language, within a JSP page. There are three different types of
scripting elements:
❑ Declarations ❑ Scriptlets ❑ Expressions
Declarations are Java code that is used to declare variables and methods. They appear as
follows:
<%! ... Java declaration goes here... %>
The XML-compatible syntax for declarations is:
<jsp:declaration> ... Java declaration goes here ... </jsp:declaration>
Scriptlets are arbitrary Java code segments. They appear as follows:
<% ... Java code goes here ... %>
The XML-compatible syntax for scriptlets is:
<jsp:scriptlet> ... Java code goes here ... </jsp:scriptlet>
Expressions are Java expressions that yield a resulting value. When the JSP is
executed, this value is converted to a text string and printed at the location of
the scripting element. Expression scripting elements appear as:
<%= ... Java expression goes here ... %>
JSP PROCESSING
Just as a web server needs a servlet container to provide an interface to servlets, the
server needs a JSP container to process JSP pages. The JSP container is responsible
for intercepting requests for JSP pages. To process all JSP elements in the page, the
container first turns the JSP page into a servlet (known as the JSP page
implementation class). The conversion is pretty straightforward; all template text is
converted to println( ) statements similar to the ones in the handcoded servlet and all
JSP elements are converted to Java code that implements the corresponding dynamic
behavior. The container then compiles the servlet class. Converting the JSP page to a
servlet and compiling the servlet form the translation phase. The JSP container
initiates the translation phase for a page automatically when it receives the first
request for the page. Since the translation phase takes a bit of time, the first user to
request a JSP page notices a slight delay. The translation phase can also be initiated
explicitly; this is referred to as precompilation of a JSP page. Precompiling a JSP
page is a way to avoid hitting the first user with this delay. The JSP container is also
responsible for invoking the JSP page implementation class (the generated servlet) to
process each request and generate the response. This is called the request processing
phase. The two phases are illustrated in Figurebelow
As long as the JSP page remains unchanged, any subsequent request goes straight to
the request processing phase (i.e., the container simply executes the class file). When
the JSP page is modified, it goes through the translation phase again before entering
the request processing phase. The JSP container is often implemented as a servlet
configured to handle all requests for JSP pages. In fact, these two containers --a
servlet container and a JSP container--are often combined in one package under the
name web container. A JSP page is really just another way to write a servlet without
having to be a Java programming wiz. Except for the translation phase, a JSP page is
handled exactly like a regular servlet: it's loaded once and called repeatedly, until the
server is shut down. By virtue of being an automatically generated servlet, a JSP page
inherits all the advantages of a servlet as platform and vendor independence,
integration, efficiency, scalability, robustness, and security.
JSP technology can play a part in everything from the simplest web application,
such as an online phone list or an employee vacation planner, to full-fledged
enterprise applications, such as a human-resource application or a sophisticated
online shopping site. How large a part JSP plays differs in each case, of course. In
this section, I introduce a design model called Model-View-Controller (MVC),
suitable for both simple and complex applications.
MVC was first described by Xerox in a number of papers published in the late
1980s. The key point of using MVC is to separate logic into three distinct units: the
Model, the View, and the Controller. In a server application, we commonly classify
the parts of the application as business logic, presentation, and request processing.
Business logic is the term used for the manipulation of an application's data, such as
customer, product, and order information. Presentation refers to how the application
data is displayed to the user, for example, position, font, and size. And finally,
request processing is what ties the business logic and presentation parts together. In
MVC terms, the Model corresponds to business logic and data, the View to the
presentation, and the Controller to the request processing.
MVC Architechture
An application data structure and logic (the Model) is typically the most stable part
of an application, while the presentation of that data (the View) changes fairly often.
Just look at all the face-lifts many web sites go through to keep up with the latest
fashion in web design. Yet, the data they present remains the same. Another
common example of why presentation should be separated from the business logic is
that you may want to present the data in different languages or present different
subsets of the data to internal and external users. Access to the data through new
types of devices, such as cell phones and personal digital assistants (PDAs), is the
latest trend. Each client type requires its own presentation format. It should come as
no surprise, then, that separating business logic from the presentation makes it easier
to evolve an application as the requirements change; new presentation interfaces can
be developed without touching the business logic.
JSP pages are used as both the Controller and the View, and JavaBeans components
are used as the Model. A single JSP page that handles everything, can use separate
pages for the Controller and the View to make the application easier to maintain.
Many types of real-world applications can be developed this way, but what's more
important is that this approach allows you to examine all the JSP features without
getting distracted by other technologies.
JSP Components
JSP categorized into 4 types
* Directives
* Standard Action elements
* Scriptlet Eléments
* Comments
a) Directives
A directives tag always appears at the top of your JSP file.
It is global definition sent to the JSP engine.
Directives contain special processing instructions for the web container.
You can import packages, define error handling pages or the session
information of the JSP page.
Directives are defined by using <%@ and %> tags.
Syntax -
<%@ directive attribute="value" %>
Directive elements
a) <%@ page ...%> Defines page-dependent attributes, such as session tracking, error
page, and buffering requirements
b) <%@ include ... %> Includes a file during the translation phase
c) <%@ tag lib ... %>Declares a tag library, containing custom actions, that is used in
Examples:
1)
<html>
<body>
<%@ page
import="java.util.Date" %>
Today is: <%= new Date() %>
</body>
</html>
2)
<html>
<body>
<%@ page
contentType="text/html" %>
Today is: <%= new
java.util.Date() %>
</body>
</html>
3)
<html>
<body>
<%@ include file="header.html" %>
Today is: <%= java.util.Calendar.getInstance().getTime() %>
</body>
</html>
c) Scripting Elements
Scripting elements, allow you to add small pieces of code (typically Java code)
in a JSP page Like actions, they are also executed when the page is requested.
i) Scriplets
In this tag we can insert any amount of valid java code.
These codes are placed in _jspService method by the JSP engine.
Scriptlets can be used anywhere in the page.
Scriptlets are defined by using <% and %> tags.
Syntax - <% Scriptlets%>
Examples:
index.jsp
<html>
<body>
<form action="welcome.jsp">
<input type="text" name="uname"><br/>
<input type="submit" value="go">
</form>
</body>
</html>
welcome.jsp
<html>
<body>
<% String name=request.getParameter("uname");
out.print("welcome "+name); %>
</body>
</html>
ii)Expressions:
Expressions in JSPs is used to output any data on the generated page.
These data are automatically converted to string and printed on the output stream.
It is an instruction to the web container for executing the code with in
the expression and replace it with the resultant output content.
For writing expression in JSP use <%= and %> tags.
Syntax - <%= expression %>
Examples:
index.jsp
<html>
<body>
<form action="welcome.jsp">
<input type="text" name="uname"><br/>
<input type="submit" value="go">
</form>
</body>
</html>
welcome.jsp
<html>
<body>
<%= "Welcome "+request.getParameter("uname") %>
</body>
</html>
iii) Declarations
This tag is used for defining the functions and variables to be used in the JSP.
This element of JSPs contains the java variables and methods which you can call in
expression block of JSP page. Declarations are defined by using <%! and %> tags.
Whatever you declare within these tags will be visible to the rest of the
page. Syntax - <%! declaration(s) %>
Example1:
<html>
<body>
<%! int data=50; %>
<%= "Value of the variable is:"+data %>
</body>
</html>
Example2:
<html>
<body>
<%!
int cube(int n){
return n*n*n*;
}
%>
<%= "Cube of 3 is:"+cube(3) %>
</body>
</html>
Comments
This tag is used for defining the functions and variables to be used in the JSP.
This element of JSPs contains the java variables and methods which
you can call in expression block of JSP page.
Declarations are defined by using <%! and %> tags.
Whatever you declare within these tags will be visible to the rest of the page.
Syntax - <%! declaration(s) %>
<b>Last Name:</b><%= request.getParameter("last_name")%>
</body>
</html>
a) Core Tags
The core group of tags are the most commonly used JSTL tags.
Following is the syntax to include the JSTL Core library in your JSP
<%@ taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core" %>
b) FormattingTags
The JSTL formatting tags are used to format and display text, the date,
the time, and numbers for internationalized Websites.
Following is the syntax to include Formatting library in your JSP −
<%@ taglib prefix = "fmt" uri = "http://java.sun.com/jsp/jstl/fmt" %>
c) SQL Tags
The JSTL SQL tag library provides tags for interacting with
relational databases (RDBMSs) such as Oracle, mySQL, or
Microsoft SQL Server.
Following is the syntax to include JSTL SQL library in your JSP −
<%@ taglib prefix = "sql" uri = "http://java.sun.com/jsp/jstl/sql" %>
d) JSTL Functions
JSTL includes a number of standard functions, most of which are
common string manipulation functions.
Following is the syntax to include JSTL Functions library in your JSP −
<%@ taglib prefix = "fn" uri = "http://java.sun.com/jsp/jstl/functions" %>
XML tags
e)
The JSTL XML tags provide a JSP-centric way of creating and
manipulating the XML documents.
Following is the syntax to include the JSTL XML library in your JSP.
The JSTL XML tag library has custom tags for interacting with the XML data.
<%@ taglib prefix = "x" uri = "http://java.sun.com/jsp/jstl/xml" %>
System Requirements
Software - Java 2 SDK Standard Edition, 1.4.2 is supported on i586 Intel and 100%
compatible platforms running Microsoft Windows. For a list of supported operating
systems and desktop managers.
Hardware - Intel and 100% compatible processors are supported. A Pentium 166MHz
or faster processor with at least 32 megabytes of physical RAM is required to run
graphically based applications. At least 48 megabytes of RAM is recommended for
applets running within a browser using the Java Plug-in. Running with less memory
may cause disk swapping which has a severe effect on performance. Very large
programs may require more RAM for adequate performance.
Installation Instructions
In this procedure, we will run the self-installing executable to unpack and install the
Java 2 SDK software bundle. As part of the Java 2 SDK, this installation includes the
Java Plug-in and Java Web Start, as well as an option to include the public Java 2
Runtime Environment. The Java 2 SDK also contains a private J2RE for use only by
its tools. For issues related to Windows Installation (IFTW) and Java Update, see the
Windows Installation (IFTW) and Java Update FAQ. After the Java 2 SDK software
has been installed, you may be asked to reboot your system.
<version> For example, if you are downloading the installer for update 1.4.2_01, the
following file name: j2sdk-1_4_2_<version>-windows-i586.exe would become: j2sdk-
1_4_2_01-windows-i586.exe
1. Check the download file size (Optional) If you save the self-installing
executable to disk without running it from the download page at the web site, notice that
its byte size is provided on the download page. Once the download has completed,
check that you have downloaded the full, uncorrupted software file.
2. If 1.4.2 Beta is installed, uninstall it. Use the Microsoft Windows
Add/Remove Programs utility, accessible from the Control Panel (Start ->
Settings -> Control Panel).
3. Run the Java 2 SDK installer Note - you must have administrative
permissions in order to install the Java 2 SDK on Microsoft Windows 2000 and XP.
Steps 4:
A screen of 'License Agreement'
displays. Click on the 'I Agree'
button.
Step 5:
A screen shot appears asking for the 'installing
location' choose the default components and
click on the 'Next' button.
Step 6:
A screen shot of 'Configuration Options'
displays on the screen. Choose the location for
the Tomcat files as per your convenience. You
can also opt the default Location The port
number will be your choice on which you want
to run the tomcat server. The port number
8080 is the default port value for tomcat server
to proceed the HTTP requests. The user can
also change the 'port number' after completing
the process of installation; for this, users have
to follow the following tips. Go to the
specified location as " Tomcat 6.0 \conf \server.xml ". Within the server.xml file choose
"Connector" tag and change the port number. Now, click on the 'Next' button to further
proceed the installation process.
Step 7:
A Window of Java Virtual Machine
displays on the screen .This window
asks for the location of the installed
Java Virtual Machine. Browse the
location of the JRE folder and click on
the Install button. This will install the
Apache tomcat at the specified
location.
Step 8:
A processing window of installing
displays on the screen. To get the
information about installer click on
the "Show details" button
Step 9:
A screen shot of 'Tomcat Completion' displays on
the screen. Click on the 'Finish' button.
Step 10:
A window of Apache Service Manager appears with
displaying the running process. Let the running
process goes on.
Step 11:
After completing the installation process, the Apache Tomcat
Manager appears on the toolbar panel like shown in the picture.