210 likes | 220 Views
This lecture discusses JavaServer Pages (JSP) and their advantages over other scripting languages for building web applications. It covers the structure of JSP pages, implicit variables, output handling, scope layers, expressions, statements, declarations, and directives. Detailed examples and guidelines are provided for effective JSP implementation.
E N D
Lecture 9 JavaServer Pages (JSP) (Based on Møller and Schwartzbach, 2006, Chapter 9) CIS336Website design, implementation and management(also Semester 2 of CIS219, CIS221 and IT226) David Meredith d.meredith@gold.ac.uk www.titanmusic.com/teaching/cis336-2006-7.html
Scripting languages • Scripting languages, like ASP and PHP, view Web applications as collections of active pages • An active page is an HTML document with embedded fragments of script code that are executed on the server • Scripting languages are OK for simple applications • but weaknesses become apparent when try to use scripting languages to build large, complex Web applications • e.g., lack of static type checking (i.e., checking the types of parameters and variables at compile time)
The JSP framework • Pages written using the JavaServer Pages (JSP) scripting language are translated into servlets and then compiled using a Java compiler • implies full power of Java language (including, e.g., static type checking) is preserved • This is an advantage of JSP over, e.g., ASP or PHP
A simple JSP example • JSP page above maintains a hit counter and prints the current server time • When using a Tomcat server, needs to be saved in a directory underneath webapps, e.g., $CATALINA_HOME/webapps/myjsps/hello.jsp • JSP pages compiled into servlets automatically • JSP page is an HTML page with embedded Java code • variable out declared implicitly to hold current output stream • JSP should be as simple as HTML but, without tag libraries or expression language, need a good knowledge of Java
Templates • JSP page written as a template • Template is a text file (usually an HTML file) containing snippets of Java code and JSP-specific directives • Java code in a JSP page appears as • expressions:<%= expression %> • e.g., <%= new java.util.Date().toLocaleString() %> • statements:<% statement %> • e.g., <% synchronized(this) {out.println(++hits); } %> • declarations:<%! declaration %> • e.g., <%! int hits = 0; %>
Implicitly declared variables • JSP page translated into a servlet and following variables are implicitly declared: HttpServletRequest request; HttpServletResponse response; HttpSession session; ServletContext application; ServletConfig config; • Output stream declared as JspWriter out; • Unlike PrintWriter • JspWriter throws a java.io.IOException if print method fails • JspWriter may buffer output before printing • Constant parts of a JSP page are also printed to out • PageContext pageContext; • adds extra layer of scope and corresponding setAttribute and getAttribute methods • Four successively broader layers of scope for setting and getting attributes: • page scope: pageContext • request scope: request • session scope: session • application scope: application • pageContext.findAttribute() • searches for named attribute in successively broader scopes
Expressions • Java expressions are embedded in JSP pages using syntax: <%= expression %>
Statements • Java statements are embedded in JSP pages using syntax: <% statement %> • Statement must have side-effects to be noticeable, e.g., • change state of variables • print to output stream
Declarations • Java declarations are embedded in a JSP file using the syntax <%! declaration %> • Can be used to define class fields and methods
Declaring variables in declarations and statements • If line 6 were a statement, then variable hits would be set to zero every time the page was loaded • statement would correspond to a line in a method in the servlet generated from the page • Using a declaration means that hits is declared as a field in the servlet generated by the page • therefore only set to zero once, when the servlet class is instantiated
Directives • JSP directives have the syntax <%@ directive %> • Directives provide parameters to the JSP processor, e.g., <%@ include file="header.jsp" %> • includes the file header.jsp at the position where the directive occurs • Note how we declare title to be a field so that we can refer to it in an expression in header.jsp
The page directive • page directive can be used with various attributes to set different properties of the JSP page • buffer="size" • sets size of output stream buffer in bytes • autoFlush = "true-of-false" • determines whether output buffer is automatically flushed • contentType = "mime-type" • sets mime type for output stream • default is "text/html" • pageEncoding = "encoding" • sets character set for output • default is ISO-8859-1 • info="string" • sets descriptive string returned by invoking getServletInfo() on generated servlet • errorPage="path" • sets JSP page that should be invoked if uncaught exception thrown • isErrorPage="true-or-false" • determines whether current page is an error page • if it is, then there is a variable, exception, available that contains the thrown exception • import="package" • specifies package to be imported in generated servlet class
Translation into servlets • Tomcat generates servlet that specializes HttpJspBase (a subclass of Servlet) • Expressions wrapped in out.print(...) • HTML markup wrapped in out.write(...) • Declarations translated into fields and methods
Translation into servlets • Translation is lexical • means that HTML markup and Java code are not parsed • means Java code statements don't have to be individually syntactically well-formed - only result that has to be well-formed
XML version of JSP • JSP processor performs lexical translation of JSP pages into servlets • means no syntactic requirements are enforced • JSP can also be written using an XML syntax • called JSP documents (not pages) • means JSP documents can be validated • can be manipulated using XML tools
JSP Expression Language • ${expression} occurring anywhere within JSP template text or attribute values of markup is replaced with string resulting from evaluating expression • Expression language resembles JavaScript • Supports • strings, booleans, various numerical types • arithmetic, logical and comparison operators • References to named variables resolved using findAttribute mechanism • Supports operations on certain objects, e.g., ${gadget.weight} is translated intopageContext.findAttribute("gadget").getWeight() • Some implicit objects defined, e.g., • param is a map of the request parameters • pageContext references the object pageContext
Tags • JSP is intended to be used by people who are not expert Java programmers • However, hard to use JSP without knowledge of Java • Tags designed to allow markup to be separated cleanly from Java code • Standard Tag Library can be used by non-programmers to access JSP through mark-up
Tag files • A tag file is a definition of a new tag (i.e., element) which can contain arbitrary Java code to be executed • Means the active content can be obtained by designer simply by using appropriate tags in the markup • Tag file is a JSP page with the file extension .tag and the directive <%@ tag %> • Note use of attribute directive to declare an attribute for the new tag • jsp:doBody instruction indicates where contents of tag is inserted • taglib directive indicates where tags are located (cf. XML namespaces)
Using jsp:doBody with the var attribute • Declare a variable in the var attribute of the jsp:doBody instruction • Content of new tag is stored in the declared variable • Each reference to declared variable in tag file then replaced with content of new tag when used