Session 5
Introduction to
Java Server
Pages
Objectives:
What are Java Server Pages?
Structure of a JSP document.
Scriplet Tag
Expression Tag
Declaration Tag
Directive Tag
JSP Tags
Processing Request
Parameters in JSPs.
Why use JSP Technology?
• Convenient:
We already know Java and HTML!
• Provides an extensive infrastructure for:
Tracking sessions.
Managing cookies.
Reading and sending HTML headers.
Parsing and decoding HTML form data.
• Efficient:
– Every request for a JSP is handled by a simple Javathread.
Why use JSP Technology?..
• Portable
– JSP follow a well standardized API.
– The Java VM which is used to execute a JSP file is
supported on many architectures and operating systems.
• Inexpensive
– There are a number of free or inexpensive Web Servers
– that are good for commercial-quality websites.
What is JSP?
• Java based technology that simplifies the developing
of dynamic web sites.
• JSP pages are HTML pages with embedded code that
allows to access data from Java code running on the
server.
• JSP provides separation of HTML presentation logic
from the application logic.
JSP Technology
• JSP technology provides a way to combine the
worlds of HTML and Java servlet programming.
• JSP specs are built on the Java Servlet API.
• JSP supports two different styles for adding dynamic
content to web pages:
– JSP pages can embed actual programming code (typically
Java).
– JSP supports a set of HTML-like tags that interact with
Java objects on the server (without the need for raw Java
code to appear in the page).
JSP Flow..
• JSP pages “live”
within a container that
manages its
interaction:
– HTTP Protocol
(request, response,
header).
– Sessions.
How it really works... (1/2)
• Client requests a page ending with
“.jsp”.
• Web Server fires up the JSP engine.
• JSP engine checks whether JSP file is
new or changed.
• JSP engine converts the page into a
Java servlet (JSP parser).
• JSP engine compiles the servlet (Java
compiler).
How it really works... (2/2)
• Servlet Engine executes
the new Java servlet
using the standard API.
• Servlet’s output is
transferred by Web
Server as a http response
Structure of a JSP file.
• Similar to a HTML document. Four basic tags:
– Scriplet <html>
– Expression <head>
<title>Hello World</head>
– Declaration
</head>
– Definition <body>
<h1>Hello, World</h1>
It’s <%=(new java.util.Date()).toString()%>
and all is well.
</body>
</html>
Scriptlet Tag
• Two forms: <html>
– <% any java code %> <body>
– <jsp:scriptlet> ... <% for (int i = 0; i < 2; i++) { %>
</jsp:scriptlet>. (XML form) <p>Hello World!</p>
<% } %>
• Embeds Java code in the
</body>
JSP document that will be </html>
executed each time the JSP
page is processed. <html>
• Code is inserted in the <body>
service() method of the <p>Hello World!</p>
generated Servlet <p>Hello World!</p>
</body>
</html>
JSP Implicit Objects
• In JSP, need to be able to access information about the environment in which
the page is running e.g. the parameters passed in a request for a form, the
browser type of the user etc.
• Implicit objects are a set of Java objects that the JSP Container makes
available to developers in each page. These objects may be accessed as built-
in variables via scripting elements.
• Implicit objects accessible to actions
– Page
– Out
– Config
– Session
– Request
– Application
– Response
– pageContext
– exception
– Think of as “variables that are automatically available to your JSP page”
Implicit Objects
• Session
– The HttpSession object associated to the request
– Same usage as in servlets
– Created automatically
• Application
– The ServletContext object
– Used to share variables across all servlets in the application
– getAttribute and setAttribute methods
• Config
– The ServletConfig object
– Same usage as in servlets
• pageContext
– The PageContext object
– Used for sharing JavaBeans
Implicit Objects
• Request
– The HttpServletRequest parameter
– Same usage as in servlets
– Mainly used for getting request parameters
• Response
– The HttpServletResponse parameter
– Same usage as in servlets
– Rarely used in JSP (directives already to the work for us...)
• Out
– The PrintWriter associated to the response (buffered)
– out.println()
– Not much used... just escape to HTML
• %>html code<%
Expression Tag
• <%= expr %>
• <jsp:expression> expr </jsp:expression>
• Expression expr is evaluated (in Java) and its value is
placed in the output.
– Note: no semi-colon “;” following expr
<html>
<html>
<body>
<body>
<p>
<p>25</p>
<%= Integer.toString( 5 * 5 ) %>
</body>
</p>
</html>
</body>
</html>
Declaration Tag
• <%! declaration %>
• <jsp:declaration> declaration(s)</jsp:declaration>
• Embeds Java declarations inside a JSP document
• Code is inserted in the body of the servlet class, outside the
service method.
– May declare instance variables.
– May declare (private) member functions.
<html>
<body>
<%! private int accessCount = 0; %>
<p> Accesses to page since server reboot:
<%= ++accessCount %> </p>
</body>
</html>
Directive Tag
• <%@ directive att="value" %>
• <jsp:directive.page att="val" />
• Directives are used to convey special processing information
about the page to the JSP container.
– page directive.
– include directive.
<%@ page import="java.util.*" %>
<%@ page contentType="text/xml" %>
<%@ page errorPage="error.jsp" %>
The JSP @page Directive
• import="package.class" or import="pkg.class1,...,pkg.classN“
– This lets you specify what packages should be imported.
The import attribute is the only one that is allowed to
appear multiple times.
– Example: <%@ page import="java.util.*" %>
• contentType="MIME-Type" or contentType="MIME-Type;
charset=Character-Set“
– Specifies the MIME type of the output. Default is text/html.
– Example: <%@ page contentType="text/plain" %> equivalent to <%
response.setContentType("text/plain"); %>
The JSP @page Directive
• session="true|false“.
– A value of true (the default) indicates that the predefined
variable session (of type HttpSession) should be bound to
the existing session if one exists, otherwise a new session
should be created and bound to it.
– A value of false indicates that no sessions will be used, and
attempts to access the variable session will result in errors
at the time the JSP page is translated into a servlet.
The JSP @page Directive
• errorPage="url“.
– This specifies a JSP page that should process any
Throwables thrown but not caught in the current
page.
• isErrorPage="true|false“.
– This indicates whether or not the current page can
act as the error page for another JSP page. The
default is false.
The JSP @include Directive
• <%@ include file="relative url" %>
– Include files at the time the JSP page is translated into a servlet.
• The contents of the included file are parsed as regular JSP
text, and thus can include static HTML, scripting
elements,directives, and actions.
• Warning: when included files change, the page is not
automatically recompiled
<%@ include file="header.jsp" %>
Only the content of a page is unique.
Header and footer are reused from header.jsp and footer.jsp
<%@ include file="footer.jsp" %>
JSP Comments
• Regular (HTML) Comment
– <!-- comment -->
• Hidden (JSP) Comment
– <%-- comment --%>
<html>
<!-- Regular Comment -->
<%-- Hidden Comment --%> <html>
<% <!-- Regular Comment -->
// Java comment </html>
%>
</html>
Scriptlet Example
JSP Action elements
• Action elements are an important syntax element in JSP
• They are represented by tags (as is HTML)
• They assist JSP developers to develop in tags rather than
scriplet programming
• Instead of <%, they just use the < character (like HTML)
<prefix:action_name>
body
</prefix:action_name>
JSP Action elements
• JSP tags have a “start tag”, a “tag body” and an “end tag”
• The start and end tag have the same name enclosed in < and >
• The tag names have an embedded colon character “:” in them
– the part before the colon (prefix) describes the type of the tag
– the part after the “:” is the Action Name
<prefix:action_name>
body
</prefix:action_name>
JSP Action elements
• Tags have associated attributes (like HTML e.g. <img src =
“..”)
• Full syntax of JSP Action Elements is:
<prefix:action_name attr1 = “value” attr2 = “value2”>
action_body
</prefix:action_name>
• If the element doesn’t have a body, can lose the end tag and
use shorthand syntax of:
<prefix:action_name attr1 = “value” attr2 = “value2” />
• Example:
<jsp:include page="scripts/login.jsp" />
JSP Predefined Tags
• Also called JSP Standard Action Elements
– <jsp:forward>
– <jsp:include>
The jsp:forward Action
• This action lets you forward the request to another page.
• It has a single attribute, page, which should consist of a
relative URL:
– a static value
– a string expression computed at request time.
• It emulates a new request from the browser
<jsp:forward page="/utils/errorReporter.jsp" />
<jsp:forward page="<%= someJavaExpression %>" />
Forwarding with parameters
<jsp:forward page="urlSpec">
<jsp:param name="param1Name”
value="param1Value" />
<jsp:param name="param2Name”
value="param2Value" />
...
</jsp:forward>
Example
• Standard Action Example: <JSP: forward> tag
• Stops processing of one page and starts processing the page
specified by the page attribute
• Example:
<html>
<body>
Error occurred…please wait<br/>
<jsp:forward page=“errorpage.jsp"/>
</body>
</html>
The <jsp:include> Action
• Standard Action Example: <jsp:include> tag
• Example:
<html>
<body>
Going to include hello.jsp...<br/>
<jsp:include page="hello.jsp"/>
</body>
</html>
• Executes the included JSP page and adds its output
into the page
The jsp:include Action
• Unlike the include directive, which inserts the file at
the time the JSP page is translated into a servlet, this
action inserts the file at the time the page is
requested:
– Small penalty in efficiency
– The included page cannot contain JSP code (only HTML)
– Gains significantly in flexibility.
jsp:param with jsp:include
• Can be used to pass parameters when using
<jsp:include> or <jsp:forward>
• Example
<jsp:include page="login.jsp">
<jsp:param name="user" value="smith" />
</jsp:include>
– Executes a login page
– jsp:param passes in username to the login page
Request object- getting
parameters
• String getParameter(String name)
– Returns the value of a request parameter as a String, or null if the
parameter does not exist.
• Map getParameterMap()
– Returns a java.util.Map of the parameters
• Enumeration getParameterNames()
– Returns an Enumeration of String objects containing the names of the
parameters
• String[] getParameterValues(String name)
– Returns an array of String objects containing all of the values the given
request parameter has, or null if the parameter does not exist.
Request Parameters
• JSP provides access to the implicit object request that stores
attributes related to the request for the JSP page as parameters,
the request type and the incoming HTTP headers (cookies,
referer, etc.).
• Example Request:
– http://localhost/example.jsp? param1=hello¶m2=world
<html> <html>
<body> <body>
<p><%= request.getParameter(“param1”) %></p> <p>Hello</p>
<p><%= request.getParameter(“param2”) %></p> <p>World</p>
</body> </body>
</html> </html>
Q&A