1 / 80

Middleware Technology JavaServer Pages (JSP)

Middleware Technology JavaServer Pages (JSP). Agenda. Developing JSP-based Web Application JSP 2.0 (in J2EE 1.4) EL JSTL Custom tags in JSP pages. Web Application & Components. Web Application is a deployable package Web components (Servlets and JSP's)

ailani
Download Presentation

Middleware Technology JavaServer Pages (JSP)

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Middleware TechnologyJavaServer Pages (JSP)

  2. Agenda • Developing JSP-based Web Application • JSP 2.0 (in J2EE 1.4) • EL • JSTL • Custom tags in JSP pages

  3. Web Application & Components • Web Application is a deployable package • Web components (Servlets and JSP's) • Static resource files such as images • Helper classes • Libraries • Deployment descriptor (web.xml file) • Web Application can be represented as • A hierarchy of directories and files (unpacked form) or • *.WAR file reflecting the same hierarchy (packed form)

  4. Web Application Development and Deployment Steps • 1.Write (and compile) the Web component code (Servlet or JSP) and helper classes referenced by the web component code • 2.Create any static resources (for example, images or HTML pages) • 3.Create deployment descriptor (web.xml) • 4.Build the Web application (*.war file or deployment-ready directory) • 5.Deploy the web application into a Web container • Web clients are now ready to access them via URL

  5. Example Tomcat将JSTL默认放在了jsp-examples目录中, greeting.jsp应该放在那里

  6. Example.

  7. Write and compile the Web component code • Create development tree structure • Write either servlet code or JSP pages along with related helper code • IDE (i.e. NetBeans, Eclipse with Plugin) handles all these chores

  8. Create any static resources • HTML pages • Custom pages • Login pages • Error pages • Image files that are used by HTML pages or JSP pages • Example: duke.waving.gif

  9. Development Tree Structure • JSP file can be placed under the deployment directory together with the main HTML files. • JSP files can also be mapped to specific URLs in the web.xml file.

  10. Deployment Descriptor (web.xml) • Every web application has to have web.xml • The configuration information for JSP pages is described in the web.xml file rooted on the <jsp-config> element. • Configuration elements may include: • <taglib> - element in mapping of tag libraries • <jsp-property-group> - properties of collections of JSP files, such as page encoding or automatic includes before and after pages, etc

  11. Example: Deployment Descriptor • Common header and footer for JSP file can be defined in the web.xml file as follows: • <?xml version="1.0" encoding="UTF-8"?> • <web-app> • <jsp-config> • <jsp-property-group> • <url-pattern>*.jsp</url-pattern> • <include-prelude>/header.jsp</include-prelude> • <include-coda>/footer.jsp</include-coda> • </jsp-property-group> • </jsp-config> • </web-app>

  12. Mapping JSP to a URL • A JSP page can be mapped to a specific URL by modifying the web.xml file. • <?xml version="1.0" encoding="UTF-8"?> • <web-app> • <servlet> • <servlet-name>greeting</servlet-name> • <jsp-file>/greeting.jsp</jsp-file> • </servlet> • <servlet-mapping> • <servlet-name>greeting</servlet-name> • <url-pattern>/greeting</url-pattern> • </servlet-mapping> • </web-app>

  13. Example: Mapping JSP • Investigate the mapping mechanism for JSP file. • Create a JSP • Put it under the directory <your_web_context>/WEB-INF/classes/ • Browse it with a web browser

  14. Build the Web application • Either *.WAR file or unpacked form of *.WAR file • Build the “.war” file • Use IDE (Eclipse with Lomboz) • Use ant tool after putting proper build instruction in build.xml file • Use “jar cvf <filename>.war .” command under build directory

  15. Directory Structure of *.WAR file

  16. Install or Deploy Web application • There are 2 different ways to install/deploy Web application • By manually copying files to Tomcat's webapps directory and then restarting Tomcat • By asking Tomcat Manager via sending a command to it (Tomcat Manager is just another Servlet app that is always running) • ant install • ant deploy

  17. Perform Client Access to Web Application • From a browser, go to URL of the Web application • http://localhost:8080/hello/greeting

  18. Document Root & Context • Document Root of the Web application • Top-level directory of WAR • Contains JSP pages, client-side classes and archives, and static Web resources are stored • Also contains WEB-INF directory • A context is a name that gets mapped to the document root of a Web application • /hello is context for hello example • Distinguishes a Web application in a single Web container • Has to be specified as part of client URL

  19. JSP 2.0 (in J2EE 1.4)

  20. JSP 2.0 Expression Language • JSP-specific expression language(JSP EL), is defined in JSP 2.0 specification. • JSP EL provides a cleaner syntax and is designed specially for JSP.

  21. JSP EL Examples • A variable can be accessed as: ${variable_name} • The property can be accessed as: <c:if test="${aBean.age < 20}"> … </c:if>

  22. JSP EL: Syntax • In JSP EL, expressions are always enclosed by ${} characters. • Any values not begin with ${ is literal. • Literal value containers the ${ has to be escaped with “\” character.

  23. JSP EL: Attributes • Attributes are accessed by name, with an optional scope. • Members, getter methods, and array items are all accessed with a “.” • Examples: • A member b in object a ${a.b} • A member in an array a[b] ${a.b} or ${a["b"]}

  24. Example 1 • Using scriptlets: • Equivalent, using an EL expression: <center> <jsp:useBean id="foo" class="FooBean" /> <%= foo.getBar() %> </center> <center> ${foo.bar} </center>

  25. Example 2 • Using scriptlets: • Equivalent, using an EL expression: <% Map m = (Map)pageContext.getAttribute("state" ); State s = ((State)m.get( "NY" )); if( s != null ) { %> <%= s.getCapitol() %> <% } %> ${state["NY"].capitol}

  26. Data structures: arrays, maps, sets • Arrays and maps permit access to their collection via indices • arrays via integer indices • maps via key indices. • EL regards both of these accesses as syntactically similar using the [ ] operator. <% Map<String,String> theMap = new HashMap<String,String>(); theMap.put("John", "5"); theMap.put("Jim", "7"); String theArray[] = { "aaa", "bbb", "ccc" }; session.setAttribute( "theMap", theMap ); session.setAttribute( "theArray", theArray ); %> ${theMap["Jim"]} <!-- same as theMap.get("Jim"), outputs 7 --> ${theArray[1]} <!-- outputs bbb -->

  27. Data structures: arrays, maps, sets • The EL expressions for maps, sets and lists can all print directly. • Arrays, as in Java, don't print directly, but must use an auxiliary function. • In this case the fn:join function serves the purpose: ${fn:join(theArray,",")}

  28. JSP EL: Operators • [] . • () - Used to change the precedence of operators. • - (unary) not ! empty • * / div % mod • + - (binary) • < > <= >= lt gt le ge • == != eq ne • && and • || or • ? : • Note: order of preference from top to bottom, left to right

  29. Notes for EL • The == operator for strings functions like the Java .equals operator. • An EL expression with an undefined value, which (normally represented by null in Java) is also represented by null in EL, but is equivalent to the empty string. • EL has a unary operator empty: empty(x) acts like the expression x==null but also means "x equals the empty string". • The operators or, and are synonyms for ||, &&, respectively.

  30. Reserved Words • The following words are reserved for the JSP expression language and should not be used as identifiers. • and   eq   gt   true   instanceof or    ne   le   false  empty not   lt   ge   null   div   mod • Note that many of these words are not in the language now, but they may be in the future, so you should avoid using them.

  31. Query parameters • The value of the parameter “xx” is expressed by the EL expression param.xx. (param是一个内置对象) • Using an EL expression • Equivalent, using scriptlets: ${param.xx} <%= (request.getParameter("xx") != null) ? (request.getParameter("xx") : "" %>

  32. JSP EL: Implicit Objects 1 • A set of implicit objects is defined to match the JSP equivalents: • 1) pageContext: the context for the JSP page • Through pageContext, the following implict objects can be accessed: • servletContext • session • sequest/response • For example, the context path can be accessed as: • ${pageContext.request.contextPath}

  33. JSP EL: Implicit Objects 2 • 2) param • Maps name of parameter to a single string value • Same as ServletRequest.getParameter(String name) • E.g. ${param.name} • 3) paramValues • Map name of parameter to an array of string objects • Same as ServletRequest.getParameterValues(String name) • E.g. ${paramValues.name}

  34. JSP EL: Implicit Objects 3 • 4) header • Maps a request header name to a single string header value • Same as HttpServletRequest.getHeader(String name) • E.g. ${header.name} • 5) headerValues • Map request header names to an array of string objects • Same as HttpServletRequest.getHeaders(String name) • E.g. ${headerValues.name} • 6) cookie • Maps the single cookie objects that are available by invoking HttpServletRequest.getCookies() • If there are multiple cookies with the same name, only the first one encountered is placed in the map

  35. JSP EL: Implicit Objects 4 • Additional implicit objects are available for accessing scope attributes: • pageScope • requestScope • sessionScope • applicationScope • For example: • ${sessionScope.user.userid}

  36. Session variables are EL variables • A session variable x automatically becomes available as an EL variable • Example: <% session.setAttribute( "x", "hello" ); // or pageContext.setAttribute( "x", "hello" ); %> x = ${x} <!-- prints: x = hello -- >

  37. JSP EL: Defining EL Functions 1 • To define a function you program it as a public static method in a public class. package mypkg; public class MyLocales {    ...    public static boolean equals( String l1, String l2 ) {      return l1.equals(l2);    } }

  38. JSP EL: Defining EL Functions 2 • Map the function name as used in the EL expression to the defining class and function signature in a TLD (Tag Library Descriptor). • <?xml version="1.0" encoding="UTF-8"?> • <web-app>No two functions within a tag library can have the same name. • <jsp-config> • <taglib> • <function>    • <name>equals</name> • <function-class>mypkg.MyLocales</function-class>   • <function-signature> • boolean equals( java.lang.String,  java.lang.String ) • </function-signature> • </function> • </taglib> • </jsp-config> • </web-app> No two functions within a tag library can have the same name.

  39. JSP EL: Using EL Functions • The previous EL functions can be used as following: • ${equals('string1', 'string2')}

  40. JSP EL Compatibility • Using JSP EL may cause compatibility problems with JSP1.2 and earlier code. • JSP EL is disabled by default for a web application with a deployment descriptor that is not Servlet 2.4 conformant and it's enabled by default for a web application with a Servlet 2.4 deployment descriptor. • JSP EL is enabled by default for a web applications with Servlet 2.4 deployment descriptor.

  41. Enabling / Disabling JSP EL • For a single page with the el-Ignored page attribute • <%@ page isELIgnored="true|false"%> • For a set of JSP pages with an <el-ignored> element in a JSP group: <web-app ...> ... <jsp-config> <jsp-property-group> <url-pattern>*.jsp</url-pattern> <el-ignored>true</el-ignored> </jsp-property-group> </jsp-config> ... </web-app>

  42. Standard Tag Library • JavaServer Pages Standard Tag Library (JSTL) is an extended set of JSP standard action includes the following tags: • Iteration and conditional • Expression language • Url manipulation • Internationalization-capable text formatting • Xml manipulation • Database access

  43. Problems with JSP Scriptlet Tags • Java code is embedded within scriptlet tags • Non-Java developer cannot understand the embedded java code • Java code within JSP scriptlets cannot be reused by other JSP pages • Casting to the object’s class is required when retrieving objects out of HTTP request and session.

  44. Advantage of JSTL • JSTL tags are in xml format and can be cleanly and uniformly blended into a page’s html mark up tags. • JSTL tag libraries are organized into four libraries which include most functionality required for a JSP page and are easier for non-programmers to use • JSTL tags encapsulate reusable logic and allow to be reused. • No casting is requiring while using JSTL referencing objects in the request and session • JSP’s EL allows using dot notation to access the attributes of java objects.

  45. Example: JSTL 1 • Without JSTL, some scriplets may look as follows • <% • List addresses = (List)request.getAttribute("addresses"); • Iterator addressIter = addresses.iterator(); • while(addressIter.hasNext()) { • AddressVo address = (AddressVo)addressIter.next(); • if(address != null) {%> • <%=address.getLastName() %><br /> • <% } else { %> N/A<br /> • <% } • } • %>

  46. Example: JSTL 2 • With JSTL, the previous may looks as follows • <% taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> • <c:forEach item=${addresses} var="address" > • <c:choose> • <c:when test="${address != null}"> • <c:out value="${address.lastName}"/><br/> • <c:otherwise> • N/A<br/> • </c:otherwise> • </c:choose> • </c:forEach>

  47. Using JSTL • JSTL is standardized, but not a standard part of JSP 1.2 or 2.0 • JSTL must be downloaded and installed separately before being used.

  48. Installing the JSTL • The JSTL will be installed and setup for used. • Download the library from this URL: • http://www.apache.org/dist/jakarta/taglibs/standard/ • Unpack the file and two jar files are inside the /lib dirctory: • jstl.jar • standard.jar

  49. Installing the JSTL • Copy the jar file to the following directory • <Tomcat_Home>/common/lib • The jar file can also be copied to the /WEB-INF/lib directory under your application context. • In the JSP page, the following tags can be used to refer to the installed JSTL: <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

  50. Organization of JSTL • The JSTL tags are organized into five libraries

More Related