Survey
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
Web Technologies
B.Tech. IT III Year II Semester
UNIT VI
JSP
Java Server Pages
Outline of Presentation
•
•
•
•
•
•
•
•
•
Introduction to JSP
Servlets Vs JSP
Lifecycle of JSP
JSP Elements
Anatomy of a JSP page
JSP Processing
JSP Application Design with MVC setting
Installing JSDK
Installing Tomcat Server
Introduction
• JavaServer Pages (JSP) is a technology that
helps software developers create dynamically
generated web pages based on HTML XML or other document
types.
• JSP separates content generation from content presentation
• Released in 1999 by Sun Microsystems JSP is similar to the
Java Programming language.
• To deploy and run JavaServer Pages, a compatible web server
with a servlet container, such as Apache Tomcat or Jetty, is
required.
Servlets
• Server side Java programs
• Solve scalability issue
– serlvets are run on threads of execution not separate
processes
• Solve portability issue
– runs on every platform that supports Java
– supported by all most popular web servers
• Issue
– html tags are embedded in java programs within out.print()
statements which reduces flexibilty of programming
JSP
• server-side technology
• separate dynamic content from static content
of a page
– Java scriptlets embedded into html-like page
• Separate the work of
– java programmers
– page designers
JSP relationship to Servlets
A JSP is converted into a Servlet
JSP Life Cycle
• JSP Life Cycle
• JSP is a Web server side programming technology based on
Servlet technology. The JSP specification is built on the top of
the Servlet API.
• Any JSP page is translated into a Java Servlet by a JSP engine
at runtime so that the JSP life cycle is determined by Servlet
technology.
• The JSP engine is a JSP specification implementation which
comes with web servers that implement JSP. Tomcat is one
example.
• When a request comes to a JSP page, it may come from client
browser or come from another Web component such as a
Servlet or JSP.
JSP Life Cycle (cont.)
• The Web server asks the JSP engine to check whether
the JSP page has never been accessed before, or it has
been modified since its last access. If this is the case
the JSP engine will
1. Parse the JSP document to translate into a Servlet Java file
2. Compile the Servlet Java file into a class file
• Then the Servlet container loads the Servlet class for
execution and sends the results back to the client.
JSP Life Cycle (cont.)
JSP file
(when JSP get
first access or get
changed)
translate
Servlet
Java file
JSP engine
Servlet Container
Process of a JSP page
compile
Servlet
Class
JSP Life Cycle (cont.)
• The jspInit()
– This method is executed first after the JSP is loaded.
– The jspInit() is only called once during any JSP component
life time.
– <%! public void jspInit(){ . . . } %>
• _jspService()
– This method is executed for processing client request and
send the response back to client.
• _jspDestroy()
– This method is executed to destroy the JSP object.
JSP Elements
Besides HTML tag elements, JSP provides four basic
categories of constructors (markup tags): directives, scripting
elements, standard actions, and comments.
JSP Directives
JSP Actions
JSP Scripting Elements
JSP comments
Expression Language
JSP Syntax
Elements
JSP Standard Syntax
JSP XML Syntax
<%! ..%>
<jsp:declaration> .. </jsp:declaration>
<%@ include .. %>
<jsp:directive.include .. />
<%@ page attributes %>
<jsp:directive.page attributes />
<%@ taglib .. %>
<html xmlns:prefix="tag library URL" >
Expressions
<%= ..%>
<jsp:expression> .. </jsp:expression>
Scriptlets
<% ..%>
<jsp:scriptlet> .. </jsp:scriptlet>
Comments
<%--.. --%>
<!-- .. -->
Declarations
Directives
JSP Directives
JSP directives provide directions and instructions to the container,
telling it how to handle certain aspects of JSP processing.
A JSP directive affects the overall structure of the servlet class.
Syntax:
<%@ directive attribute="value" %>
There are three types of directive tag:
Directive
Description
<%@ page ... %>
Defines page-dependent attributes, such as scripting
language, error page, and buffering requirements.
<%@ include ... %>
Includes a file during the translation phase.
<%@ taglib ... %>
Declares a tag library, containing custom actions, used in
the page
The page Directive
The page directive is used to provide instructions to the container that pertain to
the current JSP page. You may code page directives anywhere in your JSP page. By
convention, page directives are coded at the top of the JSP page.
Following is the basic syntax of page directive:
<%@ page attribute="value" %>
You can write XML equivalent of the above syntax as follows:
<jsp:directive.page attribute="value" />
The page Directive
Following is the list of attributes associated with page directive:
Attribute
Purpose
buffer
Specifies a buffering model for the output stream.
autoFlush
Controls the behavior of the servlet output buffer.
contentType
Defines the character encoding scheme.
errorPage
Defines the URL of another JSP that reports on Java unchecked
runtime exceptions.
isErrorPage
Indicates if this JSP page is a URL specified by another JSP page's
errorPage attribute.
extends
Specifies a superclass that the generated servlet must extend
import
Specifies a list of packages or classes for use in the JSP as the
Java import statement does for Java classes.
info
Defines a string that can be accessed with the servlet's
getServletInfo() method.
isThreadSafe
Defines the threading model for the generated servlet.
language
Defines the programming language used in the JSP page.
session
Specifies whether or not the JSP page participates in HTTP
sessions
isELIgnored
Specifies whether or not EL expression within the JSP page will be
ignored.
isScriptingEnabled
Determines if scripting elements are allowed for use.
Page Directive
Example:
• <%@ page import="package.class" %>
• <%@ page import="java.util.*" %>
• <%@ page contentType="text/html" %>
– <% response.setContentType("text/html"); %>
The include Directive:
The include directive is used to include a file during the translation phase. This
directive tells the container to merge the content of other external files with the
current JSP during the translation phase. You may code include directives
anywhere in your JSP page.
The general usage form of this directive is as follows:
<%@ include file="relative url" >
The filename in the include directive is actually a relative URL. If you just specify a
filename with no associated path, the JSP compiler assumes that the file is in the
same directory as your JSP.
You can write XML equivalent of the above syntax as follows:
<jsp:directive.include file="relative url" />
Include Directive
• <%@ include file="Relative URL">
• Included at Translation time
• May contain JSP code such as response header
settings, field definitions, etc... that affect the
main page
The taglib Directive
The taglib directive declares that your JSP page uses a set of custom tags,
identifies the location of the library, and provides a means for identifying the
custom tags in your JSP page.
The taglib directive follows the following syntax:
<%@ taglib uri="uri" prefix="prefixOfTag" >
Where the uri attribute value resolves to a location the container understands and
the prefix attribute informs a container what bits of markup are custom actions.
You can write XML equivalent of the above syntax as follows:
<jsp:directive.taglib uri="uri" prefix="prefixOfTag" />
When you use a custom tag, it is typically of the form <prefix:tagname>. The
prefix is the same as the prefix you specify in the taglib directive, and the tagname
is the name of a tag implemented in the tag library
Scripting Elements
There are three types of Scripting Elements
• Declaration
• Expression
• Scriptlets
Declaration Element
• The JSP declaration element defines page-scope
variables to store information or defines supporting
methods that the rest of a JSP page may need.
Declaration elements do not produce outputs.
Its syntax is
<%! Java Code %>
Example:
<%! int i=0; Double d; %>
Declaration Element (cont.)
You can also declare methods by declaration scripting elements. For example,
you can declare the JSP life cycle methods jspInit() and jspDestroy() as follows :
<%! Connection conn %>
...
<%! public void jspInit() {
{
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
conn = java.sql.DriverManager.getConnection(
"jdbc:oracle:oci9:myDB","scott","tiger");
}
catch (Exception e)
{
. . .}
}
}
%>
Expression Element
• Typically, expressions are used to display simple values of
variables or return values of shared data by invoking a bean's
getter methods.
• In JSP, the results of an expression evaluation are always
converted to a string and directly included in the output page.
• The predefined JSP objects such as request, response, and
session can also be used within the expression element to
make the expression as simple as possible.
Syntax : <%= expr %>
// No semicolon
<%= i * j + k %>
<%= myBean.getSalary() %>
<%= request.getRemoteHost() %>
<%= new java.util.Date() %> // To display Date & Time
Scriptlet Element
• JSP scriptlets are embedded within <% ... %> tags. They are
executed at the runtime.
• <% Java code
%>
• The scriptlets are inserted into the _jspService() method of the
translated Servlet code which is invoked by the Servlet
service() method. This java code is executed when the request
is serviced by the JSP page. You can put any valid Java code
within a scriptlet element, and it is not limited to one line of
source code. For example, the following displays the counter
during execution of a loop, combining the use of the
expressions element and the scriptlets element:
• <% for (int i=1; i<=4; i++) { %>
•
The counter is now <% = i %>
• <% } %>
JSP Standard Actions
• The JSP specification defines a few standard
action elements (built-in in JSP)
• The syntax:
<jsp:action-name attr1=“value1” attr2=“value2”>
action_body
</jsp:action-name>
• or (with no body)
<jsp: action-name attr1=“value1”
attr2=“value2” />
JSP forward Action
• <jsp:forward page="another page" />
• This action forwards the request to another
page, i.e. an internal redirect.
• For example, it forwards the control from
current page to second.jsp.
• ...
• <jsp:forward page=”second.jsp”/>
• ...
JSP include Action
• Addition to the JSP page include directive that includes a
page at the JSP translation time, JSP also supports an
action that can dynamically include a page at run-time.
• <jsp:include page = “<jsp or html page>” flush=”true |
false” />
• If the flush attribute is set to true, the included page will
update when the JSP is updated. Remember that the
include directive only copies the contents once and never
changes afterwards since it is static. The purpose of
include action is to include the other page to be part of
current page. It is used for conditionally including other
pages at run time.
jsp:useBean Action Element
• The jsp:useBean action instantiates an instance of the bean
class if there is not an existing one or creates a reference to
an existing one. It also specifies the visibility and
accessibility scope of this bean. The other Web
components in JSP can reference this bean object by its id.
Its syntax is given as:
• <jsp:useBean id="name" class=”<package>.<Java bean
class>” scope=”. . .”>
• The id is the access name of this bean. The scope attribute
defines the visibility of this bean.
–
–
–
–
page
Only active in the page , default scope
request Active for the current request
session Active for the current session
application
Active for the current application
jsp:useBean Action Element (cont.)
• After you get a reference to a bean you can use
jsp:setProperty action and jsp:getProperty action to modify
and retrieve the bean properties.
• Once you have a bean reference, you can also modify its
properties by calling the bean’s getXXX() or setXXX()
methods explicitly in a scriptlets element.
• Note that the class specified for the bean must be in the
server's regular class path. For example, in Tomcat, this class
and all the classes it uses should go in the classes directory or
be in a jar file in the lib directory.
jsp:useBean Action Element (cont.)
• You can also incorporate Java code into the body of a
jsp:useBean tag so that the incorporated code will be
executed when the bean is instantiated for the first
time. If the instance exists already the code will be
ignored.
• <jsp:useBean ...>
Java code
</jsp:useBean>
jsp:setProperty Action
• You use jsp:setProperty to assign values to properties of a
bean. You can either use jsp:setProperty after, but outside of, a
jsp:useBean element or within the body of jsp:useBean action
element.
• Option 1:
• <jsp:useBean id="myBook" ... />
• ...
• <jsp:setProperty name="myBook" property="price" ... />
• In this case, the jsp:setProperty is executed regardless of
whether a new bean was instantiated or an existing bean was
found.
jsp:setProperty Action (cont.)
• Option 2:
<jsp:useBean id="myBook" ... >
...
<jsp:setProperty name="myBook" property="price" ... />
</jsp:useBean>
In this case, the jsp:setProperty is executed only if a new object is
instantiated, i.e., no existing bean object exists yet.
The following action sets myBook’s price property to 31.99.
<jsp:setProperty name="myBook" property="price" value =
“31.99” />
jsp:setProperty Action (cont.)
• The required “name” attribute is the id of the bean
specified in <jsp:useBean> action tag.
• The required “property” attribute specifies the
property you want to set. You can also assign a "*" to
the property if all request parameter names match
bean property names. It will set all corresponding
properties of the bean with the values of request
parameters either from request form or request string.
• The “value”attribute specifies the value for the
property. The String type value will be converted to
the correct type for the property.
jsp:setProperty Action (cont.)
• You can also associate the bean properties with the input
parameters. The next example shows that the bookPrice input
parameter in the request form or query string is associated with
the price property of myBook bean.
• <jsp:setProperty name="myBook" property="price"
param="bookPrice" />
• Or you can associate all properties with input request
parameters with the “*” wildcard character. Assume that there
are four input request parameters whose names match four
property names: title, isbn, price, and quantity. Whatever data
you input to the parameters will be assigned to the properties
with same names. This is one of the most useful javaBean
features.
• <jsp:setProperty name="myBook" property="*" />
jsp:setProperty Action (cont.)
• You can't use both value and param at same time, but
it is allowed to use neither. If you use neither param
nor value, that indicates that a parameter name
matches the property name. JSP will take the input
from the parameter which has the same name as the
property name.
• jsp:setProperty action is much more powerful than
the setXXX() methods in that it can automatically
convert String type data to the required data type of
the bean property and set multiple properties using
only one single command.
jsp:getProperty Action Element
• This element retrieves the value of a bean property, converts it to
a string, and inserts it into the JSP outputs. The two required
attributes are name – the id of a bean defined via jsp:useBean,
and property – the property whose value should be inserted.
• <jsp:useBean id='myBook'
•
class='shopping.Book'
•
scope='session' >
• ...
• The next action can return the number of copies of myBook,
which may reference a specific book at the time.
•
<jsp:getProperty name="myBook" property="quantity" />
•
• To return the price of the same book:
•
<jsp:getProperty name="myBook" property="price" />
• </jsp:useBean>
Example
• The form.jsp takes user name input on the form request, saves the
input in a JavaBean, and redirects to response.jsp. The
response.jsp JSP page gets the username from the bean, and
finally it responds to the user with a message “Hello, <user
name>”.
<%@ page import="user.NameBean" %>
<jsp:useBean id="myBean" scope="request" class="user.NameBean" />
<jsp:setProperty name="myBean" property="*" />
<html>
<body>
<form method="get">
<input type="text" name="userName" size="20">
<br>
<input type="submit" value="Submit">
</form>
<% if (request.getParameter("userName") != null) { %>
<%@ include file="response.jsp" %>
<% } %>
</body>
</html>
(cont.)
• Here is the NameBean javaBean file.
package user;
public class NameBean {
String userName;
public NameBean(){ userName=null; }
public void setUserName(String name) { userName=name; }
public String getUserName() { return userName; }
}
Here is the response.jsp file
<h1>Hello, <jsp:getProperty name="myBean"
property="userName" /></h1>
jsp:plugin Action Element
• The jsp:plugin action can insert an Java Applet client-side
component into a server-side JSP page component. It
downloads Java plug-in software (if necessary) and client-side
component such as Applet and executes the client-side
component.
• The syntax is as follows.
• <jsp:plugin type=”applet” code=”MyApplet.class”
width=”400” height=”200”>
• ...
• <!-- Parameter lists passed on the current JSP -->
• <jsp:param name=”username” value=”Smith” />
• …
• </jsp:plugin>
jsp:plugin Action Element (cont.)
• The <jsp:plugin> element can display an Applet object or a
bean object in the client Web browser, using a Java plug-in
which is part of the browser or downloaded from a specified
URL.
• When the JSP file sends an HTML response to the client, the
<jsp:plugin> element is replaced by an <object> element in
HTML specification. In general, the attributes to the
<jsp:plugin> element specify whether the object is a bean or
an applet, locate the code that will be run, position the object
in the browser window, specify an URL from which to
download the plug-in software, and pass parameter names
and values to the object.
JSP Comments
• JSP Comments: Different from HTML comments
<!-- an HTML comment -->
<%-- a JSP comment --%>
• JSP comments are used for documenting JSP code
and are not visible client-side (using browser's View
Source option) where as HTML comments are
visible.
Expression Language (EL)
• A new feature of JSP technology version 2.0 is the
Expression Language (EL). The EL is a simple and
very powerful notation which makes it easier for the
JSP page author to write code for accessing
application data such as data stored in JavaBean
components and attribute data of pageContext,
request, session, and application.
• EL uses a shorthand notation of ${ expr } instead of
<%= expr %>.
• For example, you have a Book JavaBean class in
shopping package
Anatomy of JSP page
• Anatomy of a JSP Page
– A JSP page is a mixture of standard HTML tags, web page content, and some
dynamic content that is specified using JSP constructs. Everything except the
JSP constructs is called Template Text.
Example:
HTML>
<HEAD>
<TITLE>Hello World</TITLE>
Template data
</HEAD>
<BODY>
<H1>Hello World</H1>
Today is: <%= new java.util.Date().toString() %> // Jsp element
</BODY>
</HTML>
JSP Processing
• When a JSP page request is processed, the template text and dynamic
content generated by the JSP elements are merged, and the result is sent as
the response to the browser
• Whenever a .jsp is requested for the first time, the server needs a JSP
container to process JSP pages
– The JSP container initiates the translation phase for a page
automatically when it receives the first request for the page
1. Translates the .jsp page into a servlet
2. Compiles the servlet into a class file
3. Executes the servlet (response is sent to the client)
– As long as the JSP page remains unchanged, any subsequent request goes
straight to the request processing phase
– When the JSP page is modified, it goes through the translation phase again
– It is loaded once and called repeatedly, until the server is shut down
JSP Processing (cont..)
JSP Application Design with MVC
Model–view–controller (MVC)
• It is a software pattern for implementing user interfaces.
• It divides a given software application into three interconnected parts, so as
to separate internal representations of information from the ways that
information is presented to or accepted from the user.
• The central component, the model, consists of application data, business
rules, logic, and functions.
• A view can be any output representation of information, such as a chart or a
diagram. Multiple views of the same information are possible, such as a bar
chart for management and a tabular view for accountants.
• The third part, the controller, accepts input and converts it to commands for
the model or view.
JSP Application Design with MVC
The Model/View/Controller architecture is a good framework for JSP.
•
View is a JSP page used for Presentation Layer
•
The controller object is master Servlet. Every request goes through the controller
who retrieves the necessary model object.
•
The model may interact with other business entities such as databases or Enterprise
Java Beans (EJB).
•
The model object sends the output results back to the controller. The controller
takes the results and places it inside the web browser session and forwards a
redirect request to a particular Java Server Page. The JSP, in the case, is the view.
The controller has to bind a model and a view
•
JSP Application Design with MVC
JSP Application Design with MVC
• MVC roles in a pure JSP scenario
Apache Tomcat
Installing Tomcat
Representation and Management of
Data on the Web
What is Tomcat?
• Tomcat is a Servlet container (Web server that
interacts with Servlets) developed under the Jakarta
Project of Apache Software Foundation
• Tomcat implements the Servlet and the Java Server
Pages (JSP) specifications of Sun Microsystems
• Tomcat is an open-source, non commercial project
– Licensed under the Apache Software License
• Tomcat is written in Java (OS independent)
Basic Setup Steps
•
•
•
•
•
•
•
Download & Install Java S/W Development Kit
Download a server (Apache Tomcat)
Configure the server
Set up development environment
Test your setup
Establish a deployment method
Create custom Web applications
Install Instructions
• Get & install 5.5.15 Core Windows Executable
(apache-tomcat-5.5.15.exe)
• Configuration
– Port? (8080 or 80)
– User: admin
– Password: webtech
Installation Configuration
(pswd: webtech)
Set Path to the Installed JVM
(Tomcat 5.5 is designed to run on J2SE 5.0 and later.)
Tomcat Directory Structure
Tomcat-Base
conf
logs
webapps
server
server.xml
ROOT
myApp1
myApp2
work
shared
lib
classes
WEB-INF
web.xml
lib
classes
Tomcat-Home
bin
common
lib
classes
Running & Testing Tomcat
•
•
•
In the Tomcat folder, open the bin
folder.
Click the startup.bat icon.
You should see a black and white Java
command window.
–
•
Open your browser and point to
http://localhost:8080.
–
•
•
You should not see any obvious java
error messages.
You should see the Tomcat welcome
page.
Note startup.bat actually calls other
scripts in the same directory
(catalina.bat, particularly).
The .sh files are for running Tomcat on
Linux/Unix
–
Maybe Mac also.
Testing the Server
• Involves two steps:
– Verifying that the server can even start
– Checking that you can access your own HTML and
JSP pages
• use the default Web application.
– put HTML and JSP pages in
install_dir/webapps/ROOT or
install_dir/webapps/ROOT/somePath and access
them with http://localhost/filename or
http://localhost/somePath/filename.
The Directory Structure of a Web
Application
• An application's directory must contain
the following:
– The directory WEB-INF/
– A legal web.xml file under WEB-INF/
myApp
<web-app>
</web-app>
WEB-INF
web.xml
Configuring a Web
Application(web.xml)
• Application-specific configuration and declarations are
written in the file myApp/WEB-INF/web.xml
• This file contains:
– Servlet declarations, mappings and parameters
– Default files for directory requests
–
–
–
–
–
Error pages (sent in cases of HTTP errors)
Security constraints
Session time-out specification
Context (application) parameters
And more…
Compiling and Testing Simple Servlets
• to verify the environment is all set compile and run
some simple Servlet, i.e. HelloServlet.java
• the location for servlets in the default Web
application is:
• create a directory name myApp in webapps
install_dir/webapps/myApp/WEB-INF/classes
• Once you compile HelloServlet.java, put
HelloServlet.class in:
install_dir/webapps/myApp/WEB-INF/classes
• After compiling the code, access the servlet with the
URL:
http://localhost/myApp/HelloServlet
Installing JSDK
1.
2
3
4
5
6
7
8
9
Download the latest version of the *Java JDK from Sun Microsystems
Double-click on the install file and it should open an installer
Click next, then read and accept the license.
On the next screen you will encounter some options. Just leave these alone
and click next
The next page you encounter should install (and in some cases download)
the Java Development Kit.
After the installer is finished, open run by clicking Start > Run.
In the text box, type "cmd" and click "OK“
A simple window should be opened with a black background and a text
prompt.
After focusing the window, type "javac" and press enter. If the prompt
returns something along the lines of: "'javac' is not recognized as an
internal or external command, operable program or batch file" then
continue with the next step. If it shows many more options and lines, skip
to step 15.
Installing JSDK(cont..)
9 Open the properties of "My Computer" by either right-clicking the icon on
the desktop or right-clicking Start > My Computer. When the pop up menu
opens, scroll to the bottom and select "Properties".
10 This should open a window named "System Properties". Click on the
"Advanced" tab and then click "Environment Variables".
11 Next, another window opens with a lot of confusing sentences and letters.
Double-click on the "Path" variable on either of the option boxes.
12 Once the variable is opened, a text box in yet another window appears.
Careful not to delete anything in this box. At the end of the text box, add a
semi-colon if there is not one already, and add "C:\Program
Files\Java\jdk1.6.0\bin" to the text box. This is assuming you did not
change the file path of the installation.
13 Click "Apply" and "OK" to all the windows you have just opened. Open
the command prompt again, while following steps 6-9 to see if that "javac"
command works.
Important Questions
1. a) Briefly explain about Tomcat web server
b) How do you Test Tomcat Webserver
2. What are the limitations of Servlets?
3. Explain the Directive and Scripting elements of JSP.
4. Explain JSP Processing with a neat diagram
5. Explain the anatomy of JSP page.
6. Give an overview of java software development kit.
7. Explain various Elements of JSP