1
(Server-Side Programming using Java Server Pages)
cs236607
2
Many HTML Pages are Mostly StaticServlets allow us to write dynamic Web pages
Easy access to request, session and context dataEasy manipulation of the response (cookies, etc.)And lots more...
It is very inconvenient to write and maintain long and mostly static HTML pages using Servlets (even though such pages are very common)
out.println("<h1>Bla Bla</h1>" + "bla bla bla bla" + "lots more here...")
cs236607
3
Introducing JSPThe Idea:
Use HTML for most of the pageWrite Servlet code directly in the HTML page,
marked with special tagsThe server automatically translates a JSP
page to a Servlet class and invokes this servletIn Tomcat 5.5, you can find the generated
Servlet code under $CATALINA_BASE/work/
cs236607
A JSP is no more than a convenient way to write Servlets that output textual data
4
RelationshipsServlets: HTML code is printed using Java
codeJSP: Java code is embedded in HTML codeNot only for HTML!
JSP can be used for any textual format Servlets can be used for any data!
Java
HTML
HTML
JAVA
cs236607
5
Example<html>
<head>
<title>Hello World</title>
</head>
<body>
<h2><%= new java.util.Date() %></h2>
<h1>Hello World</h1>
</body>
</html>
cs236607
cs236607 6
The file dates.jsp is inC:\Program Files\Tomcat 5.5\webapps\Examples\($CATALINA_BASE\webapps\MyApplication\)
The file dates.jsp is inC:\Program Files\Tomcat 5.5\webapps\Examples\($CATALINA_BASE\webapps\MyApplication\)
The urlhttp://ibm373.cs.technion.ac.il:8080/Examples/dates.jspThe urlhttp://ibm373.cs.technion.ac.il:8080/Examples/dates.jsp
Translation to Servlet
cs236607 7
package org.apache.jsp;
import javax.servlet.*;import javax.servlet.http.*;import javax.servlet.jsp.*;
public final class dates_jsp extends org.apache.jasper.runtime.HttpJspBase implements org.apache.jasper.runtime.JspSourceDependent {
private static java.util.List _jspx_dependants;
public Object getDependants() { return _jspx_dependants; }
public void _jspService(HttpServletRequest request, HttpServletResponse response) throws java.io.IOException, ServletException {
JspFactory _jspxFactory = null; PageContext pageContext = null; HttpSession session = null; ServletContext application = null; ServletConfig config = null; JspWriter out = null; Object page = this; JspWriter _jspx_out = null; PageContext _jspx_page_context = null;
C:\Program Files\Tomcat 5.5\webapps\Examples\work\org\apache\jsp\dates_jsp.java
cs236607 8
try { _jspxFactory = JspFactory.getDefaultFactory(); response.setContentType("text/html"); pageContext = _jspxFactory.getPageContext(this, request, response, null, true, 8192, true); _jspx_page_context = pageContext; application = pageContext.getServletContext(); config = pageContext.getServletConfig(); session = pageContext.getSession(); out = pageContext.getOut(); _jspx_out = out;
out.write("<html>\r\n"); out.write(" <head>\r\n"); out.write(" <title>Hello World</title>\r\n"); out.write(" </head>\r\n"); out.write(" <body>\r\n"); out.write(" <h2>"); out.print( new java.util.Date() ); out.write("</h2> \r\n"); out.write(" <h1>Hello World</h1>\r\n"); out.write(" </body>\r\n"); out.write("</html>\r\n"); } catch (Throwable t) { if (!(t instanceof SkipPageException)){ out = _jspx_out; if (out != null && out.getBufferSize() != 0) out.clearBuffer(); if (_jspx_page_context != null) _jspx_page_context.handlePageException(t); } } finally { if (_jspxFactory != null) _jspxFactory.releasePageContext(_jspx_page_context); } }}
9
Generated Servlet Hierarchy(Tomcat 5 Implementation)
ApacheImplementation
GeneratedServlet
SunSpecifications
GenericServlet
Servlet
JspPage
HttpJspPageHttpServlet
HttpJspBase
mypage_jsp
classes interfaces
Abstract class extended by every generated Servlet
cs236607
10
JSP Limitations and AdvantagesJSP can only do what a Servlet can doEasier to write and maintain HTMLEasier to separate HTML from codeCan be created using a "reverse engineering
technique":Create static HTML and then replace static
data with Java code
cs236607
11cs236607
12
JSP Life CycleRequest
#1
Request
#2
Request
#3
Request
#4
Request
#5
Request
#6
JSP page
translated into
servlet
Yes No No No Yes No
JSP’s Servlet
compiled
Yes No No No Yes No
Servlet
instantiated and
loaded into
server's memory
Yes No Yes No Yes No
init (or
equivalent) called
Yes No Yes No Yes No
doGet (or
equivalent) called
Yes Yes Yes Yes Yes Yes
Written by Marty Hall. Core Servlets & JSP book: www.coreservlets.com
Pag
e fi
rst writte
n
Serve
r resta
rted
Pag
e m
od
ified
Translation & compilation
only after first call…
13
JSP TranslationWhen the JSP file is modified, JSP is translated into
a Servlet But only after the JSP’s url is requested by a clientApplication is not necessarily reloaded when JSP file is
modifiedServer does not generate the Servlet class
after startup, if the latter already exists and isn’t too oldGenerated Servlet acts just like any other Servlet
The generated servlet can handle GET, POST, HEAD requests though it does not implement doGet(), doPost(), doHead() explicitlyIts Servlet.service() method calls the newly implemented
main method named HttpJspBase._jspService()
JSP file named file.jsp will be
translated into the Java file
file_jsp.java
cs236607
14
init() and destroy()init() of the generated Servlet is called every
time the Servlet class is loaded into memory and instantiated
destroy() of the generated Servlet is called every time the generated Servlet is removed
init() and destroy() are called even when the reason for loading is a modification of the JSP file
cs236607
15
jspInit and jspDestroyIn JSP pages, like regular Servlets, we
sometimes want to implement init and destroyIt is illegal to use JSP declarations to override
init or destroy, since they are (usually) already implemented by the generated Servlet
Instead, override the methods jspInit() and jspDestroy()The generated servlet is guaranteed to call these
methods from init and destroy, respectivelyThe standard versions of jspInit and jspDestroy are
empty (placeholders for you to override)
cs236607
16
Thread SynchronizationAfter the Servlet is generated, one instance
of it serves requests in different threads, just like any other Servlet
In particular, the service method (_jspService) may be executed by several concurrent threads
Thus, as with Servlets, JSP programming requires handling concurrency
cs236607
17cs236607
18
Basic Elements in a JSP fileHTML code: <html-tag>content</html-tag>JSP Comments: <%-- comment --%>Expressions: <%= expression %>Scriptlets (statements): <% code %>Declarations: <%! code %>Directives: <%@ directive attribute="value" %> Actions: <jsp:forward.../>, <jsp:include.../>Expression-Language Expressions: $
{expression}
cs236607
19
JSP ExpressionsA JSP expression is being used to insert
Java values directly into the outputIt has the form: <%= expression %> , where
expression can be a Java object, a numerical expression, a method call that returns a value, etc...
For example: <%= new java.util.Date() %>
<%= "Hello"+" World" %>
<%= (int)(100*Math.random()) %>
The heading space and the
following space are not created in the
result.
Use “ “ if you want a real
spacecs236607
20
JSP ExpressionsWithin the generated Java code
A JSP Expression is evaluatedThe result is converted to a stringThe string is inserted into the page
This evaluation is performed at runtime (when the page is requested), and thus has full access to information about the request, the session, etc...
cs236607
21
<h1>A Random Number</h1><%= Math.random() %>
public void _jspService(HttpServletRequest request, HttpServletResponse response)
throws java.io.IOException, ServletException { ... response.setContentType("text/html"); ... out.write("<h1>A Random Number</h1>\r\n"); out.print( Math.random() );
out.write("\r\n"); ...
}
The generated servlet calls
out.write() for Strings, and out.print() for
objects
Default content-
type
cs236607
22
Predefined Variables (Implicit Objects)The following predefined variables can be
used:request: the HttpServletRequestresponse: the HttpServletResponse session: the HttpSession associated with the
requestout: the PrintWriter (a buffered version of type
JspWriter) used to fill the response contentapplication: The ServletContextconfig: The ServletConfig
cs236607
23
<html> <head> <title>JSP Expressions</title> </head> <body> <h2>JSP Expressions</h2> <ul> <li>Current time: <%= new java.util.Date() %></li> <li>Your hostname:<%= request.getRemoteHost() %></li> <li>Your session ID: <%= session.getId() %></li> <li>The <code>testParam</code> form parameter: <%= request.getParameter("testParam") %></li> </ul> </body></html>
cs236607
cs236607 24
25
JSP Scriplets (Statements)JSP scriptlets let you insert arbitrary code into
the Servlet service method ( _jspService )
Scriptlets have the form: <% Java Code %> The code is inserted verbatim into the service
method, according to the location of the scriptlet
Scriptlets have access to the same automatically defined variables as expressions
cs236607
26
<%= foo() %> <% bar(); %>
public void _jspService(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
...response.setContentType("text/html");...out.print(foo());bar();...
}cs236607
27
A Divided-Code ExampleScriptlets don't have to be complete code blocks:
<% if (Math.random() < 0.5) { %> You <b>won</b> the game! <% } else { %> You <b>lost</b> the game! <% } %>
if (Math.random() < 0.5) { out.write("You <b>won</b> the game!"); } else { out.write("You <b>lost</b> the game!"); }
cs236607
28
JSP DeclarationsA JSP declaration lets you define methods or
members that are being inserted into the Servlet class (outside of all methods)
It has the following form: <%! Java Code %>
For example: <%! private int someField = 5; %>
<%! private void someMethod(...) {...} %>JSPs are intended to contain a minimal
amount of code so it is usually of better design to define methods in a separate Java class...
cs236607
29
Declaration ExamplePrint the number of times the current page has
been requested since the Servlet initialization:
<%! private int accessCount = 0; %>
<%! private synchronized int incAccess() {
return ++accessCount;
} %>
<h1>Accesses to page since Servlet init:
<%= incAccess() %> </h1>
cs236607
30
public class serviceCount_jsp extends... implements... throws... {
private int accessCount = 0;
private synchronized int incAccess() {
return ++accessCount;
} public void _jspService(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException { ... ... out.write("<h1>Accesses to page since Servlet init: "); out.print(incAccess()); ... } ... }
Generated
Servlet
Java permits variable
initialization on declaration, even if the location is
outside any method’s scope
cs236607
31
JSP DirectivesA JSP directive affects the structure of the
Servlet class that is generated from the JSP page
It usually has the following form: <%@ directive attribute1="value1" ...
attributeN="valueN" %>Three important directives: page, include
and taglib
cs236607
32
page-Directive Attributesimport attribute: A comma separated list of
classes/packages to import
<%@ page import="java.util.*, java.io.*" %>
contentType attribute: Sets the MIME-Type of the resulting document (default is text/html)
<%@ page contentType="text/plain" %>
cs236607
33
page-Directive Attributes (cont)
What is the difference between setting the page contentType attribute, and writing <%response.setContentType("...");%>?In the latter case, the new servlet will call
response.setContentType() twiceThe first, impicit (from the JSP point of view), call will be
with the default content type.The second, explicit, call might even come after the
buffer was flushed or after the writer was obtained…
cs236607
34
page-Directive Attributes (cont)
session="true|false" specifies if to use a session?
buffer="sizekb|none|8kb" Specifies the content-buffer (out) size in kilo-
bytes
autoFlush="true|false"Specifies whether the buffer should be flushed
when it fills, or throw an exception otherwise
isELIgnored ="true|false" Specifies whether JSP expression language is
usedThe underlined values are the
defaultscs236607
35cs236607
36
JSP Initial ParametersLike Servlets, initialization parameters can be
passed to JSP files using the <servlet> element of the application configuration file web.xml
Use the sub-element <jsp-file> instead of the sub-element <servlet-class>
Since a <servlet> element is being used, a <servlet-mapping> element is also neededUse the real JSP URL as the <jsp-file>Remember that just like in servlets mapping, you
have the flexibility of being able to map several URLs to the same jsp or servlet, each with different init parameters.
cs236607
37
<web-app>
<context-param>
<param-name>dbLogin</param-name>
<param-value>homer</param-value>
</context-param>
<context-param>
<param-name>dbPassword</param-name>
<param-value>doughnuts</param-value>
</context-param>
An Exampleweb.xml
Initialization parameterswhose scope is application
cs236607
38
<servlet>
<servlet-name>ParamPage</servlet-name>
<jsp-file>/paramPage.jsp</jsp-file>
<init-param>
<param-name>tableName</param-name>
<param-value>users</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>ParamPage</servlet-name>
<url-pattern>/paramPage.jsp</url-pattern>
</servlet-mapping>
</web-app>
web.xml
JSP scoped initialization parameters
In the case of JSP, the relative location of the JSP (relative to the application’s root directory) should be given instead of the Servlet classname, since the Servlet is created dynamically by the container
You can also map a different URL to this JSP (highly useful if you need the URL to end with an extension other than .jsp)cs236607
39
<html>
<head><title>JSP initial parameters</title></head>
<body>
<h1>Hello</h1>
<h2>I should use the table
<i><%= config.getInitParameter("tableName") %></i>
</h2>
<h2>To access the Database, I should use the login
<i><%= application.getInitParameter("dbLogin") %></i>
and the password
<i><%= application.getInitParameter("dbPassword") %></i>.
</h2>
</body>
</html>
paramPage.jsp
JSP scoped initialization parameters
Application scoped initialization parameters
You can omit the config and call getInitParameter() directly, since the generated servlet extends HttpJspBase which extends HttpServlet which implements the ServletConfig interface
Reminder: this is equivalent to getServletContext().getInitParameter() within a Servlet
cs236607
40cs236607
41
JSP CooperationWe will consider several ways in which JSP
and other resources cooperateForwarding the request handling to other
resourcesIncluding the content of other sourcesIncluding the code of other JSP filesForwarding exception handling to other JSPs
cs236607
42
ActionsJSP actions use constructs in XML syntax to
control the behavior of the Servlet engineUsing actions, you can
forward the request to another resource in the application
dynamically include a resource content in the response
Forward and include are translated to an invocation of the RequestDispatcher
43
The forward Actionjsp:forward - Forwards the requester to a new
resource
<jsp:forward page="{relativeURL|<%= expression %>}">
<jsp:param name="parameterName"
value="{parameterValue | <%= expression %>}" /> *
</jsp:forward>
You can use %=, % instead of <%=, %> so that the code would be a legal XML
0 or more parameters (not attributes!)added to the original request parameters
cs236607
44
<%! int even = 0; %><% even = (1 - even); %><% if (even == 0) { %>
<jsp:forward page="/requestParams.jsp" ><jsp:param name="sessionID" value="<%= session.getId() %>" /><jsp:param name="even" value="true" />
</jsp:forward><% } else { %>
<jsp:forward page="/requestParams.jsp" ><jsp:param name="sessionID" value="<%= session.getId() %>" /><jsp:param name="even" value="false" />
</jsp:forward><% } %>
Forward Action Example
cs236607
45
<html>
<head><title>Print Request Params</title></head>
<body>
<%@ page import="java.util.*" %>
<% Enumeration parameterNames = request.getParameterNames(); %>
<% while (parameterNames.hasMoreElements()) { %>
<% String name = (String)parameterNames.nextElement(); %>
<h2><%= name %> : <%= request.getParameter(name) %> </h2>
<% } %>
</body>
</html>
requestParams.jsp
cs236607
46
The include Actionjsp:include - Include a resource content
at run time
<jsp:include page="{relativeURL|<%= expression %>}">
<jsp:param name="parameterName"
value="{parameterValue | <%= expression %>}" />*
</jsp:include>
0 or more parametersadded to the original request parameters
cs236607
47
<html> <head> <title>Include (action) Example</title> </head> <body> <h2>Included part begins:<h2><hr/> <jsp:include page="/requestParams2.jsp" >
<jsp:param name="sessionID" value="<%= session.getId() %>" /> </jsp:include> <hr/><h2>Included part ends<h2> </body></html>
Include Action Example
include.jsp
cs236607
48
<%@ page import="java.util.*" %>
<% Enumeration parameterNames = request.getParameterNames(); %>
<% while (parameterNames.hasMoreElements()) { %>
<% String name = (String)parameterNames.nextElement(); %>
<h2><%= name %> : <%= request.getParameter(name) %> </h2>
<% } %>requestParams2.jsp
requestParams2.jsp is different from requestParams.jsp in not having the preceding and following html tags (otherwise the output HTML code would have <html>, <head> and <body> duplicated)
cs236607
49
The include DirectiveThis directive lets you include files at the
time the JSP page is translated into a Servlet
The directive looks like this: <%@ include file="url" %>
Included JSP content can affect main JSP pagee.g. included page directive can affect the result
ContentTypeAs of Tomcat 5.x, generated Servlets are
updated when included files change (unlike older versions...)
cs236607
50
Include - Action
File1.jsp
Servlet1
File2.jsp Servlet2
HTMLcontent
HTMLcontent
HTMLcontent
Using RequestDispatcher
Main JSP
cs236607
51
Include Directive
File1.jsp
File2.jspServlet
HTMLcontent
cs236607
52
include Action vs. DirectiveWhen a resource is included using the include
action, the generated Servlet uses the dispatcher to include its content at runtime (so the resource needs not be a JSP or even a Servlet)
When a file is included using the include directive, the file itself is included verbatim into the JSP code, prior to the Servlet generation (so the included resource must have JSP syntax)
In which of the above cases can the included resource change the HTTP headers or status?
cs236607
53
<html> <head><title>Including JSP</title></head><body> <h2>Here is an interesting page.</h2> <p>Bla, Bla, Bla, Bla.</p> <%@ include file="/AccessCount.jsp" %> <jsp:include page="/mymail.jsp"/> </body></html>
BlaBla.jsp
<%! private int accessCount = 0; %> <hr><p>Accesses to page since Servlet init: <%= ++accessCount %></p>
<hr><p>Page Created for Simpsons at <%= new java.util.Date() %>. Email <a href="mailto:[email protected]">here</a>. </p>
AccessCount.jsp
mymail.jsp
cs236607
54
out.write("<html>\r\n");out.write(" <head><title>Including JSP</title></head>\r\n");out.write(" <body>\r\n");out.write(" <h2>Here is an interesting page.</h2>\r\n");out.write(" <p>Bla, Bla, Bla, Bla.</p>\r\n");out.write("<hr>\r\n");out.write("<p> \r\n");out.write(" Accesses to page since Servlet init: \r\n");out.print( ++accessCount );out.write("</p>\r\n");org.apache.jasper.runtime.JspRuntimeLibrary.
include(request, response, "/mymail.jsp", out, false);out.write(" </body>\r\n");out.write("</html>\r\n");
BlaBla_jsp.java
Original JSP
Included JSP
Similar to RequestDispatcher().include()Original
JSPcs236607
55
Error PagesWe can set one JSP page to be the handler of
uncaught exceptions of another JSP page, using JSP directivesThe default behaviour is displaying a
500 Internal Server Error with a partialstack trace with other exception infoto the client (ugly and a security risk)
You can log the entire stack trace alongwith other data for easier debugging
<%@ page errorPage="url " %>Defines a JSP page that handles uncaught exceptionsThe page in url should have true in the page-directive:
<%@ page isErrorPage="true|false" %>The variable exception holds the exception thrown by
the calling JSPCreating an error page without isErrorPage=true, is legal but the exception object is not created in the generated Servlet. If you refer to exception in such a JSP, you’ll have a compilation error…
Runtime exceptions or other exceptions which are declared as thrown by methods your JSP code use.Other exceptions cannot be thrown or else your generated servlet code wouldn’t compile
cs236607
56
<html> <head><title>Reading From Database </title></head> <body> <%@ page import="java.sql.*" %> <%@ page errorPage="errorPage.jsp" %> <% Class.forName(“com.mysql.jdbc.Driver"); Connection con = DriverManager.getConnection (“jdbc:mysql://ibm262.cs.technion.ac.il:3306/homerDB”, “homer“, “doughnuts”); %> <h2>Can Connect!!</h2> </body></html>
connect.jsp
Reminder:• The driver is loaded dynamically• Creates an instance of itself• Register this instance with the DriverManager
cs236607
57
<html> <head><title>Connection Error</title></head> <body> <%@ page import="java.io.*" %> <%@ page isErrorPage="true" %> <h1>Oops. There was an error when you accessed the database.</h1> <h2>Here is the stack trace:</h2> <pre style="color:red"> <% exception.printStackTrace(new PrintWriter(out)); %> </pre> </body></html>
errorPage.jsp
cs236607
LinksJSP Tutorial:
http://courses.coreservlets.com/Course-Materials/csajsp2.html
Advanced Tutorials: http://courses.coreservlets.com/Course-Materials/msajsp.html
JSP API: http://tomcat.apache.org/tomcat-5.5-doc/jspapi/
JSP Syntax Reference: http://java.sun.com/products/jsp/syntax/2.0/syntaxref20.htmlcs236607 58