JavaServer Pages SWE 642, Fall 2008 Nick Duan What is JavaServer Pages? JSP is a server-side scripting language in Java for constructing dynamic web pages based on Java Servlet, specifically it contains three types vocabularies A set of special tags for interfacing with the Java language An expression language (EL) for accessing server-side JavaBeans and built-in objects An tag extension mechanism to the define customized tags An XML document containing a combination of HTML/JavaScripts, CSS, and JSP elements Any difference between JSP and JavaScripts? 10/28/2008 Nick Duan 2 1
Directive Sample JSP Action <%@ page info= Samle JSP for SWE642 %> <jsp:usebean id= mybean" class= edu.gmu.beanclass"/> <jsp:setproperty name= mybean" property= "*"/> <html> <body> <%@ import file= header.html %> Directive Scriptlet <% if (request.getparameter("name")==null ) { %> <h1>user Info Request Form</h1> <form method= get" action="/process.jsp"> <br> Name: <input type="text" name= "name > <p> <input type="submit" value= Submit"> </form> <% } else { %> <p> <b>user Name provided</b>: <p> Name: <jsp:getproperty name= mybean" property="name"/> <% } %> </body></html> Action August 21, 2008 Nick Duan 3 JSP Lifecycle Hello.jsp 1. Request 6. Response JSP Container J2EE Server 3. Generate 4. Compile Hello_jsp.java Follow the servlet lifecycle here Hello_jsp.class If JSP is already compiled, compilation is skipped 10/28/2008 Nick Duan 4 2
Types of JSP Elements JSP Element Type Syntax Comment <%-- my comments --%> Declaration <%! int count=0; %> Directives <%@ include file= myjsp.jsp %> <%@ page {attribute= value }* %> <%@ taglib uri= http://me.com prefix= me %> Expression <%= variable %> Scriptlet <% String mystring= mystring ; %> Actions <jsp:usebean {attribute= value }* /> August 21, 2008 Nick Duan 5 Page Directives Defines one of more page-dependent properties Commonly used attributes of @ page import = a java class to this page extends = a base class for this page errorpage = error page url contenttype = MINE type of this page pageencoding = character encoding of this page August 21, 2008 Nick Duan 6 3
Standard Actions in JSP XML elements with the prefix jsp, predefined by the JSP engine Standard Actions <jsp:usebean /> Actions for Dealing with Java Beans <jsp: setproperty /> <jsp: getproperty /> <jsp: param /> <jsp: include /> <jsp: forward /> <jsp: plugin /> <jsp:params /> <jsp:element /> <jsp:attribute /> <jsp:text /> 10/28/2008 Nick Duan 7 What is a JavaBean? A Java class with standard naming conventions for data members (properties) and public access methods (getters/setters) Declared as a public class with default constructor First introduced in JDK 1.0 with different types of properties (simple, indexed, change, vetoable) and introspection APIs Java Beans with simple properties are most commonly used Sometimes it may refer to any Java class 10/28/2008 Nick Duan 8 4
Sample Java Bean Definition public class User { } private String name; private String phonenumber; public String getname() { return name; } public void setname(string val) { name=val; } public String getphonenumber () { return phonenum; } public void setphonenumber(string val) { phonenumber=val; } August 21, 2008 Nick Duan 9 The usebean Action Create a Java Bean object within the page or reference an existing one in request or session object Syntax <jsp:usebean id= bname scope= page request session application class= edu.gmu.swe642.user /> id Variable name of the Java Bean object to be used throughout the page An usebean action to be defined first before any setproperty and getproperty action in a JSP 10/28/2008 Nick Duan 10 5
The setproperty Action setproperty sets a value of a data member in a Java Bean object Performs the corresponding setter function of the bean <jsp:setproperty name= bname" property= name" value= Charlie Brown"/> <jsp:setproperty name= bname" property="*" /> Set the bean properties with values of request parameters with identical names 10/28/2008 Nick Duan 11 The getproperty Action getproperty performs the corresponding getter method of the bean and output the result to the jspwriter <jsp:getproperty name= bname" property= phonenumber"/> Equivalent to the jsp expression: <%=bname.getphonenumber()%> bname must have been defined as an id in a previous usebean action August 21, 2008 Nick Duan 12 6
The forward & include Action Similar to the forward and include method of the servlet dispatcher (What s the difference between forward and include?) Syntax <jsp:include page= yours.jsp" flush= true false /> <jsp:forward page= yours.jsp /> <jsp:include page= yours.jsp" flush= true false > {<jsp:param name= name value= val />}* </jsp:include> <jsp:forward page= yours.jsp > {<jsp:param name= name value= val />}* </jsp:forward> 10/28/2008 Nick Duan 13 Implicit Objects in JSP Predefined variables for standard Servlet/JSP objects request HttpServletRequest response HttpServletResponse session HttpSession application ServletContext config ServletConfig out JspWriter Example Current session ID: <%=session.getid()%> August 21, 2008 Nick Duan 14 7
Unified Expression Language A generic scripting technology not limited to JSP (also used in JSF) Functionalities built into the JSP engine Direct access to JavaBeans/various data structures (array, enum and collections), and implicit objects via various resolvers Allow direct data mapping to/from JavaBeans (or bean-like) data objects Invoke static/public methods Built-in string and arithmetic operations August 21, 2008 Nick Duan 15 EL Examples ${expr} immediate evaluation #{expr} deferred evaluation (used mostly in JSF technology) ${employee.name} JavaBeans, Java enum, Map ${array[0]} array ${employee[ name ]} JavaBeans, Java enum, Map ${employee.age + 20} Arithmetic expr. ${planet == earth } Logical expr. August 21, 2008 Nick Duan 16 8
EL Resolvers A set of standard Java classes extending ELResolver for resolving JSP objects and accessing their properties Types of resolver classes include ArrayELResolver BeanELResolver ListELResolver MapELResolver ResourceBundleResolver ImplicitObjectResolver August 21, 2008 Nick Duan 17 Custom Tags in JSP A customer tag is a JSP element designed to perform JSP functions (e.g EL eval) and/or HTML rendering of a page segment Format in JSP <pref:tagname attri_name= value../> (with or without body) Able to access all objects available to JSP and communicate with each other Reusable and flexible, more popular than JSP fragment. Can be bundled into a tag library Can be implemented either using a combination of EL and existing tags/scripts, or via creation of tag classes using tag APIs August 21, 2008 Nick Duan 18 9
Configure Custom Tags Create tag files with extension.tag and package under WEB-INF/tags/dir, or provide tag classes under WEB-INF/classes Reference tag library in JSP <%@ taglib prefix= pref tagdir= WEB- INF/tags/subdir %> <%@ taglib prefix= pref" uri= uri" %> url references the location of the tld file In case of API implementation, define tag library descriptor file(s) with the extension.tld under WEB-INF or a subdirectory Implicit tld file is generated in case of tag files August 21, 2008 Nick Duan 19 JSP Standard Tag Library What is JSTL? A collection of commonly used custom tags for JSP A JCP standard, Latest version: 1.2 Defined in multiple categories according to tag functionality Category Uri Prefix Core http://java.sun.com/jstl/core c XML Processing http://java.sun.com/jstl/xml xml I18N formatting http://java.sun.com/jstl/fmt fmt Database http://java.sun.com/jstl/sql sql Functions http://java.sun.com/jstl/functions fn August 21, 2008 Nick Duan 20 10
Example of JSTL <%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql" %> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <sql:query var="rs" datasource="jdbc/proj642db"> select * from employee </sql:query> <table border=1 bgcolor="lightblue" width="300"> <tr><td>name</td> <td>address</td> <td>age</td> </tr> <c:foreach var="row" items="${rs.rows}"> <tr><td>${row.name}</td> <td>${row.address}</td> <td>${row.age}</td> </tr> </c:foreach> </table> August 21, 2008 Nick Duan 21 Summary JSP is a combination of various techniques for creating presentation-tier of web applications. If used properly, JSP can be a efficient tool in developing web applications The best practice in JSP nowadays is to use JavaBeans and Bean-like components, and custom tags to define page logic and HTML rendering, instead of using embedded Java code Design a JSP into reusable fragments implemented using tags August 21, 2008 Nick Duan 22 11
Quiz How to create aperform request dispatching in JSP (servlet-chaining in JSP)? Should you ever use request dispatching in JSP? What would be the best way to instantiate a Java ArrayList object in a JSP? How to define a custom tag that displays the content of a Map in HTML table format? How to create a single customer tag that renders an SQL result in table format? August 21, 2008 Nick Duan 23 12