Upload
tamsyn-francis
View
215
Download
1
Embed Size (px)
Citation preview
1
JSP – Java Server PagesJSP – Java Server Pages
Representation and
Management of Data on the
Internet
2
What is JSP Good For?What is JSP Good For?
• Servlets allow us to easily:– read data from user
– read HTTP request
– create cookies
– etc.
• It is not convenient to write long static HTML using Servlets– out.println("<h1>Bla Bla</h1>" + "bla bla bla
bla bla " + " lots more here...")
3
JSP IdeaJSP Idea
• Use HTML for most of the page
• Write Java code directly in the HTML
page (similar to Javascript)
• Automatically translate JSP to Servlet
that actually runs
4
RelationshipsRelationships
• In servlets: HTML code is printed from
java code
• In JSP pages: Java code is embedded in
HTML code
Java
HTMLJava
HTML
5
ExampleExample
<HTML>
<HEAD>
<TITLE>Hello World Example</TITLE>
</HEAD>
<BODY>
<H2>Hello World Example</H2>
<B>Hello <% =request.getParameter("name") %>!</B>
</BODY>
</HTML>
6
Page is in the proj web application: tomcat_home/webapps/proj/HelloWorld.jsp
Invoked with URL:http://<host>:<port>/proj/HelloWorld.jsp?name=snoopy
7
Invoked with URL (no parameter):http://<host>:<port>/proj/HelloWorld.jsp
8
JSP Limitations and JSP Limitations and AdvantagesAdvantages
• JSP can only do what a Servlet can do
• Easier to write and maintain HTML
• Easier to separate HTML from code
• Can use a "reverse engineering
technique": create static HTML and
then replace static data with Java code
9
What does a JSP-Enabled What does a JSP-Enabled Server do?Server do?
• receives a request for a .jsp page
• parses it
• converts it to a Servlet (JspPage) with
your code inside the _jspService()
method
• runs it
10
Translation of JSP to Translation of JSP to ServletServlet
• Two phases:
– Page translation: JSP is translated to a
Servlet. Happens the first time the JSP is
accessed
– Request time: When page is requested,
Servlet runs
• No interpretation of JSP at request
time!
11
Design StategyDesign Stategy
• Do not put lengthy code in JSP page
• Do put lengthy code in a Java class and call
it from the JSP page
• Why? Easier for
– Development (written separately)
– Debugging (find errors when compiling)
– Testing
– Code Reuse
12
The Source CodeThe Source Code
• In Tomcat 3.2.1, you can find the generated
Java and the class files in a subdirectory
under tomcat_home/work.
13
JSP Scripting ElementsJSP Scripting Elements
• Scripting elements let you insert code into the servlet that will be generated from the JSP
• Three forms: – Expressions of the form <%= expression %> that are
evaluated and inserted into the output,
– Scriptlets of the form <% code %> that are inserted into the servlet's _jspService method, and
– Declarations of the form <%! code %> that are inserted into the servlet class, outside of any methods
14
JSP ExpressionsJSP Expressions
• A JSP expression is used to insert Java
values directly into the output
• It has the following form:
<%= Java Expression %>
• Example:
– <%= Math.random() %>
15
JSP ExpressionsJSP Expressions
• A JSP Expression is evaluated
• The result is converted to a string
• The 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
16
Expression TranslationExpression Translation
<H1>A Random Number</H1><%= Math.random() %>
public void _jspService(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setContentType("text/html");HttpSession session = request.getSession(true);JspWriter out = response.getWriter();out.println("<H1>A Random Number</H1>");out.println(Math.random());...
}
17
Predefined VariablesPredefined Variables
• The following predefined variables can be
used:
– request, the HttpServletRequest
– response, the HttpServletResponse
– session, the HttpSession associated with the
request
– out, the PrintWriter (a buffered version of type
JspWriter) used to send output to the client
18
<HTML>
<HEAD> <TITLE>JSP Expressions</TITLE></HEAD>
<BODY>
<H2>JSP Expressions</H2>
<UL>
<LI>Current time: <%= new java.util.Date() %>
<LI>Your hostname: <%= request.getRemoteHost() %>
<LI>Your session ID: <%= session.getId() %>
<LI>The <CODE>testParam</CODE>
form parameter:
<%= request.getParameter("testParam") %>
</UL>
</BODY>
</HTML>
19
Encoded
Unencoded
20
JSP ScripletsJSP Scriplets
• JSP scriptlets let you insert arbitrary code
into the servlet method that will be built to
generate the page ( _jspService )
• Scriptlets have the following form:
<% Java Code %>
• Scriptlets have access to the same
automatically defined variables as
expressions. Why?
21
<%= foo() %><% bar(); %>
public void _jspService(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
request.setContentType("text/html");HttpSession session = request.getSession(true);JspWriter out = response.getWriter();out.println(foo());bar();...
}
Scriptlet TranslationScriptlet Translation
22
Producing CodeProducing Code
• Scriptlets can produce output by printing into
the out variable
• Example:
<%
String queryData = request.getQueryString();
out.println("Attached GET data: " + queryData);
%>
• Would we want to use a scriptlet in this case?
23
HTML Code in ScriptletsHTML Code in Scriptlets
• Scriptlets don't have to be entire
Java Staments:<% if (Math.random() < 0.5) { %> You <B>won</B> the game! <% } else { %> You <B>lost</B> the game! <% } %>
if (Math.random() < 0.5) { out.println("You <B>won</B> the game!"); } else { out.println("You <B>lost</B> the game!"); }
24
JSP DeclarationJSP Declaration
• A JSP declaration lets you define methods or fields that get inserted into the servlet class (outside of all methods)
• It has the following form:
<%! Java Code %>
• Declarations do not produce output
• They are used to define variables and methods
• Should you define a method in a JSP declaration?
25
Declaration ExampleDeclaration Example
• Print the number of times the current page has
been requested since the server booted (or the
servlet class was changed and reloaded):
<%! private int accessCount = 0; %>
<%! private synchronized int incAccess() {
return ++access;
} %>
Accesses to page since server reboot:
<%= incAccess() %>
• Should accessCount be static?
26
public class xxxx implements HttpJspPage {
private int accessCount = 0; private synchronized int incAccess() { return ++access; }
public void _jspService(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); HttpSession session = request.getSession(true); JspWriter out = response.getWriter();
out.println("Accesses to page since server reboot: "); out.println(incAccess()); ... } ...}
27
Predefined VariablesPredefined Variables
• As we have seen before, there are variables
that can be used in the code
• There are eight automatically defined
variables, sometimes called implicit objects
• We saw 4 variables: request, response, out,
session
• Other 4 variables: application, config,
pageContext, page
28
More Details: request, More Details: request, responseresponse
• request: the HttpServletRequest
• response: the HttpServletResponse
• The output stream is buffered
• It is legal to set HTTP status codes and
response headers, even though this is not
permitted in regular servlets once any
output has been sent to the client
• Use request to save page specific values
29
More Details: outMore Details: out
• This is the PrintWriter used to send
output to the client
• Actually a buffered version of
PrintWriter called JspWriter
• You can adjust the buffer size, or even
turn buffering off, through use of the
buffer attribute of the page directive
30
More Details: sessionMore Details: session
• This is the HttpSession object associated
with the request
• Sessions are created automatically, so this
variable is bound even if there was no
incoming session reference (unless session
was turned off using the session attribute of
the page directive)
• Use session to store client specific values
31
Another Variable: Another Variable: applicationapplication
• This is the ServletContext as obtained via getServletConfig().getContext()
• Remember:– Servlets and JSP pages can hold constant data in the
ServletContext object
– Getting and setting attributes is with getAttribute and setAttribute
– The ServletContext is shared by all the servlets in the server
• Use application to store web application specific values
32
Another Variable: configAnother Variable: config
• This is the ServletConfig of the page,
as received in init method
• Remember: Contains Servlet specific
initialization parameters
33
Another Variable: Another Variable: pageContextpageContext
• pageContext encapsulates use of
server-specific features like higher
performance JspWriters
• Access server-specific features through
this class rather than directly, your
code will still run on "regular"
servlet/JSP engines
34
Another Variable: pageAnother Variable: page
• Simply a synonym for this
• page is not very useful in JSP pages
• It was created as a placeholder for the
time when the scripting language could
be something other than Java
35
Note about Predefined Note about Predefined VariablesVariables
• Predefined variables are local to the
_jspService method.
• How can we use them in methods that
we define?
• When using out in a method, note that
it might throw a IOException
36
JSP DirectivesJSP Directives
• A JSP directive affects the structure of the servlet class that is created from the JSP page
• It usually has the following form:
<%@ directive attribute="value" %>
• Multiple attribute settings for a single directive can be combined:
<%@ directive
attribute1="value1"
...
attributeN="valueN" %>
37
Three Types of DirectivesThree Types of Directives
• page, which lets you do things like
– import classes
– customize the servlet superclass
• include, which lets you insert a file into the
servlet class at the time the JSP file is
translated into a servlet
• taglib, which indicates a library of custom
tags that the page can include
38
page Directive Attributespage Directive Attributes
• import attribute: A comma seperated 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" %>
• Note that instead of using the contentType attribute, you can write
<% response.setContentType("text/plain"); %>
39
More page Directive More page Directive AttributesAttributes
• isThreadSafe=“true|false”– false indicates that the Servlet should implement
the SingleThreadModel
• session=“true|false”– false indicates that a session should not be created
– Saves memory
– All related pages must do this!!!
• buffer=“sizekb|none”– specifies the buffer size for the JspWriter out
Default is Server Dependant
40
More page Directive More page Directive AttributesAttributes
• autoflush=“true|false”
– Flush buffer when full or throws an exception when
buffer isfull
• extends=“package.class”
– Makes Servlet created a subclass of class supplied
– Don't use this! Why?
• info=“message”
– A message for the getServletInfo method
41
More page Directive More page Directive AttributesAttributes
• errorPage=“url”
– Define a JSP page that handles uncaught
exceptions
– available to next page by exception
variable
– example
• isErrorPage=“true|false”
– allows the page to be an error page
42
<HTML>
<HEAD> <TITLE>Reading From Database</TITLE></HEAD>
<BODY>
<%@ page import="java.sql.*" %>
<%@ page errorPage="Error.jsp" %>
<% Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con =
DriverManager.getConnection("jdbc:oracle:thin:" +
"snoopy/snoopy@sol4:1521:stud");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("Select * from a");
ResultSetMetaData md = rs.getMetaData();
int col = md.getColumnCount();
%>
43
<TABLE border="2">
<% while (rs.next()) { %>
<TR>
<% for (int i = 1 ; i <= col ; i++) { %>
<TD><%= rs.getString(i) %></TD>
<% } %>
</TR>
<% } %>
</TABLE>
</BODY>
</HTML>Note: Is this a convenient way to print out a table?
What would be a better way?
44
<HTML>
<HEAD> <TITLE>Reading From Database</TITLE></HEAD>
<BODY>
<%@ page isErrorPage="true" %>
Oops. There was an error when you accessed the database. <br>
Here is the stack trace: <br> <br>
<pre>
<% exception.printStackTrace(new java.io.PrintWriter(out)); %>
</pre>
</BODY>
</HTML>
45
Accessing ReadingDatabase when
there is a table "a"
Accessing ReadingDatabase when there is no table "a"
46
The include DirectiveThe include Directive
• This directive lets you include files at the
time the JSP page is translated into a servlet
• The directive looks like this:
<%@ include file="relative url" %>
• JSP content can affect main page
• servers don't notice changes in included files
47
<HTML>
<HEAD> <TITLE>Reading From Database</TITLE></HEAD>
<BODY>
Here is an interesting page.<br><br>
Bla, Bla, Bla, Bla.
<%@ include file="AccessCount.jsp" %>
</BODY>
</HTML>
BlaBla.jsp
<hr>
Page Created for Dbi Course. Email us
<a href="mailto:[email protected]">here</a>.
<br>
<%! private int accessCount = 0; %>
Accesses to page since server reboot:
<%= accessCount++ %>
AccessCount.jsp
48
49
Writing JSP in XMLWriting JSP in XML
• We can replace the JSP tags with XML
tags that represent
– Expressions
– Scriptlets
– Declarations
– Directives
50
<%= Java Expression %><jsp:expression>
Java Expression </jsp:expression>
<% Code %>
<jsp:scriptlet> Code Java
</jsp:scriptlet>
<%! declaration %><jsp:declaration>
Java Declaration </jsp:declaration>
<%@ directive %> <jsp:directive.typeAttribute = value/>
51
ActionsActions
• JSP actions use constructs in XML syntax to
control the behavior of the servlet engine
• You can
– dynamically insert a file,
– reuse JavaBeans components,
– forward the user to another page, or
– generate HTML for the Java plugin
52
Available ActionsAvailable Actions
• jsp:include - Include a file at the time the page is requested
• jsp:useBean, jsp:setProperty, jsp:getProperty – manipulate a JavaBean (not discussed today)
• jsp:forward - Forward the requester to a new page
• jsp:plugin - Generate browser-specific code that makes an OBJECT or EMBED tag for the Java plugin (not discussed today)
53
The jsp:include ActionThe jsp:include Action
• This action lets you insert files into the
page being generated
• The file inserted when page is
requested
• The syntax looks like this: <jsp:include page="relative URL" flush="true" />
54
The jsp:forward Action The jsp:forward Action
• Forwards request to another page
<jsp:forward page="relative URL"/>
• Page could be a static value, or could be
computed at request time
• Examples:
<jsp:forward page="/utils/errorReporter.jsp" />
<jsp:forward page="<%= someJavaExpression
%>" />
55
CommentsComments
• <%-- comment --%>– A JSP comment, ignored by JSP-to-scriptlet
translator
• <!-- comment -->– An HTML comment, Passed through to resultant
HTML
– Any embedded JSP scripting elements, directives, or actions are executed normally
• /* comment */ or // comment– Java comment, Part of the Java code
56
Quoting ConventionsQuoting Conventions
• <\% - used in template text (static
HTML) and in attributes where you
really want <%
• %\> - used in scripting elements and in
attributes where you really want %>
• \‘ \” - for using quotes in attributes
• \\ for having \ in an attribute
57
Init and DestroyInit and Destroy
• In JSP pages, like regular servlets, sometimes want to use init and destroy
• It is illegal to use JSP declarations to override init or destroy, since they are already implemented (usually) by Servlet created
• Instead use jspInit and jspDestroy– The auto-generated servlet is guaranteed to call
these methods from init and destroy
– The standard versions of jspInit and jspDestroy are empty (placeholders for you to override)
58
Material Not CoveredMaterial Not Covered
• Java beans: Using Java beans you can simplify the process of sharing information between JSP pages and Servlets. (How can you share information now?)
• Custom Tags: You may define new tags and Java classes that define what should be done when the tag appears in a JSP page
59
JSP versus JavaScriptJSP versus JavaScript
• Q: Can/Should you have JSP and
Javascript in the same page?
• Q: Can you validate a form using
JavaScript? Where should the code go?
• Q: Can you validate a form using JSP?
Where should the code go?