Presentation is loading. Please wait.

Presentation is loading. Please wait.

Intermediate JSP Matt Wheeler. Notes This is a training NOT a presentation Please ask questions Prerequisites – Introduction to Java Stack – Basic Java.

Similar presentations


Presentation on theme: "Intermediate JSP Matt Wheeler. Notes This is a training NOT a presentation Please ask questions Prerequisites – Introduction to Java Stack – Basic Java."— Presentation transcript:

1 Intermediate JSP Matt Wheeler

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

3 Overview Review Scriptlets Expressions Expression Language (EL) Taglibs Custom taglibs Functions Templating

4 Review Scriptlets Expressions …

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

6 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 <% } %>

7 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: – http://www.javaranch.com/journal/200603/Journal2 00603.jsp#a5

8 Expression Language (EL) The expression language is meant to provide easy access within a JSP page to application data 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: http://download.oracle.com/javaee/6/tutorial/ doc/gjddd.html

9 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}

10 EL (JavaBeans) EL looks for a specified bean in all scopes (request, session, application) to resolve the EL – ${someBean.whatever} After a bean/resource named someBean is found EL attempts to access the whatever property of that bean //TODO: give example of someBean

11 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[1]} //access the item at index 1 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

12 EL (Implicit Objects) Objects exposed for reference in EL without any extra work or configuration from the developer Some of these objects include: – pageContext (provides access to 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

13 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 – Empty: empty, null For operator precedence, please see: http://download.oracle.com/javaee/6/tutorial/doc/ bnaik.html

14 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’]}

15 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

16 Lab 1 https://tech.lds.org/wiki/Intermediate_JSP#Lab_1_ Expression_Language_.28EL.29

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

18 Basic Usage Taglibs – Declare the namespace – Use the tag Functions – Declare the namespace – Use the function ${web:concat(‘abc’, ‘def’)}

19 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(" "); %>

20 What did this save us? Without the function <%! public String concat(String str1, str2) { return str1 + str2; } %> <% out.write(concat(“abc”, “def”)); %>

21 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

22 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 //resulting output: Include me, include me!

23 @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 //resulting output: Include me, include me! Something special

24 Additional info Also not that using the jsp:include parameters can be passed to the included page as follows: For more info on jsp:include: http://java.sun.com/products/jsp/syntax/1.2/syntax ref1214.html For more info on @include: http://java.sun.com/products/jsp/syntax/1.2/syntax ref129.html#997991

25 Demo DEMO ?

26 Common Taglibs (JSTL) JavaServer Pages Standard Tag Library (JSTL) taglibs for many common web use cases – Core – Xml processing – Internationalization and formatting

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

28 Core (c:set) Facilitates scoped variable manipulation Sets the value of the given key in the given scope – Value can also be provided as the body content of the tag – If var is null the value is removed – Basically equivalent to: Can also be used to set a property on a scoped object

29 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

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

31 Core (Urls) - Aids in constructing correctly formatted URLs with URL-rewriting rules applied – Allow session tracking even if cookies are disabled) In short – Appends a jsessionid to the end of the query string – Track requests that originate from the same user (i.e. are part of the same session) For example: //results in a rewritten url in the form of something like http://www.whatever.com/whatever.jsp;jsessionid=12345678

32 Core (Params) - 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: http://www.whatever.com/whatever.jsp?apathy=dontknow&ignorance=dontcare;jsessionid =123456789

33 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

34 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 http://whatever.com/?userInput= alert(‘You should encode this silly.”);

35 Other Useful Taglibs Spring taglibs – http://static.springsource.org/spring/docs/3.1.0.M1/spri ng-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 – In JSP you have to take special care to encode user entered values that are displayed to avoid cross site scripting errors

36 XSS: Avoidance To avoid this, all user input should be encoded before it is displayed Stack provides following encoding functions More comprehensive information: – https://tech.lds.org/wiki/Java_Stack_Security_%28Encodi ng%29_Tech_Tip – http://code.lds.org/maven- sites/stack/module.html?module=security- web/index.html ${ssw:encodeHtml(param.something)} ${ssw:encodeAttribute(param.something)} ${ssw:encodeJS(param.something)}

37 Other Stack Provided Taglibs Other taglibs – message-source – xsrfToken – display-exception – jumperPager – numberPager – param

38 Lab 2

39 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 (the tag has access to all implicit objects

40 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; }

41 Associated tld file <taglib xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web- jsptaglibrary_2_1.xsd" version="2.1"> Tag library for stack security web. 1.0 http://code.lds.org/whatever/web Spits out hello. hello org.lds.stack.whatever.web.HelloTag empty Whether hello formal or informal formal false true

42 Functions Sometimes a taglib might be overkill and all that is needed is some calculation or processing You don’t want to embed that code in the page particularly if it is reusable Accordingly jsp functions allow you to call a static java function to perform the processing

43 Functions (example) Suppose you hava 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)}

44 Tag Files 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

45 Tag Files Basically you create a file with a.tag extension and place it in WEB-INF/tags (or a subdirectory) and the container makes a JSP tag for you 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

46 Tag Files We would create a file named hello.tag and place it in WEB-INF/tags (maybe put Hello! in it) And that is it, believe it or not, it is ready for use But we have lost the customization of formal or informal hello – Not to worry

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

48 Tag Files Now our new tag can be use as follows: Then I could call this tag with: Notice that the tag is really just a basic jsp file, but that you define parts that can be overridden or customized when the tag is used //or

49 Define a portion of the tag that can be overridden by the user of the tag This tag could be utilized as follows: Before body content Default body content After body content My body content some javascript My body content

50 This tag 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

51 – 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: – http://java.sun.com/products/jsp/syntax/2.0/syntaxref20 8.html#997991

52 Tag Files 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 --%>

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

54 Templating Tag file ${title}

55 Tag file usage Use tag file as a template Freak Show How do you like me now?

56 Credit where credit is due


Download ppt "Intermediate JSP Matt Wheeler. Notes This is a training NOT a presentation Please ask questions Prerequisites – Introduction to Java Stack – Basic Java."

Similar presentations


Ads by Google