SE 452 Fall 2001/2002
Lecture Notes Set 7
Java Server Pages
- What is Java Server Pages (JSP)?
- HTML or XML documents with embedded Java code to generate dynamic content
- text based document that describes how to process a request and generate a
response
- mix of template data in HTML/XML with some dynamic actions in Java
- How is it related to a servlet?
- servlet:HTML/XML in Java code
- JSP: Java code in HTML/XML (inverted servlet)
- JSP's are complied (by JSP compiler) to servlets:
- first time JSP is invoked
- precompiled (done by user)
- JSP's are processed on the server side
- required a JSP container, usually part of servlet container
- clients receive the result of the processing, not source
- results of servlet is produced by calling _jspService() method
- JSP current version is 1.1 (supported in Tomcat 3.2)
- JSP 1.2 spec in available for public review
Advantages of JSP
- Powerful - use full power of Java language and libraries
- Efficient - compiled to bytecode before execution, not interpreted
- Portable - JSP's are platform independent and a J2EE standard
- Convenient - using Java Beans component architecture
- Flexible, extensible and elegent - tag extension with custion tag libraries
Application Models
- A web app often consists of both servlets and JSP's
- JSP - presentation heavy
- Servlet - mixed presentation and logic
- Java beans - pure business logic
- JSP can interact with:
- JDBC
- server side Java beans
- Enterprise Java Beans (EJB)
- XML, XSLT, etc
Hello in JSP
-
Example
- Source
- This JSP file can reside anywhere (except WEB_INF/classes) under the doc root of the
web app context
- Invoking JSP is just like invoking HTML
(http://flyweight.cti.depaul.edu:9080/se452servlets/jsp/hello.jsp)
- What's the difference??
- Don't have to write out HTML tags from Java code
- Easier to get idea of what page will look like to client
Deploying JSP Pages
- Just like depolying HTML pages
- You can place JSP pages anywhere under DOC_ROOT of the application
- DO NOT copy to WEB-INF/classes!!
- Invoke JSP just like HTML.
- Use URI that is relative to the DOC_ROOT of the context.
The JSP container
- Manages JSP page life cycle
- Interact with the JSP pages through the javax.servlet.jsp.HttpJspPage,
which extends javax.servlet.jsp.JspPage, which extends javax.servlet.Servlet
- Methods
- void jspInit()
- void jspDestroy()
- void _jspServlce(HttpServletRequest request, HttpServletResponse response)
- JSP pages may define the jspInit() and jspDestroy() methods in declarations:
<%!
public void jspInit() { ... }
public void jspDestroy { ... }
%>
...
- JSP pages have the same lifecycle as servlets
- You should never define the _jspServlet() method.
- You should never define any of the servlet methods.
The Generated Servlet
- Servlet Skeleton:
import package.name;
class _jspXXX extends SuperClass{
public void _jspService(...){
}
}
What goes where??
- A declaration - verbatim copy into the <Declaraion Section>
- Template data (HTML) - statement fragment in the <Main Section>
(ie out.print(template)
- A scriptlet - verpatim copy into the <Main Section>
- An expression - statement in the <Main Section>
(ie out.print(expression)
- An action - statement fragment in the <Main Section> which
creates objects and invokes the action handler.
Elements of JSP Pages
- Comments
- HTML comments - passed to the client
- JSP comments (<%-- --%>) - not passed to the client
- Declarations
- Used to declare methods and variables in Java
- These become class level variables and methods (outside _jspService)
- Format:
<%! private int count = l; %>
or
private int count = 1;
- You can have multiple declarations in a declaration tag
- the second is used in XML documents
- Expression
- Contains a Java expression
- Format:
<%= new java.util.Date() %>
or
new java.util.Date()
- You can only have one expression per tag
- Scriptlet
- Contains Java code snippet
- Format:
<%
String s = request.getQueryString();
out.println(s);
%>
or
String s = request.getQueryString();
out.println(s);
- You can can have many lines of code per tag
JSP Page Examples
- Request info
- Request headers
- Request parameters
- Notice that Java control structures can be used to control what
parts of the HTML template are shown.
Handle Login in JSP
- Using code in JSP page
- Problem with above example.
- Business logic and presentation both handled by JSP page
- Not easy for a non-Java programmer to write this page
- Solution: Using another class to handle login processing
CLASSPATH for JSP Pages
- Extra classes used by JSP pages must be included in servlet engine classpath
- Classpath must be set before servlet engine starts up
- tomcat.bat/tomcat.sh is used to set classpath
- You can also drop the classes in the WEB-INF/classes directory for the web app
Object Scope in JSP
- Object can be manipulated in JSP.
- Objects have different scopes:
- page: object only visible in this page
- request: pages processed in the same request
- session: pages processed in the same session
- application: all pages in an application
- Scope is controled by the page that created the object
Implicit Objects
- JSP provides access to some objects that don't need to be declared
- request
- type: HttpServletRequest or subclass of ServletRequest
- scope: request
- When using HTTP, identical to the request object that
gets passed around in doPost(), doGet(), etc
- Not many, if any, JSP servers support non-HTTP servlets.
- response
- type: HttpServletResponse or subclass of ServletResponse
- scope: page
- Not typically used in JSP pages
- pageContext
- type: javax.servlet.jsp.PageContext
- scope: page
- Used to get info about the current page
- session
- type: HttpSession
- scope: session
- Identical to the HttpSession object in servlets.
- Used to store session level information
- application
- type: ServletContext
- scope: application
- Identical to the ServletContext object that we use in servlets
- You can store some application level data into this object
- out
- type: javax.servlet.jsp.JspWriter (subclass or PrintWriter)
- scope: page
- Used to write information out to the client.
- Different from PrintWriter in that it handles buffering of
information
- Not often used.
- config
- type: ServletConfig
- scope: page
- The ServletConfig object for this page
- page
- type: Object
- scope: page
- the "this" pointer for the current JSP page
- Not typically used.
- exception
- type: Throwable
- scope: page
- Available only to error pages
- Identical to exceptions in Java but now a JSP page
handles the exception
JSP Directives
- Messages or instructions to the JSP container as to what the
resulting servlet should look like.
- Do not produce any output
- Syntax:
<%@ directive attr1=value1 attr2=value2 ... %>
- JSP 1.1 standard directives:
- page
- Format:
<%@ page [language="java"]
[extends="package.class"]
[import="{package.class | package.*}, ..."]
[session="true | false"]
[buffer="none | 8kb | 'size'kb"]
[autoFlush="true | false"]
[isThreadSafe="true | false"]
[info="text"]
[errorPage="relativeURL"]
[contentType="{mimeType}"]
[isErrorPage="true | false"] %>
- import
- comma separated import list of either fully qualified
class name or package name.*
- Default import list is java.lang.*, javax.servlet.*,
javax.servlet.jsp.*, javax.servlet.http.*
- session
- tells JSP compiler if this JSP page participates in the session
- session object only available if attribute is true
- default is true
- isThreadSafe
- false - single threaded model
- true - multiple threads allowed. Developer must handle
synchronization issues.
- default is true
- buffer
- specifies buffering model for the out object
- none - no buffering
- default - buffer no smaller than 8kb
- autoFlush
- true - buffer is flushed automatically
- false - exception raised when buffer fills
- errorPage
- URL to JSP for error processing
- error page is invoked when Throwable object is thrown but
not caught
- isErrorPage
- indicates that the current JSP page is an error page
- default is false
- exception object is only available if this attribute is true
- info
- defines an arbitrary string that can be retrieved by the
Servlet.getServletInfo() method
- include
- taglib
JSP Actions
- Actions are special tags that may affect the current out stream and use, modify
and/or create objects
- Standard actions:
- <jsp:forward>
- <jsp:include>
- <jsp:param>
- <jsp:plugin>
- <jsp:useBean>
- <jsp:getProperty>
- <jsp:setProperty>
- Custom actions - use custom tag extensions and taglib directive
Including Files in JSP pages
- Include directive
- Include a staic page or JSP page
- Processed at translation time
- Syntax:
<%@ include file="relativeURL" %>
- The page contents are inserted directly into the
generated servlet. Not translation is done.
- If included file is changed then the JSP page must be
recompiled.
- Include action
- Includes a static HTML page or
- Sends a request to a JSP page or servlet and includes the
result page, which must be static
- Processed at request time
- Included page has access to the out(JspWriter) object and the
request object but can't set headers
- Syntax:
or
[] +
- Second one is used to pass infomation to the included page
- The parameters are added to the ones present in the
original request object (ie if A=foo is in the original request and
I add A=bar, the forwarded request will contain A=bar,foo)
Forward Action
- Forwards the client request to a static page, JSP page or
servlet for processing.
- Terminates the execution of the current page
- If the page output (out object) is buffered, then
the buffer is cleared prior to forwarding.
- If the page output is unbuffered and anything has been written to it,
an attempt to forward the request will result in an Exception.
- Syntax:
or
[] +
- The parameters are added to the ones present in the
original request object (ie if A=foo is in the original request and
I add A=bar, the forwarded request will contain A=bar,foo)