1 / 31

Week 10

Week 10. JSP Tags. JSP-page logic / code. Java-code can be used in JSP-page <% java-code %> Everything is possible But: bad habit to combine user interface with (business) logic, and data-layer. Interface and Logic/data. Differentiate between user interface and logic/data

ethel
Download Presentation

Week 10

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. Week 10 JSP Tags

  2. JSP-page logic / code • Java-code can be used in JSP-page • <% java-code %> • Everything is possible • But: bad habit to combine user interface with (business) logic, and data-layer

  3. Interface and Logic/data • Differentiate between user interface and logic/data • User interface for web-designers • Java? HTML + XML (tags) • Logic/data for software engineers • Classes and layers • Layers: controller / business logic / data (database)

  4. JSP-tags for interface • Tags like HTML • <jsp:forward page="relative URL"/> • Tags (start- and endtags) + parameters • Tags are translated (runtime) into java-code • Tags need tag-library

  5. Example: Page-logic (java-code) <jsp:useBean id="bean0" scope="session" class="studexercise.UserBean" /> <jsp:setProperty name="bean0" property="*" /> <% if (bean0.getLoggedIn()){ //display menu if (bean0.getIsStudent()) //user is student response.sendRedirect("studentMenu1.jsp"); else //user must be a teacher response.sendRedirect("docentMenu1.jsp"); } else {//return to login page response.sendRedirect("Start2.jsp"); } %>

  6. Example: Page-logic (tags) <jsp:useBean id="bean0" scope="session" class="studexercise.UserBean" /> <jsp:setProperty name="bean0" property="*" /> <c:if test="${!bean0.loggedIn}"> <jsp:forward page="Start2.jsp"/> </c:if> <c:if test="${bean0.isStudent}"> <jsp:forward page="studentMenu1.jsp"/> </c:if> <jsp:forward page="docentMenu1.jsp"/>

  7. The jsp:forward Action • Forwards request to another page • Syntax: <jsp:forward page="relative URL"/> • It has a single attribute, page, which should consist of a relative URL • This could be a static value, or could be computed at request time • Examples: <jsp:forward page="/utils/errorReporter.jsp" /> <jsp:forward page="<%= someJavaExpression %>" />

  8. Standard Actions (list – recall) <jsp:useBean> Makes a JavaBeans component available in a page <jsp:getProperty> Gets a property value from a JavaBeans component and adds it to the response <jsp:setProperty> Set a JavaBeans property value <jsp:include> Includes the response from a servlet or JSP page during the request processing phase

  9. Standard Actions (list2 – recall) <jsp:forward> Forwards the processing of a request to servlet or JSP page <jsp:param> Adds a parameter value to a request handed off to another servlet or JSP page using <jsp:include> or <jsp: forward> <jsp:plugin> Generates HTML that contains the appropriate client browser-dependent elements (OBJECT or EMBED) needed to execute an applet with the Java Plug-in software

  10. JSP Action elements:External tag libraries – JSTL • JSP 1.2 introduced JSP Standard Tag Library (JSTL) • Version 1.0 released in June 2002 • Supports range of common tasks • database access, conditional loops etc • Important development for JSP technology

  11. JSTL • 4 groups actions in JSP Standard Tag Library

  12. How to use JSTL-libraries in a JSP • Declare the taglib directive in the JSP page • Specifies URI and Prefix • Example of declaring use of core library: <%@ taglib prefix = “c” uri = “http://java.sun.com/jstl/core %>

  13. Foreach: example • Problem: display list of groups in dropdown-list <%@ taglib prefix="c" uri="/c.tld" %> <jsp:useBean id="groepBean" scope="session" class="studexercise.Groep" /> <select name="selectGroup"> <c:forEach items="${groepBean.groups}" var="groep"> <option><c:out value="${groep}"/></option> </c:forEach> </select>

  14. foreach Example (more parameters) Example: JSP page using JSTL that outputs 1 to 10 on a webpageusing the <c:forEach> and <c:out> tags of the core library <%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %> <html> <head> <title>Count to 10 Example (using JSTL)</title> </head> <body> <c:forEach var="i" begin="1" end="10" step="1"> <c:out value="${i}" /> <br /> </c:forEach> </body> </html> A taglib directive declare use of core library JSTL tag examples

  15. JSTL: Example <c:foreach> All JSTL tags have a set of attributes (similar to HTML tags..) e.g. <c:foreach> tag has 6 attributes: var, items, varStatus, begin, end, step The full details for each attribute is in the JSTL specification document (on website). See p 65 for <c:foreach> tag definition Will need to use this document to verify WHICH tag should be used and HOW is should be used

  16. JSTL: Example <c:out> <c:out> .. outputs a value to webpage. Usually uses just one attribute value Examples: <c:out value="${i}" /> <c:out value=“The result of 1 + 2 is ${1+2}” /> <c:out value=“param.userName" />

  17. JSTL: Example <c:if> <c:if> .. evaluates a condition. Uses an attribute test to hold the condition Example : <%-- Simple if conditions --%> <c:if test='${param.p == "someValue"}'> Generate this template text if p equals someValue </c:if> Example 2 <c:if test='${param.p}'> Generate this template text if p equals "true“ </c:if>

  18. JSTL: Multiple ‘if’ conditions An if/else action requires the use of the <c:choose> tag Syntax : <c:choose> body content (<when> and <otherwise> subtags) </c:choose>

  19. JSTL: Multiple ‘if’ conditions Uses <c:choose>, <c:when> and <c:otherwise> Example: <c:choose> <c:when test='${param.p == "0"}'> <c:out value = “zero recorded”/> </c:when> <c:when test='${param.p == "1"}'> Generate this <c:out value = “single value”/> </c:when> <c:otherwise> <c:out value = “Set to ${param.p}”/> </c:otherwise> </c:choose>

  20. JSTL: Other core <c:..> actions Other examples: (NOT a complete list!) <c:set> ….sets the value of a variable <c:remove> ….removes a scoped variable <c:catch> ….catches an exception <c:url> ….. encodes a URL <c:import>… imports the content of a resource <c:redirect>.. redirects to another URL <c:param>.. adds a request parameter to other actions

  21. JSTL: <fmt:…..> example • JSTL contains Formatting library • tags useful for formatting numbers, times and dates • e.g. <fmt:parseDate>

  22. JSTL: <fmt:parseDate> example <%@ taglib uri="http://java.sun.com/jstl/fmt" prefix=“fmt" %> <html> etc etc <fmt:parseDatevalue= ${param.empDate}” var = “parsedEmpDate type = “date” pattern = “yyyy-MM-dd” /> etc etc </html> The fmt:parseDate action takes the date or time string specified by the value attribute (e.g. 2001-09-28) , interprets it according to the pattern defined by the pattern attribute and saves it in a variable called “parsedEmpDate”

  23. JSTL: other <fmt> actions Other examples: (NOT a complete list!) <fmt:formatNumber> - formats a numeric value e.g. number of digits, currency, decimal place e.g.<fmt:formatNumber value="12.3" pattern=".000"/> will output “12.300” <fmt:formatDate> --formats a date and time

  24. Tag Library Descriptor • TLD binds the custom tags to Java-classes ‘behind the code’ that implement the tags <taglib> … <description>Custom tags voor Saxion Hogeschool</description> … <tag> <name>showStudent</name> <tag-class>org.saxion.ict.tags.ShowStudentTagImpl</tag-class> <body-content>empty</body-content> <attribute> <name>name</name> <required>true</required> </attribute> … </tag> </taglib>

  25. JSTL in Jbuilder • .Jar must be in lib • Tld must be in module library • In Jbuilder: • Tools/add lib • Add lib to project

  26. jstl.jar   JBuilder • JSTL-tag-library installed by default in JBuilderX • to use it you must alter a few settings in JBuilder: • 1.you will have to add the library to your project. • 2.Then copy the c.tld (see installed files in JBuilder-directory!) to the module-directory. Now it should work. • NO!  • 3. Lib must ALSO be in WEB-INF?! Copy it manually!

  27. Examples (code) • Problem: • Display dropdown-list with names of students • How to populate the list? • Values must be filled with loop! •  while (or iterator) in Java • How to use JSP-tags? • 2 solutions: repeater and foreach

  28. ForEach-tag (JSTL) //now we use the forEach-tag to loop through the list //the field (getter!) personsNotInGroup returns an ArrayList. //That arraylist implements Iterator, so it can loop. //Every loop the variable "userid" is created, and the contents of that "userid" //can be printed on the HTML-page (c:out-tag) <select name="studentToBeAdded"> <c:forEach items="${groupBean.personsNotInGroup}" var="userid"> <option><c:out value="${userid}"/></option> </c:forEach> </select>

  29. Custom Actions (Tag Libraries) • Can Define Your own! • Description • Define • Install • Declare • Use • Details in JavaServer Pages 2nd ed found on Safari Techbooks

  30. Custom tag implementatie package org.saxion.ict.tags; import javax.jsp.tagext.TagSupport; … public class ShowStudentTagImpl extends TagSupport { private String name; public void setName(String name) { this.name = name; } public String getName() { return name; } private String scope; … public int doEndTag() { try { HttpSession session=pageContext.getSession(); Student student=(Student)session.getAttribute(name); pageContext.getOut().println(“<TD>Naam:”+student.getLastName()+”</TD>”); … } catch (Exception ignored) { } return EVAL_PAGE; } … }

  31. zie Tomcat 5 examples panel.jsp <%@ attribute name="color" %><%@ attribute name="bgcolor" %><%@ attribute name="title" %><table border="1" bgcolor="${color}"> <tr><td><b>${title}</b></td></tr> <tr><td bgcolor="${bgcolor}"><jsp:doBody/></td></tr></table> …<tags:panel color=“blue" bgcolor=“white" title="Panel 1"> Inhoud van een panel.<br/></tags:panel>…<tags:panel color=“white" bgcolor=“black" title="Panel 1"> Inhoud van een ander panel.<br/></tags:panel>… panel.tag

More Related