Java Server Pages
Java Server Pages
by Jon Pearce
JSP Documents
JSP docs are XHTML Documents
containing:
Fixed-Template Data: FTD
HTML Components
XML markup
JSP Components: <JSP>
demo.jsp
<?xml version = 1.0?>
<!DOCTYPE html PUBLIC ".../xhtml1-strict.dtd">
<html xmlns = "http://www.w3.org/1999/xhtml">
<head> <title> Demo </title> </head>
<body>
FTD <JSP> FTD <JSP> FTD <JSP>...
</body>
</html>
JSP Components <JSP>
Scriptlets
<%, <%--, <%=, <%! ... %>
Directives
<%@ directive %>
Actions
<jsp: action> ... </jsp:action>
<myNS:action> ... </myNS:action>
JSP Facts
The container compiles a JSP to a servlet the
first time it is served.
Use JSPs when ratio of FTD to Dynamic
Content is high
JSPs decouple design from programming
JSP = HTML containing Java
Servlet = Java containing HTML
JSPs replace views
JSP Compilation
client container
form.jsp
request
HTML
Scriptlets
<<Interface>>
JSPPage
jspDestroy()
jspInit() contains implicit
objects + actions
PageContext
<<Interface>>
HttpJspPage getAttribute()
setAttribute()
_jspService() 1 1
include()
container
generated from MyJSP
JSP
The JSP to Servlet Translation
public class MyJSP implements HttpJspPage {
// ...
public void _jspService(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
JspFactory factory = JspFactory.getDefaultFactory();
PageContext pageContext = factory.getPageContext(...);
HttpSession session = pageContext.getSession();
JspWriter out = pageContext.getOut();
Object page = this;
try {
// body of translated JSP goes here ...
} catch (Exception e) {
out.clear();
pageContext.handlePageException(e);
} finally {
out.close();
factory.releasePageContext(pageContext);
}
}
}
Examples
clock.jsp
<%= new java.util.Date() %>
scriptTest.jsp
Pallindrome Tester
beanTest.jsp
various counters
personView.jsp
Standard Actions
<jsp:action> ... </jsp:action>
include
forward
plugin
param
useBean
setProperty
getProperty
Directives
<%@ include ... %>
<%@ taglib ... %>
<%@ page ... %>
<%@ page errorPage = "foo.jsp" %>
<%@ page session = "true" %>
<%@ page language = "java" %>
<%@ page extends = "java.awt.Frame" %>
<%@ page import = "java.util.*" %>
Include Directive
<%@ include file = "banner.html" %>
Include Directive vs. Action
<jsp:include page = "foo.jsp" flush = "true" />
foo.html included after each change
<%@ include file = "foo.jsp" %>
foo.html included once at compile time
Static (html) or dynamic (jsp) files can be included
forward
<jsp:forward page = "foo.jsp">
<jsp:param
name = "date"
value = "<%= new Date() %>"
/>
</jsp:forward>
useBean
<jsp:useBean id="cart" scope="session" class = "CartBean" />
Accessing Bean Properties
<%= cart.getTotal() %>
<jsp:getProperty name = "cart" property = "total" />
Setting Bean Properties
<% cart.setTotal(200); %>
<jsp:setProperty name = "cart" property = "total" value = "200" />
Example