Transcript ppt

JSP – Java Server Pages
Representation and Management
of Data on the Internet
1
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...")
2
JSP 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
3
Relationships
• In servlets: HTML code is printed from
java code
• In JSP pages: Java code is embedded in
HTML code
Java
HTML
HTML
Java
4
Example
<HTML>
<HEAD>
<TITLE>Hello World Example</TITLE>
</HEAD>
<BODY>
<H2>Hello World Example</H2>
<B>Hello <% =request.getParameter("name") %>!</B>
</BODY>
</HTML>
5
Page is in the proj web application:
tomcat_home/webapps/proj/HelloWorld.jsp
Invoked with URL:
http://<host>:<port>/proj/HelloWorld.jsp?name=snoopy
6
Invoked with URL (no parameter):
http://<host>:<port>/proj/HelloWorld.jsp
7
JSP Limitations and
Advantages
• 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
8
What does a JSP-Enabled
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
9
Translation of JSP to Servlet
• 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!
10
Design 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
11
The Source Code
• In Tomcat 3.2.1, you can find the generated
Java and the class files in a subdirectory under
tomcat_home/work.
12
JSP 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
13
JSP Expressions
• A JSP expression is used to insert Java
values directly into the output
• It has the following form:
<%= Java Expression %>
• Example:
– <%= Math.random() %>
14
JSP 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
15
Expression 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());
...
}
16
Predefined 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
17
<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>
18
Encoded
Unencoded
19
JSP 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?
20
Scriptlet Translation
<%= 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();
...
}
21
Producing 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?
22
HTML 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!");
}
23
JSP 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?
24
Declaration 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?
25
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());
...
} ...
}
26
Predefined 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
27
More Details: request, response
• 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
28
More 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
29
More 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
30
Another Variable: application
• 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
31
Another Variable: config
• This is the ServletConfig of the page, as
received in init method
• Remember: Contains Servlet specific
initialization parameters
32
Another Variable: pageContext
• pageContext encapsulates use of serverspecific 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
33
Another 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
34
Note about Predefined
Variables
• 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
35
JSP 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" %>
36
Three 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
37
page 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"); %>
38
More page Directive Attributes
• 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” Default is Server Dependant
– specifies the buffer size for the JspWriter out
39
More page Directive Attributes
• 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
40
More page Directive Attributes
• 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
41
<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();
%>
42
<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?
43
<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>
44
Accessing ReadingDatabase when there is no table "a"
Accessing ReadingDatabase
when there is a table "a"
45
The 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
46
<HTML>
<HEAD> <TITLE>Reading From Database</TITLE></HEAD>
<BODY>
Here is an interesting page.<br><br>
BlaBla.jsp
Bla, Bla, Bla, Bla.
<%@ include file="AccessCount.jsp" %>
</BODY>
</HTML>
<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
47
48
Writing JSP in XML
• We can replace the JSP tags with XML
tags that represent
– Expressions
– Scriptlets
– Declarations
– Directives
49
<%= 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.type
Attribute = value/>
50
Actions
• 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
51
Available 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)
52
The 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" />
53
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 %>" />
54
Comments
• <%-- 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
55
Quoting 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
56
Init 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)
57
Material 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
58
JSP 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?
59