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
CSC 2720
Building Web Applications
JavaServer Pages (JSP)
The Basics
The JSP Framework
JavaServer Pages (JSP) is a Java technology that allows
Java code and certain pre-defined actions to be embedded
into static content.
JSPs are compiled into Java Servlets by a JSP compiler.
Architecturally, JSP can be viewed as a high-level
abstraction of servlets that is implemented as an extension
of the Servlet API.
Ref: Wikipedia
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<%-- This is a comment in JSP --%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%
String param = request.getParameter("ParamName");
%>
<html>
<head>
<title>My first JSP page
</title>
</head>
<body>
Parameter value is <%= param %>.
</body>
</html>
A JSP file interweaved with HTML codes and JSP scriplets
JSP vs. Servlet
A JavaServer page can be viewed a Java class written in
"different language".
A JavaServer page is first compiled into a Servlet class and
then into Java byte code.
It has the same lifecycle as a servlet (init, serve, destroy)
JSP (corresponding class)
Servlet
jspInit()
init()
jspDestroy()
destroy()
_jspService(request,
response)
service(request, response)
Static contents, <% … %>, and <%= … %> elements in a JSP Page are translated
into Java codes and placed in _jspService()
JSP Syntax
A JavaServer Page may be broken down into the following
pieces:
Static data such as HTML
JSP scripting elements and variables
JSP actions
JSP directives
Custom tags with correct library
Predefined Variables (Implicit Objects)
These objects are automatically made available in a JSP
page (they are declared as local variables in
_jspService())
request
The HttpServletRequest object
response
The HttpServletResponse object
out
The stream (of type JspWriter) used to send output to the client
application
An instance of ServletContext. It is the object obtained by
invoking getServletContext(). We can use this object to share
data among all servlets and JSP pages in the same application.
Predefined Variables (Implicit Objects)
session
The HttpSession object associated with the request (unless disabled
with the session attribute of the page directive)
page
The servlet itself (for self reference).
pageContext
A PageContext instance that contains data associated with the
whole page.
config
An instance of ServletConfig. It is the object obtained by calling
getServletConfig().
exception
Represent an exception not caught by the application code in an
"Error handling JSP page".
Implicit objects and their corresponding class
application: javax.servlet.ServletContext
config: javax.servlet.ServletConfig
exception: java.lang.Throwable
out: javax.servlet.jsp.JspWriter
page: java.lang.Object
pageContext: javax.servlet.jsp.PageContext
request: javax.servlet.ServletRequest
response: javax.servlet.ServletResponse
session: javax.servlet.http.HttpSession
JSP Elements
Three types of JSP elements:
Directive elements
Scripting elements
Action elements
JSP Elements have two forms:
the XML form
the <% … %> alternative form
Comments
Comments
<%-- JSP comment --%>
Discarded by JSP container
Won't appear in the output
<!-- HTML comment -->
Treated as template data.
Reproduced in the output
Note:
<!-- <%= 3+4 %> -->
is produced as
<!-- 7 -->
Scripting Elements
Allow you to insert Java code in JSP pages.
Three types:
Expressions
<%= Expression %>
Scriplets
<% Java code %>
Declarations
<%! Declaring methods or instance variables %>
Expressions
Format: <%= Java Expression %>
Result
The element is replaced by the evaluated result of the expression
in the output.
Examples
Current time: <%= new java.util.Date() %>
Your hostname: <%= request.getRemoteHost() %>
3 * 4 + 5 = <%= 3 * 4 + 5 %>
XML-compatible syntax
<jsp:expression>Java Expression</jsp:expression>
Scriptlets
Format: <% Java Code %>
Result
Code is inserted verbatim into servlet's _jspService()
Examples
<%
String queryData = request.getQueryString();
out.println("Attached GET data: " + queryData);
%>
<% response.setContentType("text/plain"); %>
XML-compatible syntax
<jsp:scriptlet>Java Code</jsp:scriptlet>
JSP/Servlet Correspondence
Scriptlets in JSP:
<%= foo() %>
<% bar(); %>
No ';' after foo() as it represents
an expression and not a
statement
Possible resulting servlet code:
public void _jspService(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
// Initialization code
...
out.println(foo());
bar();
...
}
<%
JSP
for (int i=100; i>=0; i--)
{
%>
<%= i %> bottles of beer on the
wall.<br>
<%
}
%>
Resulting Servlet
for (int i=100; i>=0; i--)
{
out.println(i);
out.println(" bottles of beer
on the wall.<br>");
}
JSP Scriptlets
Example
Output appears in browser
100 bottles of beer on the wall.
99 bottles of beer on the wall.
98 bottles of beer on the wall.
97 bottles of beer on the wall.
96 bottles of beer on the wall.
95 bottles of beer on the wall.
94 bottles of beer on the wall.
…
Example Using JSP Scriptlets
<HTML>
<HEAD>
<TITLE>Color Testing</TITLE>
</HEAD>
<%
String bgColor = request.getParameter("bgColor");
boolean hasExplicitColor;
if (bgColor != null)
hasExplicitColor = true;
else {
hasExplicitColor = false;
bgColor = "WHITE";
}
%>
<BODY BGCOLOR="<%= bgColor %>">
…
</BODY></HTML>
Declarations
Format: <%! Java Code %>
Result
Code is inserted verbatim into servlet's class definition,
outside of any existing methods
Use this to introduce instance/static variables and
methods
Examples
<%! private int someField = 5; %>
<%! private void someMethod(...) {...} %>
XML-compatible syntax
<jsp:declaration>Java Code</jsp:declaration>
Original JSP
<H1>Some Heading</H1>
<%!
private String randomHeading() {
return("<H2>" + Math.random() + "</H2>");
}
%>
<%= randomHeading() %>
Possible resulting servlet code
public class xxxx implements HttpJspPage {
private String randomHeading() {
return("<H2>" + Math.random() + "</H2>");
}
public void _jspService(HttpServletRequest request,
HttpServletResponse response) throws
ServletException, IOException {
...
out.println("<H1>Some Heading</H1>");
out.println(randomHeading());
...
}
JSP/Servlet Correspondence
Original JSP
<%! int age1 = 100; %>
<% int age2 = 100; %>
Possible resulting servlet code
public class xxxx implements HttpJspPage {
int age1 = 100;
public void _jspService(HttpServletRequest request,
HttpServletResponse response) throws
ServletException, IOException {
...
int age2 = 100;
...
}
JSP/Servlet Correspondence (Declaration vs. Sniplet)
Example: JSP Tags + HTML Tags
<h2>Table of Square Roots</h2>
<table border="2">
<tr>
<td><b>Number</b></td>
<td><b>Square Root</b></td>
</tr>
<%
for (int n=0; n<=100; n++)
{
%>
<tr>
<td><%=n%></td>
<td><%=Math.sqrt(n)%></td>
</tr>
<%
}
%>
</table>
References
Wikipedia: JavaServer Pages
http://en.wikipedia.org/wiki/JavaServer_Pages
Free Tutorial (Java, JSP, Java Servlets)
http://www.courses.coreservlets.com/Course-Materials/
Sample JSP codes
http://www.java2s.com/Code/Java/JSP/CatalogJSP.htm