Session 12. JSP Tag Library (JSTL) Reading & Reference

Similar documents
Session 11. Expression Language (EL) Reading

Session 21. Expression Languages. Reading. Java EE 7 Chapter 9 in the Tutorial. Session 21 Expression Languages 11/7/ Robert Kelly,

Fast Track to Java EE 5 with Servlets, JSP & JDBC

JSTL. JSTL (Java Standard Tag Library) is a collection of custom tags that are developed and maintained by the Jakarta project.

JSP MOCK TEST JSP MOCK TEST IV

Introduction to JSP and Servlets Training 5-days

Fast Track to Java EE

This course is intended for Java programmers who wish to write programs using many of the advanced Java features.

JSTL ( )

Chapter 10 Servlets and Java Server Pages

JavaServer Pages. What is JavaServer Pages?

JAVA 2 ENTERPRISE EDITION (J2EE)

Peers Techno log ies Pv t. L td. Core Java & Core Java &Adv Adv Java Java

Application Development in JAVA. Data Types, Variable, Comments & Operators. Part I: Core Java (J2SE) Getting Started

COMP9321 Web Application Engineering

Database. Request Class. jdbc. Servlet. Result Bean. Response JSP. JSP and Servlets. A Comprehensive Study. Mahesh P. Matha

Java Server Pages. JSP Part II

COMP9321 Web Application Engineering

COMP9321 Web Application Engineering

JAVA. Duration: 2 Months

ADVANCED JAVA TRAINING IN BANGALORE

Type of Classes Nested Classes Inner Classes Local and Anonymous Inner Classes

Advanced Web Systems 3- Portlet and JSP-JSTL. A. Venturini

ANTAL Margit. Sapientia - EMTE, Pannon Forrás,,Egységes erdélyi felnőttképzés a

Oracle 10g: Build J2EE Applications

Complete Java Contents

Session 22. Intra Server Control. Lecture Objectives

open source community experience distilled

GUJARAT TECHNOLOGICAL UNIVERSITY

directive attribute1= value1 attribute2= value2... attributen= valuen %>

Java.. servlets and. murach's TRAINING & REFERENCE 2ND EDITION. Joel Murach Andrea Steelman. IlB MIKE MURACH & ASSOCIATES, INC.

112. Introduction to JSP

ive JAVA EE C u r r i c u l u m

JAVA. 1. Introduction to JAVA

Class Libraries. Readings and References. Java fundamentals. Java class libraries and data structures. Reading. Other References

112-WL. Introduction to JSP with WebLogic

Session 18. JSP Access to an XML Document XPath. Reading

JAVA MICROSERVICES. Java Language Environment. Java Set Up. Java Fundamentals. Packages. Operations

About the Authors. Who Should Read This Book. How This Book Is Organized

Java Collections. Readings and References. Collections Framework. Java 2 Collections. CSE 403, Spring 2004 Software Engineering

Session 8. JavaBeans. Reading & Reference. Reading. Reference. Session 8 Java Beans. 2/27/2013 Robert Kelly, Head First Chapter 3 (MVC)

11-1. Collections. CSE 143 Java. Java 2 Collection Interfaces. Goals for Next Several Lectures

Session 20 Data Sharing Session 20 Data Sharing & Cookies

JSP. Basic Elements. For a Tutorial, see:

AN ISO 9001:2008 CERTIFIED COMPANY ADVANCED. Java TRAINING.

Java Collections. Readings and References. Collections Framework. Java 2 Collections. References. CSE 403, Winter 2003 Software Engineering

PSD1B Advance Java Programming Unit : I-V. PSD1B- Advance Java Programming

Page 1

ADVANCED JAVA COURSE CURRICULUM

Module 3 Web Component

JAVA SYLLABUS FOR 6 WEEKS

Vendor: SUN. Exam Code: Exam Name: Sun Certified Web Component Developer for J2EE 5. Version: Demo

UNIT -5. Java Server Page

JAVA SYLLABUS FOR 6 MONTHS

More JSP. Advanced Topics in Java. Khalid Azim Mughal Version date: ATIJ More JSP 1/42

1. Introduction. 2. Life Cycle Why JSP is preferred over Servlets? 2.1. Translation. Java Server Pages (JSP) THETOPPERSWAY.

Advanced Java Exercises

FINALTERM EXAMINATION Spring 2009 CS506- Web Design and Development Solved by Tahseen Anwar

Writing Servlets and JSPs p. 1 Writing a Servlet p. 1 Writing a JSP p. 7 Compiling a Servlet p. 10 Packaging Servlets and JSPs p.

Software 1 with Java. Recitation No. 6 (Collections)

CS506 Web Design & Development Final Term Solved MCQs with Reference

SNS COLLEGE OF ENGINEERING, Coimbatore

1Z Java EE 6 Web Component Developer Certified Expert Exam Summary Syllabus Questions

Actual4Test. Actual4test - actual test exam dumps-pass for IT exams

The Standard Tag Library. Chapter 3 explained how to get values from beans to pages with the jsp:

Java EE Application Assembly & Deployment Packaging Applications, Java EE modules. Model View Controller (MVC)2 Architecture & Packaging EJB Module

Sun Sun Certified Web Component Developer for J2EE 5 Version 4.0

Object-Oriented Programming with Java

Topic #9: Collections. Readings and References. Collections. Collection Interface. Java Collections CSE142 A-1

J2EE - Version: 25. Developing Enterprise Applications with J2EE Enterprise Technologies

Unit 5 JSP (Java Server Pages)

Core Java. Basics of Java. String Handling. OOPS Concepts. Exception Handling

Experiment No: Group B_2

A Gentle Introduction to Java Server Pages

Java Collections Framework reloaded

Software 1 with Java. Java Collections Framework. Collection Interfaces. Online Resources. The Collection Interface

Call us: /

LTBP INDUSTRIAL TRAINING INSTITUTE

Oracle 1z Java Enterprise Edition 5 Web Component Developer Certified Professional Exam. Practice Test. Version:

Advanced Java Programming

Struts Lab 3: Creating the View

sessionx Desarrollo de Aplicaciones en Red EL (2) EL (1) Implicit objects in EL Literals José Rafael Rojano Cáceres

Principles and Techniques of DBMS 6 JSP & Servlet

Collections Questions

JavaServer Pages and the Expression Language

Introduction to Java Server Pages. Enabling Technologies - Plug-ins Scripted Pages

Table of Contents. Introduction... xxi

Collections and Iterators. Collections

Java SE7 Fundamentals

Implementation. (Mapping to Java) Jörg Kienzle & Alfred Strohmeier. COMP-533 Implementation

Developing Applications with Java EE 6 on WebLogic Server 12c

Topic 10: The Java Collections Framework (and Iterators)

Courses For Event Java Advanced Summer Training 2018

CONTAİNERS COLLECTİONS

Table of Contents Fast Track to Java EE 5 with Servlets/JSP and JDBC

Anno Accademico Laboratorio di Tecnologie Web. Sviluppo di applicazioni web JSP

Java J Course Outline

01KPS BF Progettazione di applicazioni web

What's New in the Servlet and JSP Specifications

Oracle EXAM - 1Z Java Enterprise Edition 5 Web Component Developer Certified Professional Exam. Buy Full Product

Transcription:

Session 12 JSP Tag Library (JSTL) 1 Reading & Reference Reading Head First Chap 9, pages 439-474 Reference (skip internationalization and sql sections) Java EE 5 Tutorial (Chapter 7) - link on CSE336 Web site (References Section) JavaWorld www.javaworld.com/javaworld/jw-02-2003/jw-0228-jstl.html Collections java.sun.com/docs/books/tutorial/collections/ 2 1

HW 4 Project Form HW 4 requires a clear approach to testing and development an understanding of objects that are passed and objects that are shared Your debugging should test your assumptions about the passed and shared objects We will build a JSP using JSTL that may help you in your debugging for HW#4 3 HW 4 Approach For now, you can use a redirect to send control from the servlet to a JSP Remember that redirect is an http header that you set in your response (with a URL) servlet Bean Use a forward if you want to read ahead OK JSP Page Debug JSP Page Form JSP Page 4 2

Web Architecture Clients Web layer Data sources servlet JSP Page JSP Page Bean JSTL Tag Custom Tag XML JDBC EJB 5 JSTL Background JSTL tags are valid XML JSTL contains actions for common tasks Iteration Session tracking Redirect XML Remember the development theme is no scriptlets Etc. You will use EL expressions in your JSTL tags 6 3

Libraries JSTL has 5 standard tag libraries Core Internationalization/format XML SQL Functions (primarily string manipulations) We refer to JSTL tags as actions (to distinguish them from static tags) 7 Example Form Debugger A JSP that you can use during testing to verify the state of your objects when you submit a request from your browser To use the form debugger, you can send your form request to this JSP instead of to your servlet 8 4

Example Form Debugger Output The JSP will output the collection of parameter name/value pairs in a table 9 Example Form Debug JSP <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <html> <head> <title>formtester</title> <link rel="stylesheet" type="text/css href="http://www.cs.sunysb.edu/~cse336/cse336.css"/> </head> <body> <h2>testing the Input Form</h2> <table> <th>parameter Name</th> <th>parameter Value</th></tr> <c:foreach var="p" items="${param}"> <td> <c:out value="${p.key}"/> </td> <td> <c:out value="${p.value}"/> </td> </tr> </c:foreach> </table> </body> </html> EL expression Declares the JSTL core tag library Variable is a named reference to an object (explicit or implicit) 10 5

c:out Use the <c:out> tag to evaluate an expression and include the expression s output in the page <c:out value="${p.value} escapexml= true default= No value for parameter /> Attributes value expression whose value is sent to the output escapexml specifies whether the html characters (e.g., <) should be converted to the corresponding character entity code default default value if EL cannot evaluate the expression or if the expression evaluates to null Is <c:out value="${p.key}"/> the same as ${p.key}? 11 JSP 2.0 You can use pure EL instead of c:out <c:out value= ${applicationscope[x]} /> <c:out value= ${x} /> ${x} Remember, these tags are equivalent (if x is a key in only the ServletContext) 12 6

c:foreach Use the <c:foreach> tag to iterate through a collection s elements <c:foreach var="p" items="${param}"> If the items attribute is a map, the iteration variable is a Map.Entry with properties of key and value Allows partial collection iteration through attributes begin end step <c:foreach var="x" begin="0" end="10" step="2"> 13 Java For Each Loop With Java 5.0, there is a new loop construct Equivalent Code Collection<String> c = ; Iterator<String> iter = c.iterator(); while (iter.hasnext()) { String elem = iter.next (); loop content } Both constructs iterate over c, a collection of objects. Java 5.0 foreach loop Code Collection<String> c = ; for (String elem : c) { loop content } For each iteration, elem is the current object 14 7

Iteration Over a Collection In JSTL, you can iterate over a collection or a range similar to Java Java Collection<String> t = ; for (String i : t) { loop content } Both constructs iterate over t, a collection of objects. <c:foreach var= i items="${t} > loop content </c:foreach> JSTL For each iteration, i is the current object It is helpful to understand the type of the iterator 15 What is a Collection? A collection is a Java object that groups multiple elements into a single unit Java uses collections in a collection framework - a unified architecture for representing and manipulating collections, allowing them to be manipulated independently of the details of their representation The Collection Framework includes Interfaces abstract data types Implementations concrete implementations Algorithms methods that perform useful computations Array utilities 16 8

Collections Interfaces Collection Map interfaces contain methods that allow them to be manipulated as collections Map Set List Queue SortedMap SortedSet BlockingQueue ConcurrentMap Some collections are ordered, some not Some allow duplicate elements, some do not Collection Interface includes an iterator method and Map interface includes methods to obtain a collection of values and a set of keys 17 Interfaces Set an unordered collection that does not allow duplicate entries List an ordered collection that allows duplicate entries Map an object that maps keys to values and does not allow duplicate keys SortedSet set sorted in ascending order SortedMap map sorted in ascending key order 18 9

Implementations (partial list) Collection Map Set List SortedMap HashMap SortedSet ArrayList Vector TreeSet HashSet TreeMap Important to separate the declaration from the implementation List l = new ArrayList(); 19 Deconstruct foreach Code <c:foreach var="p" items="${param}"> <td> ${p.key} </td> <td> ${p.value} </td> </tr> </c:foreach> What is param? What is the type of param? What is p? What is the type of p? What is p.key? What is the type of p.key? What is p.value? What is the type of p.value? What if we replace param with paramvalues? 20 10

items Attribute The items attribute can be any collection (List, LinkedList, ArrayList, Vector, Stack, Set), any Map (HashMap, Hashtable, Properties, Provider, Attributes), csv String arrays of object, and arrays of primitive. What is the type of the loop index when you iterate over an array of primitive (e.g., int)? Hint: the items attribute is a scoped variable? 21 When items Attribute is a Map If the items attribute is of type Map, the loop index will be of type Map.Entry A Map.Entry object has 2 properties key key under which this item is stored value value corresponding to the key 22 11

Example Java One Headers The http headers can be accessed and displayed using an JSTL implicit variable 23 Example Headers <h2>http Headers</h2> <table> <th>header Name</th> <th>header Value</th></tr> <c:foreach var="h" items="${header}"> <td class="name"> ${h.key} </td> <td> ${h.value} </td> </tr> </c:foreach> </table> Specifies the value property of h (the value of the current http header in the iteration) 24 12

Are We on Track? Using your laptop, code a JSP that displays the session attributes (keys and values) Use a scriptlet to store 2 attributes (with values) in your session object Use JSTL and EL to display the result in a table Hint: your answer should work for any number of attributes You can use the following CSS to display a simple cell border td {border: 1px solid black;} 25 Were We on Track? <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <html> <head>... <style>td {border: 1px solid black;}</style> </head> <body> <h1>jstl On Track Example</h1> <% session.setattribute("a1", "First Attribute"); session.setattribute("a2", "Second Attribute"); %> <table> <c:foreach var="a" items="${sessionscope}" > <td>${a.key}</td> <td>${a.value}</td> </tr> </c:foreach> </table> </body> </html> 26 13

c:if Allows you to conditionally include, or process, a piece of the page This example includes a personal greeting if the user is a repeat visitor, as indicated by the presence of a cookie with the user's name <c:if test="${!empty cookie.username}"> Welcome back ${cookie.username.value} </c:if> 27 c:foreach You can refer to the iteration count in a foreach iteration <table> <th></th> <th>header Name</th> <th>header Value</th></tr> A LoopTagStatus object (contains properties of the loop) <c:foreach var="h" items="${header}" varstatus="i > <td> ${i.count} </td> <td class="name">${h.key}</td> <td>${h.value}</td> </tr> </c:foreach> </table> 28 14

Example Display a table of ServletContext attributes (name and value) 29 Example - ServletContext <h2>servletcontext</h2> <table> <thead> <th>parameter Name</th> <th>parameter Value</th></tr></thead> <c:foreach var="p" items="${applicationscope}"> <td class="name">${p.key}</td> <td><c:out value="${p.value} default="no value for attribute"/></td> </tr> </c:foreach> </table> How would you display a table of request attributes? 30 15

Example Display a table of cookies (names, values, and max age) A value of -1 (default) for maxage indicates that the cookie will persist until browser shutdown 31 Example Cookies Display <h2>cookies</h2> <table><th>cookie Name</th> <th>cookie Value</th><th>Max Age</th></tr> <c:foreach var="cm" items="${cookie}"> <td class="name">${cm.key}</td> <td>${cm.value.value}</td> <td>${cm.value.maxage}</td> </tr> </c:foreach> </table> What is the type of cm.value? Cookie is an EL implicit object that maps cookie names to a single cookie object 32 16

Using c:set for Scoped Variables Allows you to set scoped variables in your JSP var set attribute value in a shared scope Value the Object value in the key/value pair <c:set var= Fido value= ${person.dog} /> You can also specify a scope (and a body) 33 Using c:set for Beans and Maps Allows you to do assignments in your JSP target set bean properties or map values <c:set target= ${PetMap} property= dogname value= Clover /> Target must not be null If target is a bean, sets the value of the property dogname If target is a Map, sets the value corresponding to a key named dogname 34 17

c:remove You can remove a scoped attribute using the set tag (when value evaluates to null), however it doesn t seem intuitive to remove an object with a set Use the c:remove <c:remove var= Fido scope= request /> Scope is optional, but the attribute will be removed from all scopes if scope is not specified 35 To Include Content in your JSP Include directive <%@ include file= Header.html %> jsp:include action <jsp:include page= Header.jsp /> c:import JSTL tag Static (translation time) Dynamic (request time) Dynamic (request time) <c:import url= http://www.cs.sunysb.edu... /> These are all useful to import html fragments (e.g., headers and footers) common to multiple pages c:import can access a resource outside the current Web container 36 18

Other C Library JSTL Tags c:choose / c:when / c:otherwise c:url Allows URL rewriting when cookies are disabled In the exam, you should be able to use JSTL tags you have had no previous experience with 37 Assignment 4b Write a JSP that you can use for testing in your project The JSP should display The attribute names and values contained in the shared objects (request, session, servlet context) The values of all the http headers The form data set The property values of your bean All of the items above should be contained in HTML tables, similar to the examples given in class. To display the bean properties you may need to use Java reflection. Using a scriptlet is OK for this assignment 38 19

Reflection Mechanism for discovering data about a program at runtime Fields Methods Constructors You can You can only directly use the public methods Operate on the fields you discover Create an instance of a class whose name is known only at runtime Get and set the value of an object s public fields Invoke a method on an object 39 Bean Property Analysis public class CountBean implements java.io.serializable { private int count = 0; private Calendar calendar = new GregorianCalendar(); public int getcount() { return (count); } public void setcount(int newcount) { this.count = newcount; } public Calendar getcalendar() { return (calendar); } public void setcalendar(calendar newcalendar) { this.calendar = newcalendar; } } This example will dynamically determine the bean properties and display them 40 20

Bean Viewer JSP Fragment <h3>bean Viewer</h3> <%@ page import="java.lang.reflect.*" %> <jsp:usebean id="bean" class="lectures.countbean3" /> <jsp:setproperty name="bean" property="count" value= 0" /> %> <% Class b = Class.forName("lectures.CountBean3"); Field[] fields = b.getdeclaredfields(); for (Field f : fields) { String name = f.getname(); out.println("<p>"); String camelname = "get" + (name.substring(0,1).touppercase() + name.substring(1)); Method m = b.getmethod(camelname); out.println("bean instance variable - " + name + ":"); out.println(m.invoke(bean)); out.println("</p>"); } Instantiates the bean Better done with a custom tag Gets public and private fields Note use of the Java 5 for loop We cannot access the fields directly since they are private 41 21