Una guida alla libreria JSTL

1. Panoramica

JavaServer Pages Tag Library (JSTL) è un insieme di tag che possono essere utilizzati per implementare alcune operazioni comuni come il ciclo, la formattazione condizionale e altre.

In questo tutorial, discuteremo come configurare JSTL e come utilizzare i suoi numerosi tag.

2. Configurazione

Per abilitare le funzionalità JSTL, dovremmo aggiungere la libreria al nostro progetto. Per un progetto Maven, aggiungiamo la dipendenza nel file pom.xml :

 javax.servlet jstl 1.2 

Con la libreria aggiunta al nostro progetto, la configurazione finale sarà quella di aggiungere il tag JSTL principale e qualsiasi altro file dello spazio dei nomi dei tag al nostro JSP utilizzando la direttiva taglib in questo modo:

Successivamente, daremo un'occhiata a questi tag che sono ampiamente raggruppati in cinque categorie.

3. Tag principali

La libreria di tag di base JSTL contiene tag per eseguire operazioni di base come la stampa di valori, la dichiarazione di variabili, la gestione delle eccezioni, l'esecuzione di iterazioni e la dichiarazione di istruzioni condizionali tra le altre.

Diamo un'occhiata ai tag principali.

3.1. Il Etichetta

viene utilizzato per visualizzare i valori contenuti nelle variabili o il risultato di un'espressione implicita.

Ha tre attributi: value, default e escapeXML. L' attributo escapeXML restituisce tag XML non elaborati contenuti nell'attributo value o nel suo allegato.

Un esempio di tag sarà:

3.2. Il Etichetta

Iltag viene utilizzato per dichiarare le variabili con ambito in JSP. Possiamo anche dichiarare il nome della variabile e il suo valore rispettivamente negli attributi var e value .

Un esempio sarà della forma:

3.3. Il Etichetta

Iltag rimuove le variabili con ambito che è equivalente all'assegnazione di null a una variabile. Richiede l' attributo var e scope con scope con un valore predefinito di tutti gli ambiti.

Di seguito, mostriamo un esempio di utilizzo di etichetta:

3.4. Il Etichetta

Iltag cattura qualsiasi eccezione generata all'interno del suo contenitore. Se viene generata l'eccezione, il suo valore viene memorizzato nell'attributo var di questo tag.

L'utilizzo tipico potrebbe essere simile a:

E per verificare se viene generata l'eccezione, usiamo il tag come mostrato di seguito:

The exception is : ${exceptionThrown}

There is an exception: ${exceptionThrown.message}

3.5. Il Etichetta

Ilè un tag condizionale che visualizza o esegue i suoi scriptlet racchiusi solo quando il suo attributo di test restituisce true. Il risultato della valutazione può essere memorizzato nel suo attributo var .

3.6. , e Tag

Il è un tag genitore utilizzato per eseguire espressioni simili a switch o if-else. Ha due sottotag;e che rappresentano rispettivamente if / else-if e else.

accetta un attributo di test che contiene l'espressione da valutare. Di seguito, mostriamo un esempio di utilizzo di questi tag:


    

3.7. Il Etichetta

Il tag gestisce il recupero e l'esposizione di contenuti da URL assoluti o relativi.

Possiamo utilizzare gli attributi url e var per contenere rispettivamente l'URL e il contenuto recuperato dall'URL. Ad esempio, potremmo importare contenuti da un URL:

3.8. Il Etichetta

Il tag è simile alla sintassi for, while o do-while di Java. L' attributo items contiene l'elenco degli elementi su cui eseguire l'iterazione, mentre gli attributi di inizio e di fine contengono rispettivamente l'indice iniziale e finale (indicizzazione zero).

tag ha anche un attributo step che controlla la dimensione dell'incremento dell'indice dopo ogni iterazione. Di seguito, mostriamo un esempio di utilizzo:

 Item 

3.9. Il Etichetta

Il tag viene utilizzato per dividere una stringa in token e iterare attraverso di essi.

Simile a tag, ha un attributo items e un attributo delim aggiuntivo che è il delimitatore per la String come questo:

3.10. e Tag

Il 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.