Un guide de la bibliothèque JSTL

1. Vue d'ensemble

La bibliothèque de balises JavaServer Pages (JSTL) est un ensemble de balises qui peuvent être utilisées pour implémenter certaines opérations courantes telles que la mise en boucle, la mise en forme conditionnelle, etc.

Dans ce didacticiel, nous discuterons de la configuration de JSTL et de l'utilisation de ses nombreuses balises.

2. Configuration

Pour activer les fonctionnalités JSTL, nous devrons ajouter la bibliothèque à notre projet. Pour un projet Maven, nous ajoutons la dépendance dans le fichier pom.xml :

 javax.servlet jstl 1.2 

Avec la bibliothèque ajoutée à notre projet, la configuration finale consistera à ajouter la balise JSTL principale et le fichier d'espace de noms des autres balises à notre JSP en utilisant la directive taglib comme ceci:

Ensuite, nous examinerons ces balises qui sont globalement regroupées en cinq catégories.

3. Balises principales

La bibliothèque de balises de base JSTL contient des balises pour effectuer des opérations de base telles que l'impression de valeurs, la déclaration de variables, la gestion des exceptions, l'exécution d'itérations et la déclaration d'instructions conditionnelles, entre autres.

Jetons un coup d'œil aux balises principales.

3.1. le Marque

est utilisé pour afficher les valeurs contenues dans les variables ou le résultat d'une expression implicite.

Il a trois attributs: value, default et escapeXML. L' attribut escapeXML génère des balises XML brutes contenues dans l' attribut value ou son boîtier.

Un exemple de la balise sera:

3.2. le Marque

leLa balise est utilisée pour déclarer des variables de portée dans JSP. Nous pouvons également déclarer le nom de la variable et sa valeur dans les attributs var et value respectivement.

Un exemple sera de la forme:

3.3. le Marque

leLa balise supprime les variables de portée, ce qui équivaut à affecter null à une variable. Il prend les attributs var et scope avec une portée ayant une valeur par défaut de toutes les étendues.

Ci-dessous, nous montrons un exemple d'utilisation de marque:

3.4. le Marque

letag intercepte toute exception lancée dans son enclos. Si l'exception est levée, sa valeur est stockée dans l' attribut var de cette balise.

L'utilisation typique pourrait ressembler à:

Et pour vérifier si l'exception est levée, nous utilisons le étiquette comme indiqué ci-dessous:

The exception is : ${exceptionThrown}

There is an exception: ${exceptionThrown.message}

3.5. le Marque

leest une balise conditionnelle qui affiche ou exécute ses scriptlets inclus uniquement lorsque son attribut de test est évalué à true. Le résultat de l'évaluation peut être stocké dans son attribut var .

3.6. , et Mots clés

le est une balise parent utilisée pour exécuter des expressions de type switch ou if-else. Il a deux sous-étiquettes;et qui représentent respectivement if / else-if et else.

prend un attribut de test qui contient l'expression à évaluer. Ci-dessous, nous montrons un exemple d'utilisation de ces balises:


    

3.7. le Marque

le La balise gère la récupération et l'exposition du contenu à partir d'URL absolues ou relatives.

Nous pouvons utiliser les attributs url et var pour contenir respectivement l'URL et le contenu extrait de l'URL. Par exemple, nous pourrions importer le contenu d'une URL en:

3.8. le Marque

le La balise est similaire à la syntaxe Java for, while ou do-while. L' attribut items contient la liste des éléments à parcourir, tandis que les attributs de début et de fin contiennent respectivement l'index de début et de fin (indexation nulle).

La balise a également un attribut step qui contrôle la taille de l'incrément d'index après chaque itération. Ci-dessous, nous montrons un exemple d'utilisation:

 Item 

3.9. le Marque

le La balise est utilisée pour diviser une chaîne en jetons et les parcourir.

Semblable à tag, il a un attribut items et un attribut delim supplémentaire qui est le délimiteur pour la chaîne comme ceci:

3.10. et Mots clés

le tag is useful for formatting a URL with proper request encoding. the formatted URL is stored in the var attribute.

tag also has a subtag which is used for specifying URL parameters. We show an example below:

3.11. The Tag

The tag performs a URL rewrite and redirects the user to the page specified in its url attribute. A typical use case will look like this:

4. Formatting Tags

JSTL formatting tag library provides a convenient way for formatting text, numbers, dates, times and other variables for better display.

JSTL formatting tags can also be used to enhance the internationalization of a website.

Before using these formatting tags, we've to add the taglib to our JSP:

Let's identify the various formatting tags and how they can be used.

4.1. The Tag

The tag is useful in formatting dates or time. The value attribute holds the date to be formatted, and the type attribute takes one of three values; date, time or both.

also has a pattern attribute where we can specify the desired formatting pattern. Below is an example of one of the patterns:


    

4.2. The Tag

The tag is similar to tag.

The difference is that with tag we can specify the formatting pattern that the underlying date parser should expect the date value to be in.

We can parse dates:

4.3. The Tag

The tag handles rendering of numbers in a specific pattern or precision which can be one of number, currency or percentage as specified in its type attribute. An example usage of would be:

4.4. The Tag

The tag is similar to tag. The difference is that with tag we can specify the formatting pattern that the underlying number parser should expect the number to be in.

We could use this like:

4.5. The Tag

The tag is a parent tag for tag. makes the bundle specified in its basename attribute to the enclosed tags.

tag is useful for enabling internationalization as we can specify locale-specific objects. Typical usage will be of the form:

4.6. The Tag

The tag is used for loading a resource bundle within JSP and making it available through the entire page. The loaded resource bundle is stored in the var attribute of the tag. We can set bundle by:

4.7. The Tag

The tag is used to set the locale for the sections in JSP placed after it's declaration. Typically we will set this by:

fr_FR represents the locale which is French in this case.

4.8. The Tag

The tag is a parent tag that specifies the time zone to be used by any time formatting or parsing actions by tags in its enclosure.

This time zone parameter is supplied by its value attribute. An example usage is shown below:

4.9. The Tag

The tag can be used to copy the time zone specified in its value attribute to a scoped variable specified in its var attribute. We define this by:

4.10. The Tag

The > tag is used to display internationalization message. The unique identifier for the message to be retrieved should be passed to its key attribute.

A specific bundle to lookup the message which can also be specified through the bundle attribute.

This may look like this:

4.11. The Tag

The tag is useful in specifying the encoding type for forms with an action type of post.

The name of the character encoding to use is supplied through the key attribute of the tag.

Let's see an example below:

5. XML Tags

JSTL XML tag library provides convenient ways for interacting with XML data within a JSP.

To be able to access these XML tags, we'd add the tag library to our JSP by:

Let's look at the different tags in the JSTL XML tags library.

5.1. The Tag

The tag is similar to scriptlet tag in JSP but is specifically used for XPath expressions.

tag has a select and escapeXML attributes used for specifying the XPath expression to evaluate a String and to enable escaping of special XML characters respectively.

A simple example is:

$output in the above refers to a preloaded XSL file.

5.2. The Tag

The tag is used for parsing the XML data specified in its xml or doc attribute or enclosure. A typical example would be:

5.3. The Tag

The tag sets the variable specified in its var attribute to the evaluated XPath expression passed to its select attribute. A typical example would be:

5.4. The Tag

The tag processes its body if the XPath expression supplied to its select attribute evaluates to true.

The result of the evaluation can be stored in its var attribute.

A simple use case will look like:

 Document has at least one element. 

5.5. The Tag

The tag is used for looping over nodes in an XML document. The XML document is supplied through tag's select attribute.

Just like the core tag, tag has begin, end and step attributes.

Thus, we'd have:


     
  • Item Name:

5.6. , and Tags

The tag is a parent tag that is used in performing switch-like or if/else-if/else expressions and has no attributes but encloses and tags.

tag is similar if/else-if and takes a select attribute which holds the expression to be evaluated.

tag is similar to else/default clause and has no attribute.

Below, we show a sample use case:

 Item category is Sneakers Item category is Heels Unknown category. 

5.7. and Tags

The tag transforms an XML document within JSP by applying an eXtensible Stylesheet Language (XSL) to it.

The XML document or String to be transformed is supplied to the doc attribute while the XSL to be applied is passed to the xslt attribute of the tag.

tag is a subtag of tag and it is used to set a parameter in the transformation stylesheet.

A simple use case will be of the form:

6. SQL Tags

JSTL SQL tag library provides tags for performing relational database operations.

To enable JSTL SQL tags, we add the taglib to our JSP:

JSTL SQL tags support different databases including MySQL, Oracle and Microsoft SQL Server.

Next, we'll look at the different SQL tags available.

6.1. The Tag

The tag is used for defining the JDBC configuration variables.

These configuration variables are held in the driver, url, user, password and dataSource attributes of the tag as shown below:

In the above, the var attribute holds a value that identifies the associated database.

6.2. The Tag

The tag is used to execute an SQL SELECT statement with the result stored in a scoped variable defined in its var attribute. Typically, we'd define this as:

 SELECT * from USERS; 

tag's sql attribute holds the SQL command to be executed. Other attributes include maxRows, startRow, and dataSource.

6.3. The Tag

The tag is similar to tag but executes only SQL INSERT, UPDATE or DELETE operations which do not require a return value.

An example usage would be:

 INSERT INTO USERS(first_name, last_name, email) VALUES ('Grace', 'Adams', '[email protected]'); 

tag's var attribute holds the number of rows that were affected by the SQL statement specified in its sql attribute.

6.4. The Tag

The tag is a sub tag that can be used within or tag to supply a value for a value placeholder in the sql statement as this:

 DELETE FROM USERS WHERE email = ? 
     

tag has a single attribute; value which holds the value to be supplied.

6.5. The Tag

The tag is used within or tag to supply a date and time value for a value placeholder in the sql statement.

We can define this in our JSP like this:

 UPDATE Users SET registered = ? WHERE email = ? 
     
     

Like the tag, tag has a value attribute with an additional type attribute whose value can be one of date, time or timestamp (date and time).

6.6. The Tag

The tag is used to create JDBC transaction-like operation by grouping and tags together like this:

 UPDATE Users SET first_name = 'Patrick-Ellis' WHERE email="[email protected]" UPDATE Users SET last_name = 'Nelson' WHERE email ='[email protected]' INSERT INTO Users(first_name, last_name, email) VALUES ('Grace', 'Adams', '[email protected]'); 

tag ensures that all database operations are processed successfully (committed) or all fail gracefully (rolled back) if an error occurs in any of the operations.

7. JSTL Functions

JSTL methods are utilities for data manipulation within JSP. While some functions take different data types, most of them are dedicated for String manipulation.

To enable JSTL methods in JSP, we'd add the taglib to our page:

Let's look at these functions and how to use them.

7.1. fn:contains() and fn:containsIgnoreCase()

The fn:contains() method evaluates a String to check if it contains a given substring like this:

Found 'first' in string

The fn:contains() function takes two String arguments; the first is the source String and the second argument is the substring. It returns a boolean depending on the result of the evaluation.

The fn:containsIgnoreCase() function is a case-insensitive variant of the fn:contains() method and can be used like this:

Found 'first' string

Found 'FIRST' string

7.3. The fn:endsWith() Function

The fn:endsWith() function evaluates a String to check if its suffix matches another substring. It takes two arguments; the first argument is the String whose suffix is to be tested while the second argument is the tested suffix.

We can define this like:

String ends with 'string'

7.4. The fn:escapeXml() Function

The fn:escapeXML() function is used to escape XML markup in the input String like this:

${fn:escapeXml(string1)}

7.5. The fn:indexOf() Function

The fn:indexOf() function looks through a String and returns the index of the first occurrence of a given substring.

It takes two arguments; the first is the source String and the second argument is the substring to match and return the first occurrence.

fn:indexOf() function returns an integer and can be used like:

Index: ${fn:indexOf(string1, "first")}

7.6. The fn:join() Function

The fn:join() function concatenates all elements of an array into a single String and can be used like this:

7.7. The fn:length() Function

The fn:length() function returns the number of elements in the given collection or the number of characters in the given String.

The fn:length() function takes a single Object which can either be a collection or a String and returns an integer like this:

Length: ${fn:length(string1)}

7.8. The fn:replace() Function

The fn:replace() function replaces all occurrences of a substring in a String with another String.

It takes three arguments; the source String, the substring to lookup in the source and the String to replace all occurrences of the substring just like this:

7.9. The fn:split() Function

The fn:split() function performs split operation on a String using the specified delimiter. Here is an example usage:

7.10. The fn:startsWith() Function

The fn:startsWith() function checks the prefix of a String and returns true if it matches a given substring like this:

String starts with 'This'

7.11. The fn:substring() Function

The fn:substring() function creates a substring from a source String at the starting and ending indices specified. We'd use it like this:

7.12. The fn:substringAfter() Function

The fn:substringAfter() function checks a source String for a given substring and returns the String immediately after the first occurrence of the specified substring.

We'd use it like this:

7.13. The fn:substringBefore() Function

The fn:substringBefore() function checks a source String for a given substring and returns the String just before the first occurrence of the specified substring.

In our JSP page, it'll look like this:

7.14. The fn:toLowerCase() Function

The fn:to LowerCase() function transforms all characters in a String to lowercase and can be used like this:

7.15. The fn:toUpperCase() Function

The fn:toUpperCase() function transforms all characters in a String to uppercase:

7.16. The fn:trim() Function

The fn:trim() function removes preceding and trailing whitespaces in a String:

9. Conclusion

In this extensive article, we've looked at the various JSTL tags and how to use them.

As usual, code snippets can be found over on GitHub.