Introduction to Java Server Pages (JSPs) Robert Thornton Notes • • • • This is a training NOT a presentation Please ask questions https://tech.lds.org/wiki/Java_Stack_Training Prerequisites – Basic Java and HTML skills. – Installed LDSTech IDE (or other equivalent). – Installed App Server (such as Tomcat). Overview • Java Server Pages • What are they? • What is their role? • JSP Programming Fundamentals: • • • • Directives Declarations Expressions, Scriptlets, and implicit objects. Error handling • Maven JSP Compiler • What does a compiled JSP look like? What is a JSP really? • A text document containing: – Static data (usually HTML) – JSP elements that construct dynamic content – Typically ends with a .jsp extension • Translated into a Java class – Extends HttpServlet – May be compiled as part of a build or compiled at runtime in response to a detected change. What is the role of a JSP? • Provides the view of MVC. • Allows generation of static HTML using familiar web tools and syntax. • Allows generation of dynamic HTML using familiar Java syntax and language features. • Allows rapid prototyping of web pages. JSPs versus Java Servlets • Java Servlets: – Strictly written in Java – HTML must be embedded and escaped within Java strings literals. – Must be defined and mapped within web.xml • Java Server Pages (JSPs) – Mostly static HTML with JSP elements. – No servlet definitions or mappings necessary. JSP Example 1 <%-- JSP Training: Example 1 --%> <%@ page contentType="text/html" pageEncoding="UTF-8" %> <%@ page import="java.util.logging.Logger,java.util.Date" %> <%-- define a logger for the current page --%> <%! private static final Logger logger = Logger.getLogger("/example1.jsp"); %> <!DOCTYPE html> <html> <head> <title>JSP Training: Example 1</title> </head> <body> <h1>Hello World!</h1> <%-- write something dynamic --%> <p>The current date is <% out.write(new Date().toString()); %></p> </body> </html> <%-- log something --%> <% logger.info("Finished rendering " + request.getRequestURL()); %> Lab 1: JSP Servlet Compilation Lab 1 https://tech.lds.org/wiki/Introduction_to_JSP#Lab _1:_JSP_Servlet_Compilation JSP Elements: Directives • Directives allow control over how the JSP is translated into a servlet. • Three types of directives: – Page: defines attributes that affect the structure and definition of the generated servlet. – Include: statically includes the contents of other files in the JSP (covered in a later training). – Taglib: imports a JSP tag library for use by the page (also covered in a later training). JSP Elements: Page Directive • Example syntax: <%@ page contentType="text/html" pageEncoding="UTF-8" errorPage="error.jsp" import="java.util.*" %> • A page directive may appear anywhere in the JSP. • A page directive may appear multiple times. JSP Elements: Page Directive Attributes • contentType – The value passed to ServletResponse.setContentType • pageEncoding – The value passed to ServletResponse.setCharacterEncoding • import – Import statements to include in the generated servlet • errorPage – Relative path to an error page if an exception is thrown • isErrorPage – Whether this page is to handle exceptions from other pages JSP Elements: Page Directive Examples <%@ page contentType="text/html" pageEncoding="UTF-8" %> <%@ page errorPage="internalError.jsp" %> <%@ page import="java.util.Date" import="java.text.SimpleDateFormat" import="java.io.*,java.net.*" import="static org.lds.stack.Constants.*" %> JSP Elements: Comments • Syntax: <%-- one or more lines --%> • Can be used to comment out both JSP and HTML elements. • JSP comments will be ignored by the JSP parser and will not included in the generated servlet. JSP Elements: Declarations • Syntax: <%! Java declarations %> • May contain one or more Java declarations to be inserted into the class body of the generated servlet. • May be used multiple times to declare both member variables and helper functions on the generated servlet. JSP Elements: Example Declarations <%! private final int FOO = 1024; private String[] options = { "green", "red", "blue", "yellow" }; %> <%! private String doSomething(HttpServletRequest req) { // do something } %> JSP Elements: Scriptlets • Syntax: <% java code %> • Consists of one or more Java statements to be inserted into the generated servlet’s _jspService method (called by service). • Each scriptlet will be inserted after streaming any preceding static content and before streaming any subsequent static content. JSP Elements: Example Scriptlets <% String[] options = { "green", "red", "blue", "yellow" }; %> <select name="options"> <% for (int i = 0; i < options.length; i++) { %> <option><% out.write(options[i]); %><option> <% } %> </select> Lab 2: Hello World in JSP Lab 2 https://tech.lds.org/wiki/Introduction_to_JSP#Lab _2:_Hello_World_in_JSP JSP Elements: Expressions • Syntax: <%= java expression %> • Consists of Java code to be evaluated and written to the response output stream during the evaluation of the _jspService method. • Expression return type must not be void. • Each expression’s output will be inserted into the output stream after any preceding static content and before any subsequent static content. JSP Elements: Example Scriptlets <% String[] options = { "green", "red", "blue", "yellow" }; %> <select name="options"> <% for (int i = 0; i < options.length; i++) { %> <option value="<%= i %>"><%= options[i] %><option> <% } %> </select> JSP Elements: Implicit Objects • Implicit objects are variables available to both expressions and scriptlets. • They are not available within declarations. • They are, in fact, local variables of the _jspService method. JSP Elements: Implicit Objects • • • • • • • • request – javax.servlet.http.HttpServletRequest response – javax.servlet.http.HttpServletResponse session – javax.servlet.http.HttpSession application – javax.servlet.ServletContext config – javax.servlet.ServletConfig out – javax.servlet.jsp.JspWriter pageContext – javax.servlet.jsp.PageContext exception – java.lang.Throwable Lab 3: A JSP Calendar Lab 3 https://tech.lds.org/wiki/Introduction_to_JSP#Lab _3:_A_JSP_Calendar Using Maven to Compile JSPs Maven can be used to validate and pre-compile JSPs before deploying them to a server. • This protects against inadvertently sending broken pages to the server. • This can also be used to analyze bugs how changes in the JSP affect the compiled servlet • JSP Servlets generated by the maven build will not necessarily match JSP servlets generated by the application server. Lab 4: Pre-compiling JSPs with Maven Lab 4 https://tech.lds.org/wiki/Introduction_to_JSP#Lab _4:_Pre-compiling_JSPs_with_Maven Credit where credit is due • http://download.oracle.com/javaee/5/tutorial/doc/bnagx.html • http://java.sun.com/products/jsp/tags/11/syntaxref11.fm7.html • Core Servlets and JavaServer Pages, Marty Hall and Larry Brown, Sun Microsystems & Prentice Hall, 2000 – ISBN-13: 978-0130092298