© Yaron Kanza Advanced Java Server Pages Written by Dr. Yaron Kanza, Edited by permission from author by Liron Blecher.

Slides:



Advertisements
Similar presentations
9 Copyright © 2005, Oracle. All rights reserved. Modularizing JavaServer Pages Development with Tags.
Advertisements

JSP and Servelets.
JSP and web applications
CS4273: Distributed System Technologies and Programming I Lecture 11: JavaServer Pages (JSP)
JavaServerPages Some examples. About JSP Java server pages are a combination of html (or xml), java code appearing within tagged regions, and structures.
Java II--Copyright © Tom Hunter. J2EE JSP Custom Tag Libraries.
Expression Language Lec Umair Javed©2006 Generating Dynamic Contents Technologies available  Servlets  JSP  JavaBeans  Custom Tags  Expression.
 Copyright Wipro Technologies JSP Ver 1.0 Page 1 Talent Transformation Java Server Pages.
Advanced Java Server Pages An more detailed look at JSPs.
CS320 Web and Internet Programming Java Beans and Expression Language (EL) Chengyu Sun California State University, Los Angeles.
JSP – Java Server Pages Part 1 Representation and Management of Data on the Internet.
WEB1P servintro1 Introduction to servlets and JSP Dr Jim Briggs.
JSP Tag Extensions And Java Bean. JSP Tag Extensions Tag extensions look like HTML (or rather, XML) tags embedded in a JSP page. They have a special meaning.
28/1/2001 Seminar in Databases in the Internet Environment Introduction to J ava S erver P ages technology by Naomi Chen.
DT211/3 Internet Application Development
1 CS6320 – JSP L. Grewe 2 Java Server Pages Servlets require you to write out entire page delivered with print statements Servlets require you to write.
JSP Architecture  JSP is a simple text file consisting of HTML or XML content along with JSP elements  JSP packages define the interface for the compiled.
JSP – Java Server Pages Part 2 Representation and Management of Data on the Internet.
Introduction to Java web programming Dr Jim Briggs JWP intro1.
Java Enterprise Edition Java Web Development Structure of a web project Introduction to Web Applications The first project Introduction to Java Web Development.
1 Guide to JSP common functions 1.Including the libraries as per a Java class, e.g. not having to refer to java.util.Date 2.Accessing & using external.
Struts 2.0 an Overview ( )
1 CIS336 Website design, implementation and management (also Semester 2 of CIS219, CIS221 and IT226) Lecture 9 JavaServer Pages (JSP) (Based on Møller.
CSC 2720 Building Web Applications Using Java Beans, Custom Tags and Tag Libraries in JSP pages.
Using JavaBeans and Custom Tags in JSP Lesson 3B / Slide 1 of 37 J2EE Web Components Pre-assessment Questions 1.The _____________ attribute of a JSP page.
JavaServer Faces Jeff Schmitt October 5, Introduction to JSF Presents a standard framework for building presentation tiers for web applications.
Li Tak Sing COMPS311F. Static attributes in Servlets Since Servlets are also Java classes, you can also use static attributes to store values that can.
® IBM Software Group © 2007 IBM Corporation JSP Custom Tags
Chapter 7 Java Server Pages. Objectives Explain how the separation of concerns principle applies to JSP Describe the operation and life-cycle of a JSP.
Introduction to JavaServer Pages (JSP) Slides from Dr. Mark Llewellyn.
Chapter 8 Script-free pages. Problem with scripting in JSP When you use scripting (declaration, scriplet, expressions) in your JSP, you actually put Java.
JSP Most of the web developers deploying web applications using servlets mixes the presentation logic and business logic. Separation of business logic.
® IBM Software Group © 2007 IBM Corporation JSP Expression Language
JAVA SERVER PAGES. 2 SERVLETS The purpose of a servlet is to create a Web page in response to a client request Servlets are written in Java, with a little.
Stanisław Osiński, 2002JSP – A technology for serving dynamic web content Java Server Pages™ A technology for serving dynamic web content Stanisław Osiński,
16-Oct-15 JSP Implicit Objects. 2 JSP Implicit Objects are the Java objects that the JSP Container makes available to developers in each page and developer.
1 JSP with Custom Tags Blake Adams Introduction Advanced Java Server Pages – Custom Tags Keyterms: - Tag Library Descriptor(TLD) - Tag Libraries.
Fall 2007cs4201 Advanced Java Programming Umar Kalim Dept. of Communication Systems Engineering
CS320 Web and Internet Programming Java Beans and Expression Language (EL) Chengyu Sun California State University, Los Angeles.
COMP 321 Week 11. Overview Lab 8-1 Solution Tag Files Custom Tags Web Application Deployment.
JSP Tag Libraries Lec Last Lecture Example We incorporated JavaBeans in “Course Outline” Example But still have to write java code inside java.jsp.
Java server pages. A JSP file basically contains HTML, but with embedded JSP tags with snippets of Java code inside them. A JSP file basically contains.
COMP 321 Week 10. Overview Using Beans in JSP Expression Language JSTL Lab 10-1 Introduction Exam Review.
Copyright © 2002 ProsoftTraining. All rights reserved. JavaServer Pages.
Java Server Pages (JSP)
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Java Server Pages An introduction to JSP. Containers and Components Several clients – one system.
CS320 Web and Internet Programming Custom Tag Library Chengyu Sun California State University, Los Angeles.
1 (Server-Side Programming using Java Server Pages) cs
JavaServer Page by Antonio Ko. Overview ► Introduction ► What is a servlet? ► What can servlets do? ► Servlets Vs JSP ► Syntax ► Samples ► JavaBean ►
JSP Custom Tags. Prerequisites Servlet API Mapping to JSP implicit objects JavaServer Pages Basic syntax Implementation via servlet API XML.
JSP Pages. What and Why of JSP? JSP = Java code imbedded in HTML or XML –Static portion of the page is HTML –Dynamic portion is Java Easy way to develop.
Slides © Marty Hall, book © Sun Microsystems Press 1 Using JavaBeans with JSP Core Servlets & JSP book:
JSP BASICS AND ARCHITECTURE. Goals of JSP Simplify Creation of dynamic pages. Separate Dynamic and Static content.
CS562 Advanced Java and Internet Application Introduction to the Computer Warehouse Web Application. Java Server Pages (JSP) Technology. By Team Alpha.
JAVA BEANS JSP - Standard Tag Library (JSTL) JAVA Enterprise Edition.
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 JSP Application Models.
Basic JSP Celsina Bignoli Problems with Servlets Servlets contain –request processing, –business logic –response generation all lumped.
COMP9321 Web Application Engineering Semester 2, 2015 Dr. Amin Beheshti Service Oriented Computing Group, CSE, UNSW Australia Week 3 1COMP9321, 15s2, Week.
1 Java Server Pages A Java Server Page is a file consisting of HTML or XML markup into which special tags and code blocks are inserted When the page is.
Chapter 6 Chapter 6 Server Side Programming (JSP) Part 1 1 (IS 203) WebProgramming (IS 203) Web Programming.
Java Programming: Advanced Topics 1 Building Web Applications Chapter 13.
Chapter 14 Using JavaBeans Components in JSP Documents.
J2EE JSP Custom Tag Libraries 1 3 JSP: Custom Tag Libraries.
Scripted Page Web App Development (Java Server Pages)
Knowledge Byte In this section, you will learn about:
Pre-assessment Questions
CS320 Web and Internet Programming Expression Language (EL)
CS3220 Web and Internet Programming Expression Language (EL)
CS3220 Web and Internet Programming Expression Language (EL)
Presentation transcript:

© Yaron Kanza Advanced Java Server Pages Written by Dr. Yaron Kanza, Edited by permission from author by Liron Blecher

Agenda Java Beans in JSP Custom JSP tags - TagLib JSP Expression Language

Motivation Software components (e.g. objects, data structures, primitives) are extensively used in Web applications For example: Service local variables Attributes forwarded in requests Session attributes, such as user information Application attributes, such as access counters See tutorial at 3

Motivation Standard actions are used to manipulate components: declaration, reading from the suitable context, setting of new values (according to input parameters), storing inside the suitable context, etc. Java Beans provide a specification for automatic handling and manipulation of software components in JSP (and other technologies...) 4

Java Beans: The Idea Java Beans are simply objects of classes that follow some (natural) coding convention: An empty constructor A readable property has a matching getter A writable property has a matching setter Use JSP actions to access and manipulate the bean, and special action attributes to specify the properties of the bean, e.g., its scope JSP programmers do not wish to write cumbersome code or class files 5

Example 1: Access Counter In the following example, we use a Bean to maintain an access counter for requests to the pages 6

Counter Bean - CounterBean.java package myUtils; public class CounterBean { private int counter; public CounterBean() { counter = 0; } public int getCounter() { return counter; } public void setCounter(int i) { counter = i; } public void increment() { ++counter; } } 7 Bean must reside in a package A Bean is created by an empty constructor Counter setter and getter Other methods can be implemented as well A Bean is a concept and therefore there’s no need to extend any class or implement any interface! (though it would’ve been very Java-ish to create an empty interface “Bean”)

8 Bean Example <jsp:useBean id="accessCounter" class=“myUtils.CounterBean" scope="application"/> Welcome to Page A Accesses to this application: Page B pageA.jsp Invokes getCounter() An instance named according to the given id is either found in the relevant scope or is created The default scope is page You could also use the type attribute in order to instantiate a data type which is either superclass of class or an interface that class implements

9 Bean Example <jsp:useBean id="accessCounter" class=“myUtils.CounterBean" scope="application"/> Welcome to Page B Accesses to this application: Page A pageB.jsp A very similar JSP Since an instance named according to the given id can be found in the application scope, no instantiation takes place Counter Bean – cont.

Part of the Generated Servlet myUtils.CounterBean accessCounter = null; synchronized (application) { accessCounter = (myUtils.CounterBean) _jspx_page_context.getAttribute("accessCounter", PageContext.APPLICATION_SCOPE); if (accessCounter == null) { accessCounter = new myUtils.CounterBean(); _jspx_page_context.setAttribute("accessCounter", accessCounter, PageContext.APPLICATION_SCOPE); } 10 Similar effect to getServletContext().setAttribute() Similar effect to getServletContext().getAttribute() The instance is created and kept in the application’s scope as required. Note however that accessing this instance is out of the synchronized scope

DEMO counter 11

Example 2: Session Data In the following example, we use a Bean in order to keep a user's details throughout the session 12

package myUtils; public class UserInfoBean { private String firstName; private String lastName; public UserInfoBean() { firstName = lastName = null;} public String getFirstName() {return firstName;} public String getLastName() {return lastName;} public void setFirstName(String string) {firstName = string;} public void setLastName(String string) {lastName = string;} } UserInfoBean.java Example 2: Session Data – cont. 13

Information Form Fill in your details: Your First Name: Your Last Name: infoForm.html 14 Example 2: Session Data – cont.

Page A Hello, Have a nice session! User Info B infoA.jsp Match all the request parameters to corresponding properties. You could match parameters to properties explicitly using property=… param=… You can also set properties with explicit values using property=… value=… The String values are converted to the right bean’s property types.. 15 Example 2: Session Data – cont.

Page B Hello, Have a nice session! User Info A infoB.jsp A very similar JSP This time the request has no parameters so no bean properties are set 16 Example 2: Session Data – cont.

Advantages of Java Beans Easy and standard management of data Automatic management of bean sharing and lots more Good programming style Allow standard but not direct access to members You can add code to the setters and getters (e.g. constraint checks) without changing the client code You can change the internal representation of the data without changing the client code Increase of separation between business logic (written by programmers) and HTML (written by GUI artists) 17

DEMO session 18

Agenda Java Beans in JSP Custom JSP tags - TagLib JSP Expression Language

Custom JSP Tags JSP code may use custom tags – tags that are defined and implemented by the programmer The programmer defines how each of the custom tags is translated into Java code There are two methods to define custom tags: Tag libraries - used in old versions of JSP Tag files - much simpler, introduced in JSP

Tag Libraries A tag library consists of: Tag handlers - Java classes that define how each of the new tags is translated into Java code A TLD (Tag Library Descriptor) file, which is an XML file that defines the structure and the implementing class of each tag (see a tutorial at

Date Tag Example package my; import javax.servlet.jsp.JspException; import javax.servlet.jsp.tagext.SimpleTagSupport; import java.io.IOException; public class DateTag extends SimpleTagSupport { public void doTag() throws JspException, IOException { getJspContext().getOut().print(new java.util.Date()); } DateTag.java Using the JSP-context, You can also acquire other implicit objects by calling getSession(), getRequest() etc… The class file is placed in webapps/myapp/WEB-INF/classes/my/ The java file is placed in webapps/myapp/WEB-INF/src/my/ Base class of tags which don’t handle the body or the attributes We must use a package (not necessarily named like your application) since this is a helper class which is imported form the JSP’s generated Servlet that is placed within a named package Goal : 22

date my.DateTag empty my-taglib.tld Set this value that indicates your tag library version Name of the tag Tag’s class file in /myapp/WEB-INF/classes/my/ This defined tag contains no body 23 Date Tag Example – cont.

Hello. The time is: taglibuse.jsp The prefix for this tag must appear before the tag itself (looks like a namespace). The Prefix can’t be empty The path could be a URL. If you choose to use a local path, it must begin with /WEB-INF/tags/ You can add here more tags… 24 Date Tag Example – cont.

Taglib with Attributes package my; import javax.servlet.jsp.JspException; import javax.servlet.jsp.tagext.TagSupport; import java.io.IOException; public class DateTag2 extends TagSupport { private boolean isLongFormat = false; public void setIsLongFormat(boolean b) { isLongFormat = b; } public boolean getIsLongFormat() { return isLongFormat; { 25 DateTag2.java Base class of tags which do handle attributes the attribute is defined as not required so it must have a default value Attribute’s setter method Attribute’s getter method This member’s name should be identical to the attribute’s. The setter/getter methods should be named after the attribute (i.e. “get” + capital ( ))

public int doStartTag() throws JspException { try { if (isLongFormat) { pageContext.getOut().print(new java.util.Date().getTime()); } else { pageContext.getOut().print(new java.util.Date()); } } catch (Exception e) { throw new JspException("DateTag: " + e.getMessage()); } return SKIP_BODY; } public int doEndTag() { return EVAL_PAGE; } } Invoked when the generated Servlet starts processing the “start tag” Prints the date according to the isLongFormat attribute Signals the generated Servlet there’s no body within the tag to process Invoked when the generated Servlet starts processing the “end tag” Signals the generated Servlet to continue executing the generated Servlet code 26

date2 my.DateTag2 empty isLongFormat false my-taglib2.tld Hello. The time is: Milliseconds since the epoch : taglibuse2.jsp Same as before, only with different names for the tagclass You can put several blocks one after another The attribute is “not required” so you have to define a default value in DateTag2.java Uses default attribute value Uses a given attribute value 27

How does it work? 28 taglibuse2.jsp taglibuse2_jsp.java JspContext DateTag2 setIsLongFormat() doStartTag() doEndTag() JSP to Java Servlet translation Create the JspContext When the translation engine first encounters it creates a new instance of DateTag2 (so we needn’t worry about concurrency issues) and passes it the JspContext reference The attribute value is set using the setter method. The translator actually translated the attribute string value as it appears in the JSP source, to a boolean value as the Java tag class expects it… “Start tag” is reached “End tag” is reached

Tag Files JSP 2.0 provides an extremely simplified way of defining tags The motivation: JSP programmers prefer not to write cumbersome code or class files The idea: for each custom tag, write a tag file tagName.tag that implements the tag translation using JSP code This way, the programmer can avoid creating tag handlers and TLD files 29

The Simplified Example Hello. The time is: date.tag taguse.jsp In this new mechanism we use tagdir instead of uri we used in the old taglib implementation 30

The Attributes Example 31 <%!private String createDate(String isLong) { if ((isLong == null) || (isLong.equals("false"))) { return new java.util.Date().toString();} else { return new Long(new java.util.Date().getTime()).toString();} } %> Hello. The time is: Milliseconds since the epoch : date3.tag taguse3.jsp Private method declaration Default and isLongFormat=“false” case Calls the private method isLongFormat=“true” case Default case isLongFormat=“true” A new directive The isLongFormat parameter is identified as the isLongFormat attribute because we used the attribute directive

Other Capabilities of Custom Tags Attributes You can add validation mechanism for the attributes values Tag Body Tag translation may choose to ignore, include or change the tag body 32

DEMO taglib 33

Agenda Java Beans in JSP Custom JSP tags - TagLib JSP Expression Language

JSP expression language is a comfortable tool to access useful objects in JSP This language provides shortcuts in a somewhat JavaScript-like syntax An expression in EL is written as ${expr} For example: Hi, ${user}. Welcome Note that the EL expression does not violate the XML syntax as opposed to 35

EL Variables JSP EL does not recognize JSP's implicit objects, but rather has its own set Each of these objects maps names to values param, paramValues, header,headerValues, cookie, initParam, pageScope, requestScope, sessionScope, applicationScope For example, use the param[“x”] or param.x to get the value of the parameter x Map a parameter name to a single value or to multiple values Map a header name to a single value or to multiple values Maps a cookie name to a single value Maps a context initialization parameter name to a single value 36

EL Variables (cont) A variable that is not an EL implicit object is looked up at the page, request, session (if valid) and application scopes That is, x is evaluated as the first non-null element obtained by executing pageContext.getAttribute("x"), request.getAttribute("x"), etc. Might be confusing. Make sure you know what you’re accessing! 37

Object Properties In JSP EL, Property prop of Object o is referred to as o[prop] Property prop of Object o is evaluated as follows: If o is a Map object, then o.get(prop) is returned If o is a List or an array, then prop is converted into an integer and o.get(prop) or o[prop] is returned Otherwise, treat o “as a bean”, that is: convert p to a string, and return the corresponding getter of o, that is o.getProp() The term o.p is equivalent to o["p"] 38

An Example <% response.addCookie(new Cookie(“nameof",“homer")); session.setAttribute(“homepage", new java.net.URL(" String[] strs = {"str1","str2"}; session.setAttribute("arr", strs); %> JSP Expressions Write the parameter x: elcall.jsp 39

EL Examples Expression-Language Examples Parameter x : ${param["x"]} Cookie name : ${cookie.nameof.value} Header Connection : ${header.Connection} Path of session attr. homepage : ${sessionScope.homepage.path} Element arr[${param.x}] : ${arr[param.x]} el.jsp The default value is TRUE cookie[“nameof”].getValue() header [“Connection”] sessionScope[“homepage”]. getPath(). You can omit the sessionScope ${…} means evaluate the expression inside the {} Only the ${param.x} is evaluated sessionScope [“arr”][param[“x”] 40 An Example