Intermediate JSP Matt Wheeler. Notes This is a training NOT a presentation If you have questions please ask them Prerequisites – Introduction to Java.

Slides:



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

JSP1 Java Server Pages (JSP) Introducing JavaServer Pages TM (JSP TM ) JSP scripting elements.
© Yaron Kanza Advanced Java Server Pages Written by Dr. Yaron Kanza, Edited by permission from author by Liron Blecher.
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.
Chapter 51 Scripting With JSP Elements JavaServer Pages By Xue Bai.
Using JavaServer Pages Harry R. Erwin, PhD CIT304/CSE301.
CS320 Web and Internet Programming Java Beans and Expression Language (EL) Chengyu Sun California State University, Los Angeles.
DT211/3 Internet Application Development
CS320 Web and Internet Programming JSP Standard Tag Library (JSTL) Chengyu Sun California State University, Los Angeles.
DT228/3 Web Development JSP: Directives and Scripting elements.
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.
Java Enterprise Edition Java Web Development Structure of a web project Introduction to Web Applications The first project Introduction to Java Web Development.
UNIT-V The MVC architecture and Struts Framework.
ASHIMA KALRA.  INTRODUCTION TO JSP INTRODUCTION TO JSP  IMPLICIT OBJECTS IMPLICIT OBJECTS  COOKIES COOKIES.
1 CIS336 Website design, implementation and management (also Semester 2 of CIS219, CIS221 and IT226) Lecture 9 JavaServer Pages (JSP) (Based on Møller.
JSP Standard Tag Library
CSC 2720 Building Web Applications Using Java Beans, Custom Tags and Tag Libraries in JSP pages.
Internationalization and the Java Stack Matt Wheeler.
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.
® IBM Software Group © 2007 IBM Corporation JSP Custom Tags
Introduction to Java Server Pages (JSPs) Robert Thornton.
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.
CSCI 6962: Server-side Design and Programming Java Server Faces Components and Tags.
Internationalization in the Java Stack Matt Wheeler.
® 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,
JAVA SERVER PAGES CREATING DYNAMIC WEB PAGES USING JAVA James Faeldon CS 119 Enterprise Systems Programming.
Slides © Marty Hall, book © Sun Microsystems Press 1 JSP Scripting Elements Core Servlets & JSP book:
JSTL, XML and XSLT An introduction to JSP Standard Tag Library and XML/XSLT transformation for Web layout.
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.
JSTL: The JavaServer Pages Standard Tag Library Mark A. Kolb Security Broadband, Austin, TX
JSTL Lec Umair©2006, All rights reserved JSTL (ni) Acronym of  JavaServer Pages Standard Tag Library JSTL (like JSP) is a specification, not an.
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.
JSP Fundamentals Elements of a JSP Using Beans with JSP Integrating Servlets and 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.
Java Server Pages (JSP)
JSTL The JavaServer Pages Standard Tag Library (JSTL) is a collection of useful JSP tags which encapsulates core functionality common to many JSP applications.
JSP Expression Language (EL) 25-Nov-15. JSP - E XPRESSION L ANGUAGE (EL) Introduction Expression Language was first introduced in JSTL 1.0 (JSP Standard.
JSP Custom Tags. Prerequisites Servlet API Mapping to JSP implicit objects JavaServer Pages Basic syntax Implementation via servlet API XML.
CSC 2720 Building Web Applications JavaServer Pages (JSP) JSP Directives and Action Elements.
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.
JSP. Types of JSP Scripting Elements Expressions of the form, which are evaluated and inserted into the servlet's output. Scriptlets of the form, which.
EL and JSTL. JSTL Sources
JSP BASICS AND ARCHITECTURE. Goals of JSP Simplify Creation of dynamic pages. Separate Dynamic and Static content.
Introduction to Servlets Allen Day. Notes This is a training NOT a presentation Please ask questions Prerequisites.
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.
Intermediate JSP Matt Wheeler. Notes This is a training NOT a presentation Please ask questions Prerequisites – Introduction to Java Stack – Basic Java.
JSP JavaServer Pages. What is JSP? Java based technology that simplifies the development of dynamic web sites JSP pages are HTML pages with embedded code.
10 Copyright © 2004, Oracle. All rights reserved. Building ADF View Components.
CS520 Web Programming Servlet and JSP Review
JSP: Actions elements and JSTL
Internationalization
CS520 Web Programming Servlet and JSP Review
Knowledge Byte In this section, you will learn about:
JSP Standard Tag Library
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:

Intermediate JSP Matt Wheeler

Notes This is a training NOT a presentation If you have questions please ask them Prerequisites – Introduction to Java Stack – Basic Java and XML skills – Introduction to JSP – Installed LDSTech IDE (or other equivalent)

Overview Review Scriptlets Expressions Expression Language (EL) Taglibs (JSTL, Spring, Stack) Custom taglibs Functions Templating

Review Scriptlets Expressions …

Scriptlets Scriptlets are code in a JSP page (delimited with ) Will be compiled into the service method of the resulting servlet Lets look at a simple example <% String user = request.getAttribute(“loggedInUser”); if (user != null) { %> Welcome <% } %>

Expressions Like scriptlets but evaluate a singular Java expression and return the result Result must be a String or convertible to a String – The syntax is as follows: For example: <% String user= request.getAttribute(“loggedInUser”); if (user != null) { %> Welcome <% } %>

Disadvantages Maintenance, maintenance, maintenance – Difficult to read – Difficult to understand Not testable Not reusable Difficult to refactor Tightly coupled UI and back end code The long version can be found here: – jsp#a5

Expression Language (EL) The expression language is meant to provide easy access within a JSP page to application data/logic in JavaBeans EL is really the bridge between the model and the view and allows for separation of concerns For detailed information on the JSP EL please see: doc/gjddd.html

EL (continued) Use of EL will help mitigate too much logic in JSP pages EL allows access to properties and attributes of: – JavaBeans – Collections – Implicit objects //accessing a JavaBean ${someBean} ${someBean.someProperty} //accessing a value of a map with key of someKey ${someBean.map['someKey']} //accessing an implicit object (request) ${request.param}

EL (JavaBeans) EL looks for a specified bean in all scopes (request, session, application) to resolve the expression – ${someBean.whatever} After a bean/resource named someBean is found EL attempts to access the whatever property of the bean public class SomeBean { private String whatever; public String getWhatever() { return this.whatever; } public void setWhatever(String whatever) { this.whatever = whatever; }

EL (Collections) EL provides special syntax for accessing items in lists or maps List properties can be accessed with array notation Map items can be accessed with map or dot notation ${someBean.someList[0]} //access the first item in the list ${someBean.someMap['key']} //access the item in the map with key of 'key' ${someBean.someMap.key} //equivalently use dot notation for the same result

EL (Implicit Objects) Objects exposed for reference in EL without any extra work or configuration from the developer Some of these objects include: – pageContext, request, session, application, pageScope, requestScope, sessionScope, applicationScope, param, paramValues, header, headerValues, cookie, cookies, initParam, exception ${requestScope['nameOfSubmitted']} //extracts value for attribute of given name ${param['nameOfRequestParam']} //gets value off the url for the given name ${header['Accept-Language']} //find value for header with name Accept-Language ${initParam['paramName']} //gets the value of the initParam with name paramName ${pageContext.request.servletPath} //gets the servlet path from the request

EL (operators) While most of the view logic will be in JavaBeans, EL allows for limited logic in the view EL provides some basic operators – Logical: &&, ||, !, and, or not – Comparison: ==, !=,, =, eq, ne, lt, gt, ge, le – Conditional (turnary): test ? result1 : result2 – Arithmetic: +, -, *, /, div, %, mod, E – Empty: empty, null For operator precedence, please see: bnaik.html

EL (operators) Some examples ${someBean.administrator && someBean.owner} ${someBean.count > 0} ${someBean.count + 1 % 2} ${someBean.count *.1 gt 50 && (someBean.payTaxes || someBean.goToJail)} ${4.0 eq (3 + 1)/1} ${someBean.map['someKey']}

EL (Evaluation) There are multiple implicit resolvers that attempt to handle EL expressions In general, say we are resolving ${someBean.abc} One of the EL resolvers will, grab the first portion someBean – Will look for an implicit object of that name – Will then look for a bean of that name – Once found, it will look for a property on that name or implicit object (abc) and get that value

Lab 1 Expression_Language_.28EL.29

Taglibs Primary goal of taglibs it to provide reusable functionality – Through reusable tag elements – Through functions that extend EL Simplifies jsp pages making them more readable / maintainable by separating logic from the page’s presentation

Basic Usage Taglibs – Declare the namespace – Use the tag Functions – Declare the namespace – Use the function ${fn:join(array, ', ')}

What did these save us? Without the taglib <% String style = pageContext.getRequest().getAttributes(“exceptionStyle”); if (style == null || "".equals(style.trim())) { out.write(" } else { writer.write(" "); } if (pageContext.getException() == null) { out.write("No exception was available to print."); } else { pageContext.getException().printStackTrace(new PrintWriter(out)); } out.write(" "); %>

What did this save us? Without the function <%! public String join(String[] array, String separator) { if (array == null) return ""; if (separator == null) separator = ""; StringBuffer buf = new StringBuffer(); for (int i=0; i<array.length; i++) { buf.append(array[i]); if (i < array.length-1) buf.append(separator); } return buf.toString(); } %> <% String joined = join(someArray, “,”)); … %>

JSP Include Allows you to include static or dynamic resources in a JSP page – Facilitates reuse – Allows separation into manageable pieces – Two include mechanisms available in JSP

jsp:include Executes the included content and then includes the result in the containing JSP page //include.jsp Include me, include me! ${parentValue} //include-demo.jsp <% String parentValue = “Something spectial"; pageContext.setAttribute("parentValue", parentValue); %> //resulting output: Include me, include me!

@include (directive) Includes the content and then executes the page – Can depend on (or conflict) with variables in the containing page – Page takes a relative url //include.jsp Include me, include me! ${parentValue} //include-demo.jsp <% String parentValue = “Something special”; pageContext.setAttribute("parentValue", parentValue); %> //resulting output: Include me, include me! Something special

Additional info Also note that using the jsp:include, parameters can be passed to the included page as follows: For more info on jsp:include: ref1214.html For more info ref129.html#997991

Demo DEMO

Common Taglibs (JSTL) JavaServer Pages Standard Tag Library (JSTL) taglibs for many common web use cases – Core – Xml processing – Internationalization and formatting For more info: /products/products/jsp/jstl/1.1/docs/tlddocs/ind ex.html

Core Tags (c:out) c:out evaluates an expression and outputs it to the JspWriter – Allows you to provide a default

Core (conditionals) c:if – executes based on the result of the test attribute If / else equivalent (choose, when, otherwise) 2}"> Party time Display this if there are no results Display all of the results

Core (Looping and Iteration) c:forEach – loops over an array, Collection, Iterator, Enumeration, Map, String of comma separated values ${result.property1} ${result.property2}

Core (c:set) Facilitates scoped variable manipulation Sets the value of the given key in the given scope – Basically equivalent to: – Value can also be provided as the body content of the tag – If var is null (i.e. not specified – var="null" will set the attribute to the String "null") the value is removed Append confidential data

Core (c:set) - can also be used to set a property on a scoped object

Core (Urls) - Aids in constructing correctly formatted URLs with encoding applied - Often used in correlation with c:url to add query parameters to the url – Note that the name and value are URL encoded by default (more later) For example: Result would be something like: on'tknow;jsessionid=

Core Internationalization and Formatting Taglib – Provides support for internationalization related functions such as: Locales, resource bundles, and base names Xml Processing Taglib – Provides support for basic xml processing as well as xml flow control and transformations

JSTL Functions fn:contains() fn:containsIgnoreCase() fn:endsWith() fn:escapeXml() fn:indexOf() fn:join() fn:length() fn:replace() fn:split() fn:startsWith() fn:substring() fn:substringAfter() fn:substringBefore() fn:toLowerCase() fn:toUpperCase() fn:trim() For more info: ocs/tlddocs/

Other Useful Taglibs Spring taglibs – spring-framework-reference/html/spring.tld.html Stack Security taglib – JSP doesn’t defend against xss like JSF did (i.e. encode all output) – In JSF everything output with an h:outputText was encoded by default – In JSP you have to take special care to encode values that are displayed to avoid cross site scripting errors

XSS: The Problem In short, cross-site scripting is when user entered data executes as a script instead of being displayed as text For example: – Assume a page takes a parameter on the url and displays it – And then in your page, you put ${param.userInput} – Instead of showing on the page as text this will actually become a script in the page and be executed displaying an alert to the user – For more info: site_scripting alert('You should encode this silly.');

XSS: Avoidance To avoid this, all output (especially user entered data) should be encoded before it is displayed Stack provides following encoding functions Or in code More comprehensive information: – – web/index.html ${ssw:encodeHtml(param.something)} ${ssw:encodeAttribute(param.something)} ${ssw:encodeJS(param.something)} EncodingUtils.encodeHtml(String input); EncodingUtils.encodeAttribute(String input); EncodingUtils.encodeJS(String input);

Other Stack Provided Taglibs Other taglibs – message-source – xsrfToken – display-exception

Lab 2 Taglibs

Custom Taglibs Example As the page is being processed, the tag is read, mapped to the appropriate taglib handler, and processed Further note that hello maps to a tag class (org.lds.stack.whatever.web.HelloTag) that processes the tag

Associated tld file <taglib xmlns=" xmlns:xsi=" xsi:schemaLocation=" jsptaglibrary_2_1.xsd" version="2.1"> Tag library for stack security web Spits out hello. hello org.lds.stack.whatever.web.HelloTag empty Whether hello formal or informal formal false true

Taglib class (HelloTag) HelloTag public class HelloTag extends BodyTagSupport { private Boolean formal; public int doStartTag() throws JspException { try { if (formal) { String username = (String) ((HttpServletRequest) pageContext.getRequest()).getAttribute("currentUser"); pageContext.getOut().write("Good day to you " + username); } else { pageContext.getOut().write("Howdy Partner. "); } } catch (IOException e) { throw new JspException("Error: IOException while writing to client"); } return SKIP_BODY; } public void setFormal(Boolean formal) { this. formal = formal; }

Functions Sometimes a taglib might be overkill and all that is needed is some calculation or processing You may not want to embed that code in the page, particularly if it is reusable Accordingly EL functions allow you to call a static Java function to perform the processing

Functions (example) Suppose you have a class with static methods In a tld file define the function for use in JSP Then in the JSP page use the function as follows public class MiscUtils { public static String concat(String one, String two) { return one+two; } Concatenates two strings into one. concat org.lds.stack.web.util.MiscUtils java.lang.String concat( java.lang.String, java.lang.String ) Hello ${util:concat(param.firstName, param.lastName)}

Tag Files (Taglets) Simpler way to create taglibs Better for content driven tags as opposed to complex logic tags Tag files are not quite as powerful as the regular tag approach – However they are much simpler to create – For instance you cannot put a scriptlet in a taglet

Tag Files (Taglets) Basically you create a.tag file in WEB-INF/tags (or a subdirectory) – The container then makes it available as a JSP taglib It uses the name of the file as the tag name by default and the namespace points to a tagdir instead of a uri Lets re-create our hello tag using this approach

Tag Files (Taglets) We would create a file named hello.tag and place it in WEB-INF/tags (maybe put Hello! in it) – WEB-INF/tags/hello.tag And that is it, believe it or not, it is ready for use Hello!

Tag Files (Taglets) In out hello.tag file we can add an attribute as follows: Then you would add some logic to the tag (hello.tag): Good day ${request.currentUser} Howdy partner

Tag Files Now our new tag can be used as follows: Notice that the tag is really just a basic jsp file, but that you can customize with the attributes specified //or

Define a portion of the tag that can be overridden by the user of the tag – bodytest.tag This tag could be utilized as follows: Before body content After body content My body content My body content

This directive is only valid in a tag file Possible attributes – name – name by which to reference the attribute – required – whether or not an error should be thrown if the using tag does not specify this attribute – rtexprvalue – whether or not this attribute can take an EL (runtime) expression – type – specifies the runtime type of the attribute’s value – defaults to java.lang.String

– fragment - Whether this attribute is a fragment to be evaluated by the tag handler (true) or a normal attribute to be evaluated by the container prior to being passed to the tag handler If true do not specify the rtexprvalue as the container fixes it to true If true do not sepcify the type attribute as the container fixes it to javax.servlet.jsp.tagext.JspFragment Default value is false For more info: – 8.html#997991

Attributes For example Utilize the attribute as follows: Some content More content My attribute content My body content <%-- Output would be: Some content My body content More content My attribute content --%>

In Review Tag FileClient File Entire body or and Some wonderful stuff and ${abc} Something

Templating Tag file – template.tag ${title}

Tag file usage Use tag file as a template – index.jsp How do you like me now?

Lab 3 Custom_Taglibs

Credit where credit is due Oracle Pro JSP 2 – Simon Brown, Sam Dalton, Daniel Jepp, Dave Johnson, Sing Li, Matt Raible taxref20.html