The document discusses creating custom tags in JavaServer Pages (JSP) that support looping functionality. It describes how to create a custom "forEach" tag that can iterate over arrays and assign each element to a scoped variable specified by the "var" attribute. Code examples demonstrate a tag handler class, tag library descriptor (TLD) file, and JSP usage of the new tag.
GPars (Groovy Parallel Systems) is an open-source concurrency and parallelism library for Java and Groovy that gives you a number of high-level abstractions for writing concurrent and parallel code in Groovy (map/reduce, fork/join, asynchronous closures, actors, agents, dataflow concurrency and other concepts), which can make your Java and Groovy code concurrent and/or parallel with little effort.
This has been presented in association with Robosepians for Java concepts. Basic concepts of Java including features, conditional statements, loop statements, arrays, string, primitive datatypes, essentials of Java including oops concepts, classes, objects, polymorphism, advance topics including packages, exception handling, multihtreading and network programming have been discussed.
GPars (Groovy Parallel Systems) is an open-source concurrency and parallelism library for Java and Groovy that gives you a number of high-level abstractions for writing concurrent and parallel code in Groovy (map/reduce, fork/join, asynchronous closures, actors, agents, dataflow concurrency and other concepts), which can make your Java and Groovy code concurrent and/or parallel with little effort.
This has been presented in association with Robosepians for Java concepts. Basic concepts of Java including features, conditional statements, loop statements, arrays, string, primitive datatypes, essentials of Java including oops concepts, classes, objects, polymorphism, advance topics including packages, exception handling, multihtreading and network programming have been discussed.
Slides from a tutorial I gave at ETech 2006. Notes to accompany these slides can be found here: http://simonwillison.net/static/2006/js-reintroduction-notes.html
Lambda: A Peek Under The Hood - Brian GoetzJAX London
This is a *highly technical* session on the details of how Lambda expressions are implemented in the Java language, presented by Java Language Architect Brian Goetz
Brian and John introduce several concepts, including JavaScript Modules and Inversion of Control, and demonstrate how they alleviate many of the dominant problems encountered when building large JavaScript apps. This talk shows new architectural patterns and tangible examples of how these patterns improve testability, refactorability, composability, division of work, and team scalability.
Slides from a tutorial I gave at ETech 2006. Notes to accompany these slides can be found here: http://simonwillison.net/static/2006/js-reintroduction-notes.html
Lambda: A Peek Under The Hood - Brian GoetzJAX London
This is a *highly technical* session on the details of how Lambda expressions are implemented in the Java language, presented by Java Language Architect Brian Goetz
Brian and John introduce several concepts, including JavaScript Modules and Inversion of Control, and demonstrate how they alleviate many of the dominant problems encountered when building large JavaScript apps. This talk shows new architectural patterns and tangible examples of how these patterns improve testability, refactorability, composability, division of work, and team scalability.
Intellicore Tech Talk 10 - Apache Web Server InternalsNeil Armstrong
Sujet : Apache Web Server Internals
Description : Le Serveur Web Apache est devenu le logiciel le plus utilisé au mondepour servir les pages internet et intranet. Son utilisation très variée, du petit site familial au site d’entreprise avec systèmes de balance de charge et architecture objet, fait que sa structure est peu connue ainsi que ses différentes configurations.
Conférenciers : Neil Armstrong, élève ingénieur chez Neotion et futur ingénieur Polytech’Nice-Sophia, spécialisé en Logiciels Embarqués et technologies Open-Source.
Date : 10 juin 2008
Lieu : Amphithéâtre Edison, CICA, Sophia Antipolis, FRANCE
Aerohive - La mort annoncée du contrôleurppuichaud
Les solutions WLAN traditionnelles à base de contrôleurs peinent à répondre à nouveaux besoins des réseaux Wi-Fi (WLAN) et doivent renier leurs fondamentaux techniques afin de s’adapter, notamment au standard 802.11n. En effet, les architectures à contrôleurs brisent le modèle Ethernet, par essence distribué : elles sont centralisées ! De ce fait, les contrôleurs constituent, pour les réseaux WLAN, des goulets d’étranglement, des points de défaillance unique. Ils ajoutent latence et gigue là où les applications temps-réel nécessitent un transport optimal sur le réseau. Ils sont limités en capacité, parfois en fonctionnalités. Ils sont complexes et couteux à mettre en œuvre dans des environnements distribués et à fort besoin de disponibilité.
Architecture d’une app qui fait 5 millions de visites par moisJulien Carnelos
Basé sur un cas réel dans la presse quotidienne régionale, cette présentation vous montrera quels sont les principes d'architecture à respecter pour concevoir et maintenir un parc d'applications mobiles natives iOS / Android / Windows Phone 8. Nous verrons les différentes étapes de la construction d'un socle commun et générique, résistant à la charge et évolutif. Nous parlerons également des solutions hybrides, de la gestion server-side, de la prise en compte du réseau mobile et des difficultés rencontrées.
This is a step by step slides to study JSP, all the concepts which are required for a JSP are present in this ppt. The whole JSP is divided into SESSIONS.
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 8 ...WebStackAcademy
In this chapter, we will discuss the Custom Tags in JSP. A custom tag is a user-defined JSP language element. When a JSP page containing a custom tag is translated into a servlet, the tag is converted to operations on an object called a tag handler. The Web container then invokes those operations when the JSP page's servlet is executed.
JSP tag extensions lets you create new tags that you can insert directly into a JavaServer Page. The JSP 2.0 specification introduced the Simple Tag Handlers for writing these custom tags.
To write a custom tag, you can simply extend SimpleTagSupport class and override the doTag() method, where you can place your code to generate content for the tag.
This is targeted to be a short tutorial for familiarising the new programming concepts introduced in Java 1.7 or Java 7.0 I contains working code snippets to familiarise with new syntax as well.... Hope you will like it !!!!
h
Sudheer Mechineni, Head of Application Frameworks, Standard Chartered Bank
Discover how Standard Chartered Bank harnessed the power of Neo4j to transform complex data access challenges into a dynamic, scalable graph database solution. This keynote will cover their journey from initial adoption to deploying a fully automated, enterprise-grade causal cluster, highlighting key strategies for modelling organisational changes and ensuring robust disaster recovery. Learn how these innovations have not only enhanced Standard Chartered Bank’s data infrastructure but also positioned them as pioneers in the banking sector’s adoption of graph technology.
Unlocking Productivity: Leveraging the Potential of Copilot in Microsoft 365, a presentation by Christoforos Vlachos, Senior Solutions Manager – Modern Workplace, Uni Systems
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...DanBrown980551
Do you want to learn how to model and simulate an electrical network from scratch in under an hour?
Then welcome to this PowSyBl workshop, hosted by Rte, the French Transmission System Operator (TSO)!
During the webinar, you will discover the PowSyBl ecosystem as well as handle and study an electrical network through an interactive Python notebook.
PowSyBl is an open source project hosted by LF Energy, which offers a comprehensive set of features for electrical grid modelling and simulation. Among other advanced features, PowSyBl provides:
- A fully editable and extendable library for grid component modelling;
- Visualization tools to display your network;
- Grid simulation tools, such as power flows, security analyses (with or without remedial actions) and sensitivity analyses;
The framework is mostly written in Java, with a Python binding so that Python developers can access PowSyBl functionalities as well.
What you will learn during the webinar:
- For beginners: discover PowSyBl's functionalities through a quick general presentation and the notebook, without needing any expert coding skills;
- For advanced developers: master the skills to efficiently apply PowSyBl functionalities to your real-world scenarios.
Removing Uninteresting Bytes in Software FuzzingAftab Hussain
Imagine a world where software fuzzing, the process of mutating bytes in test seeds to uncover hidden and erroneous program behaviors, becomes faster and more effective. A lot depends on the initial seeds, which can significantly dictate the trajectory of a fuzzing campaign, particularly in terms of how long it takes to uncover interesting behaviour in your code. We introduce DIAR, a technique designed to speedup fuzzing campaigns by pinpointing and eliminating those uninteresting bytes in the seeds. Picture this: instead of wasting valuable resources on meaningless mutations in large, bloated seeds, DIAR removes the unnecessary bytes, streamlining the entire process.
In this work, we equipped AFL, a popular fuzzer, with DIAR and examined two critical Linux libraries -- Libxml's xmllint, a tool for parsing xml documents, and Binutil's readelf, an essential debugging and security analysis command-line tool used to display detailed information about ELF (Executable and Linkable Format). Our preliminary results show that AFL+DIAR does not only discover new paths more quickly but also achieves higher coverage overall. This work thus showcases how starting with lean and optimized seeds can lead to faster, more comprehensive fuzzing campaigns -- and DIAR helps you find such seeds.
- These are slides of the talk given at IEEE International Conference on Software Testing Verification and Validation Workshop, ICSTW 2022.
Pushing the limits of ePRTC: 100ns holdover for 100 daysAdtran
At WSTS 2024, Alon Stern explored the topic of parametric holdover and explained how recent research findings can be implemented in real-world PNT networks to achieve 100 nanoseconds of accuracy for up to 100 days.
A tale of scale & speed: How the US Navy is enabling software delivery from l...sonjaschweigert1
Rapid and secure feature delivery is a goal across every application team and every branch of the DoD. The Navy’s DevSecOps platform, Party Barge, has achieved:
- Reduction in onboarding time from 5 weeks to 1 day
- Improved developer experience and productivity through actionable findings and reduction of false positives
- Maintenance of superior security standards and inherent policy enforcement with Authorization to Operate (ATO)
Development teams can ship efficiently and ensure applications are cyber ready for Navy Authorizing Officials (AOs). In this webinar, Sigma Defense and Anchore will give attendees a look behind the scenes and demo secure pipeline automation and security artifacts that speed up application ATO and time to production.
We will cover:
- How to remove silos in DevSecOps
- How to build efficient development pipeline roles and component templates
- How to deliver security artifacts that matter for ATO’s (SBOMs, vulnerability reports, and policy evidence)
- How to streamline operations with automated policy checks on container images
How to Get CNIC Information System with Paksim Ga.pptxdanishmna97
Pakdata Cf is a groundbreaking system designed to streamline and facilitate access to CNIC information. This innovative platform leverages advanced technology to provide users with efficient and secure access to their CNIC details.
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AIVladimir Iglovikov, Ph.D.
Presented by Vladimir Iglovikov:
- https://www.linkedin.com/in/iglovikov/
- https://x.com/viglovikov
- https://www.instagram.com/ternaus/
This presentation delves into the journey of Albumentations.ai, a highly successful open-source library for data augmentation.
Created out of a necessity for superior performance in Kaggle competitions, Albumentations has grown to become a widely used tool among data scientists and machine learning practitioners.
This case study covers various aspects, including:
People: The contributors and community that have supported Albumentations.
Metrics: The success indicators such as downloads, daily active users, GitHub stars, and financial contributions.
Challenges: The hurdles in monetizing open-source projects and measuring user engagement.
Development Practices: Best practices for creating, maintaining, and scaling open-source libraries, including code hygiene, CI/CD, and fast iteration.
Community Building: Strategies for making adoption easy, iterating quickly, and fostering a vibrant, engaged community.
Marketing: Both online and offline marketing tactics, focusing on real, impactful interactions and collaborations.
Mental Health: Maintaining balance and not feeling pressured by user demands.
Key insights include the importance of automation, making the adoption process seamless, and leveraging offline interactions for marketing. The presentation also emphasizes the need for continuous small improvements and building a friendly, inclusive community that contributes to the project's growth.
Vladimir Iglovikov brings his extensive experience as a Kaggle Grandmaster, ex-Staff ML Engineer at Lyft, sharing valuable lessons and practical advice for anyone looking to enhance the adoption of their open-source projects.
Explore more about Albumentations and join the community at:
GitHub: https://github.com/albumentations-team/albumentations
Website: https://albumentations.ai/
LinkedIn: https://www.linkedin.com/company/100504475
Twitter: https://x.com/albumentations
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024Neo4j
Neha Bajwa, Vice President of Product Marketing, Neo4j
Join us as we explore breakthrough innovations enabled by interconnected data and AI. Discover firsthand how organizations use relationships in data to uncover contextual insights and solve our most pressing challenges – from optimizing supply chains, detecting fraud, and improving customer experiences to accelerating drug discoveries.
The Art of the Pitch: WordPress Relationships and SalesLaura Byrne
Clients don’t know what they don’t know. What web solutions are right for them? How does WordPress come into the picture? How do you make sure you understand scope and timeline? What do you do if sometime changes?
All these questions and more will be explored as we talk about matching clients’ needs with what your agency offers without pulling teeth or pulling your hair out. Practical tips, and strategies for successful relationship building that leads to closing the deal.
In his public lecture, Christian Timmerer provides insights into the fascinating history of video streaming, starting from its humble beginnings before YouTube to the groundbreaking technologies that now dominate platforms like Netflix and ORF ON. Timmerer also presents provocative contributions of his own that have significantly influenced the industry. He concludes by looking at future challenges and invites the audience to join in a discussion.
Communications Mining Series - Zero to Hero - Session 1DianaGray10
This session provides introduction to UiPath Communication Mining, importance and platform overview. You will acquire a good understand of the phases in Communication Mining as we go over the platform with you. Topics covered:
• Communication Mining Overview
• Why is it important?
• How can it help today’s business and the benefits
• Phases in Communication Mining
• Demo on Platform overview
• Q/A
2. Topics in This Chapter
Manipulating tag body
Assigning dynamic values to tag attributes
Assigning complex objects as values to tag attributes
Creating looping tags
Creating expression language functions
Working with nested custom tags
3. 8.1 Manipulating Tag Body
In Chapter 7 we have seen how to include the body of the tag in
the output of the Java-based custom tag.
To review, there are essentially two things you need to do.
Specify scriptless in the body-content element of the TLD for the tag.
This allows the page author to insert JSP content between the opening and
closing elements of the tag.
Remember that this JSPcontent is not allowed to have any scripting
elements like <% ... %> or <%= ... %>.
Invoke the output of the tag body by calling getJspBody().invoke(null)
inside the doTag method of the tag handler class.
Remember that this statement passes the output of the JSP content to the
client, not the actual JSP code itself.
4. 8.1 Manipulating Tag Body
The invoke method takes a Writer as its argument.
If null is passed to the invoke method, the container
directs the output of the tag body to the JspWriter
object.
The server obtains a reference to this object by calling
methods similar to getJspContext().getOut(). In other
words, the statements getJspBody().invoke(null); and
getJspBody().invoke(getJspContext().getOut());
accomplish exactly the same results.
5. 8.1 Manipulating Tag Body
Pass a different Writer to the invoke method.
Using the new Writer, we can buffer up the output of the JSP content, extract it from
the Writer, manipulate it, and output the new content to the client.
The following are the steps of how this can be accomplished.
Create an instance of a convenient Writer. Any class that inherits from
java.io.Writer class is acceptable. Because the output to the client is usually
HTML, which is just a string, the java.io.String- Writer class is the most
common Writer to use.
For example: StringWriter myWriter = new StringWriter();
Pass the newly created StringWriter as an argument to the invoke method.
For example: getJspBody().invoke(myWriter);
Note that now the output of the tag body is not sent to the client but
buffered up inside myWriter.
Extract the buffered output from the Writer, modify it, and send the
modified version to the client like so:
String modified = modify(myWriter.toString());
getJspContext().getOut().print(modified);
6. 8.2 Example: HTML-Filtering Tag
In this example, we create a custom tag, filterhtml,
that filters out the HTML code, converting it to
regular text, thus preventing the browser from
interpreting it as HTML code. We are now able to see
the actual unrendered HTML code .
We define 3 components as follows,
Tag Handler Class (HtmlFilterTag)
TLD file (csajsp-taglib-adv.tld)
JSP page (html-filter.jsp)
7. 8.2 Example: HTML-Filtering Tag
Tag Handler Class : HtmlFilterTag.java
package coreservlets.tags;
import javax.servlet.jsp.*; import javax.servlet.jsp.tagext.*; import java.io.*;
import coreservlets.ServletUtilities;
public class HtmlFilterTag extends SimpleTagSupport
{
public void doTag() throws JspException, IOException
{
StringWriter stringWriter = new StringWriter();
getJspBody().invoke(stringWriter);
String output =ServletUtilities.filter(stringWriter.toString());
JspWriter out = getJspContext().getOut();
out.print(output);
}
}
8. 8.2 Example: HTML-Filtering Tag
ServletUtilities.java
package coreservlets;
import javax.servlet.*;import javax.servlet.http.*;
public class ServletUtilities {
public static String filter(String input) {
if (!hasSpecialChars(input))
{ return(input); }
StringBuffer filtered = new StringBuffer(input.length());
char c;
for(int i=0; i<input.length(); i++)
{
c = input.charAt(i);
switch(c) {
case '<': filtered.append("<"); break;
case '>': filtered.append(">"); break;
case '"': filtered.append("""); break;
case '&': filtered.append("&"); break;
default: filtered.append(c);
}
}
return(filtered.toString());
}
9. 8.2 Example: HTML-Filtering Tag
private static boolean hasSpecialChars(String input)
{
boolean flag = false;
if ((input != null) && (input.length() > 0))
{ char c;
for(int i=0; i<input.length(); i++)
{
c = input.charAt(i);
switch(c)
{
case '<': flag = true; break;
case '>': flag = true; break;
case '"': flag = true; break;
case '&': flag = true; break;
}
}
}
return(flag);
}
}
10. 8.2 Example: HTML-Filtering Tag
csajsp-taglib-adv.tld
<?xml version="1.0" encoding="UTF-8" ?>
<taglib xmlns=http://java.sun.com/xml/ns/j2ee xmlns:xsi="http://www.w3.org/2001/XMLSchema-
instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-
jsptaglibrary_2_0.xsd"
version="2.0">
<tlib-version>1.0</tlib-version>
<short-name>csajsp-taglib-adv</short-name>
<uri>http://coreservlets.com/csajsp-taglib-adv</uri>
<tag>
<description>Converts special HTML characters to their corresponding HTML character
entities.</description>
<name>filterhtml</name>
<tag-class>coreservlets.tags.HtmlFilterTag</tag-class>
<body-content>scriptless</body-content>
</tag>
</taglib>
13. 8.3 Assigning Dynamic Values to Tag Attributes
In this section, we show you how to change that so the
we can pass dynamic values to our tag.
In other words, we would like to be able to call our
custom tag with a construct like the following:
<prefix:name attribute1="${bean.value}"
attribute2="<%= bean.getValue() %>" />
14. 8.3 Assigning Dynamic Values to Tag Attributes
Dynamic Attribute Values: Tag Handler Class
As far as the tag handler class is concerned, there is no
difference.
You still need to provide a setter method for the attribute in
the form setXxx(String value), where Xxx is the name of
the attribute with the first character capitalized.
public void setAttribute1(String value1)
{
doSomethingWith(value1);
}
15. 8.3 Assigning Dynamic Values to Tag Attributes
Dynamic Attribute Values: Tag Library Descriptor
As before, each attribute needs to be declared inside the TLD.
However, because we want to allow the JSP author to specify dynamic (or
runtime) expressions as values for the attributes, we must specify rtexprvalue to
be true, like in the following:
<tag>
<description>...</description>
<name>mytag</name>
<tag-class>package.TagHandler</tag-class>
<body-content>...</body-content>
<attribute>
<description>...</description>
<name>attribute1</name>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
16. 8.3 Assigning Dynamic Values to Tag Attributes
Dynamic Attribute Values: JSP File
As before, the JSP page has to declare the tag library using
the taglib directive.
Note, however, that this does not mean that only JSP
expressions are allowed to be placed as values for those
attributes. Good old static string values, placed there
during the authoring of the page, are still allowed.
Attributes that accept runtime content are allowed to be
JSP scripting expressions and JSP EL.
<prefix:name attribute1="${bean.value}"
attribute2="<%= bean.getValue() %>" />
17. 8.4 Example: Simple Looping Tag
In this example, we create a simple for loop tag that
outputs its tag body the number of times that the count
attribute specifies.
The count attribute is declared to accept runtime
expressions.
We create the following files,
CoinBean.java ( Bean Class )
SimpleLoopTest.java ( Servlet )
ForTag.java ( Tag Handler Class )
csajsp-taglib-adv.tld ( TLD file )
simple-loop-test.jsp ( JSP file)
18. 8.4 Example: Simple Looping Tag
CoinBean.java ( Bean Class )
package coreservlets;
import java.io.*;
public class CoinBean implements Serializable
{
public String getFlip()
{
if (Math.random() < 0.5)
{return("Heads");}
else
{return("Tails"); }
}
}
19. 8.4 Example: Simple Looping Tag
SimpleLoopTest.java ( Servlet )
package coreservlets;
import java.io.*; import javax.servlet.*; import javax.servlet.http.*;
public class SimpleLoopTest extends HttpServlet
{
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException
{
CoinBean coin = new CoinBean();
request.setAttribute("coin", coin);
RequestDispatcher dispatcher =
request.getRequestDispatcher("/WEB-INF/JSTL/simple-loop-test.jsp");
dispatcher.forward(request, response);
}
}
20. 8.4 Example: Simple Looping Tag
ForTag.java ( Tag Handler Class )
package coreservlets.tags;
import javax.servlet.jsp.*;import javax.servlet.jsp.tagext.*; import java.io.*;
public class ForTag extends SimpleTagSupport
{
private int count;
public void setCount(int count)
{ this.count = count; }
public void doTag() throws JspException, IOException
{
for(int i=0; i<count; i++)
{
getJspBody().invoke(null);
}
}
}
21. 8.4 Example: Simple Looping Tag
csajsp-taglib-adv.tld ( TLD file )
<tag>
<description>Loops specified number of times.</description>
<name>for</name>
<tag-class>coreservlets.tags.ForTag</tag-class>
<body-content>scriptless</body-content>
<attribute>
<description>Number of times to repeat body.</description>
<name>count</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
24. 8.5 Assigning Complex Objects asValues to Tag
Attributes
If we want to pass a Collection of Orders or some other
complex object structure than what would we have to change to
accommodate this, that is discussed in this section.
Complex Dynamic AttributeValues: Tag Handler Class
The type of the argument in the setter would now be the complex object
type instead of String,like the following:
public void setAttribute1(SomeComplexObject value1)
{
doSomethingWith(value1);
}
25. 8.5 Assigning Complex Objects asValues to Tag
Attributes
Complex Dynamic Attribute Values:TLD
The TLD stays the same ,but make sure to provide the
rtexprvalue element with a value of true.
<attribute>
<description>...</description>
<name>attribute1</name>
<rtexprvalue>true</rtexprvalue>
</attribute>
26. 8.5 Assigning Complex Objects asValues to Tag
Attributes
Complex Dynamic Attribute Values: JSP File
As before, the JSP page has to declare the tag library using
the taglib directive.
<%@ taglib uri="..." prefix="..." %>
The usage of the tag is very much the same as when we had
dynamic values that were strings.
<prefix:name attribute1="${bean.value}“
attribute2="<%= bean.getValue() %>" />
27. 8.6 Example: Table Formatting Tag
Complex Dynamic Attribute Values: JSP File
In this example, we list the three most recent swimming
world records.
To list the records, we employ the use of a custom table-
formatting tag that lets the JSP author pass the entire record
set to the tag as a two-dimensional array object.
We create the following files,
WorldRecords.java ( To retrive records)
ShowRecords.java ( Servlet )
MakeTableTag.java ( Tag Handler Class )
csajsp-taglib-adv.tld ( TLD file )
show-records.jsp (JSP file)
29. 8.7 Creating Looping Tags
Consider the following typical Java looping structure. In it, we
use a for loop to iterate through an array of strings.
for (int i; i < someArray.length; i++)
{
System.out.print("Object at position " + i + "is: ");
System.out.print(someArray[i]);
}
The for loop construct exposes the looping index i to its body.
However, no code outside of the for loop body is able to access
i because its scope is limited tothe body of the loop, delimited
by the curly braces.
30. 8.7 Creating Looping Tags
This construct is very useful inside a JSP page as well. In this
case, the looping structure would be the custom tag.
This tag would create some bean with appropriate values and
pass it to the JSP content inside the body of the tag.
This is done inside the doTag method with the use of the tag
body scope attribute.
The tag body scope is similar to the request or application
scope in nature, except that its attributes are only visible to the
tag body.
Any JSP code outside of the custom tag’s beginning and ending
elements would not be able to access it.
You use the following code inside the doTag method to place
an object as an attribute of the tag body scope:
getJspContext().setAttribute(key, object);
31. 8.7 Creating Looping Tags
You then use JSP EL inside the body of the
custom tag to access this attribute.
This is no different than accessing any other
scoped bean.
You just have to remember that this attribute is
not available outside the confines of the tag
body.
<prefix:custom-tag>
some text ${someBean.someValue}
</prefix:custom-tag>
32. 8.7 Creating Looping Tags
When creating a looping tag, it is also very common to provide
the author of the JSP page with an attribute they can set, which
lets them pass the name of the attribute they will later access in
the tag body; that is, let them specify the string value of the key
argument that gets passed into
getJspContext().setAttribute(key, object).
For example:
<mytags:for beanKeyValue="arrayValue" iterateOver="${someArray}">
Value is: ${arrayValue}
</mytags:for>
33. 8.8 Example: ForEach Tag
In this example, we create a forEach custom tag that
can iterate over arrays of any objects.
foreach tag has two attributes,
Item :- The array of elements.
var :- The name of the scoped variable to which each entry
is assigned.
We create the following files,
LoopTest.java (servlet)
ForEachTag.java (Tag Handler Class)
csajsp-taglib-foreach.tld (TLD file)
loop-test.jsp (JSP file)
39. 8.9 Creating Expression Language Functions
In the Example: Debug Tag, we have created a debug
tag.
This simple tag surrounds some debugging
information inside the JSP page.
If the debug request parameter is present, the
contents of the debug tag are allowed to be processed
and output to the JSP page.
40. 8.9 Creating Expression Language Functions
There is, however, one limitation to our debug tag. As with
all custom tags based on the SimpleTag API, the body of the
tag is not allowed to contain any JSP scripting.
The only way we can output something is through JSP
EL,which requires that the object has bean-like getter methods.
We can create such a bean in the doTag method of the debug tag
handler class, but this would require us to update the tag handler class
code every time we need to output some new debugging information or
modify the current output.
Furthermore, we would like to reuse the same debug tag on multiple
JSP pages. Placing the information we want to see for one page into the
tag handler class would require us to create multiple debug tags for
different JSP pages.
41. 8.9 Creating Expression Language Functions
There are two sensible solutions to this problem,
Usage of nested custom tags
Use an EL function
ELfunctions are a new feature to the JSP specification 2.0.
EL functions allow the developer to call a static method inside
the JSP page, but instead of using JSP scripting to do it, which
is illegal inside the tag body, EL functions allow the developer
touse EL notation to invoke the function.
Inside the JSP page, an EL function invocationwould look like
the following:
${prefix:someFunction(package.ClassName argument)}
42. 8.9 Creating Expression Language Functions
The steps for creating an EL function
1. Create a class with a public static method.
2. Declare the method inside a TLD file.
3. Declare tag library inside the JSP page.
4. Use JSP EL to invoke the method.
43. 8.9 Creating Expression Language Functions
1. Create a class with a public static method
This class should be placed into the WEB-INF/classes
directory.
public class SomeClass
{
public static void someMethod() {...}
}
44. 8.9 Creating Expression Language Functions
2. Declare the method inside a TLD file.
The fully qualified class name and one of its methods gets mapped to
some name that will be used inside the JSP page to invoke that method.
However, instead of the tag element, which declares a tag, EL
functions use the function element and its related elements as follows:
<function>
<name>run</name>
<function-class>somePackage.SomeClass</function-class>
<function-signature>void someMethod()</function-signature>
</function>
The value of the function-signature element should contain the
signature of the method with all the specified types using their fully
qualified class notation.
<function-signature>
void someMethod(java.lang.String)
</function-signature>
45. 8.9 Creating Expression Language Functions
3. Declare tag library inside the JSP page.
This step is identical to declaring a TLD that contains
declarations of custom tags exclusively.
Just like before you use the taglib directive, assign a prefix
to be used throughout the JSP page. For example:
<%@ taglib prefix="myfunc" uri="someURI" %>
46. 8.9 Creating Expression Language Functions
4. Use JSP EL to invoke the method.
The invocation of the method is done in the following form:
${myfunc:run()}
The myfunc part is the prefix that comes from the taglib
declaration mentioned in Step 3.
The run part comes from the name element inside the
function element declaration in the TLD.
Note that the function name used inside the JSP page does
not have to be the same as the method name inside the
implementing class.
47. 8.10 Handling Nested Custom Tags
So far we have seen custom tags whose bodies
contained ordinary JSP content.
However, the tag body of a custom tag can also
contain other custom tags, as follows:
<prefix:tagOuter>
<prefix:tagInner>
...
</prefix:tagInner>
</prefix:tagOuter>
48. 8.10 Handling Nested Custom Tags
The SimpleTag API provides two methods that let an
inner tag get a hold of the outer tag.
The first method is getParent().
It is called on the instance of the inner tag.
It returns an object of type JspTag, which can be cast to the type of
the outer tag’s handler class. If this method is called on the most
outer tag in the hierarchy, it returns null.
Although you can keep calling the getParent method over and over
until you either reach the tag instance you are seeking or null.
49. 8.10 Handling Nested Custom Tags
The second method is
findAncestorWithClass(JspTag fromTag, Class
toBeMatchedClass)
This method starts searching the hierarchy of tags from a given tag
instance, fromTag, looking at its parent tag up until it finds a tag
instance that matches the type of toBeMatchedClass.
If the search takes it all the way to the top of the hierarchy with no
results, it returns null.
If this method finds the right instance of the tag class, it returns it
as a JspTag instance, which needs to be cast to the proper type.
Note :- With the getParent method, you need to
anticipate a ClassCastException because you don’t
know the parent tag’s type in advance.