Panduan ke Perpustakaan JSTL

1. Ikhtisar

JavaServer Pages Tag Library (JSTL) adalah sekumpulan tag yang dapat digunakan untuk mengimplementasikan beberapa operasi umum seperti perulangan, pemformatan bersyarat, dan lainnya.

Dalam tutorial ini, kita akan membahas bagaimana mengatur JSTL dan bagaimana menggunakan banyak tagnya.

2. Penyiapan

Untuk mengaktifkan fitur JSTL, kami harus menambahkan pustaka ke proyek kami. Untuk proyek Maven, kami menambahkan ketergantungan di file pom.xml :

 javax.servlet jstl 1.2 

Dengan pustaka yang ditambahkan ke proyek kami, penyiapan terakhir adalah menambahkan tag JSTL inti dan file namespace tag lainnya ke JSP kami menggunakan direktif taglib seperti ini:

Selanjutnya, kita akan melihat tag ini yang dikelompokkan ke dalam lima kategori.

3. Tag Inti

Pustaka tag inti JSTL berisi tag untuk melakukan operasi dasar seperti nilai pencetakan, deklarasi variabel, penanganan pengecualian, melakukan iterasi, dan mendeklarasikan pernyataan bersyarat antara lain.

Mari kita lihat tag inti.

3.1. Itu Menandai

digunakan untuk menampilkan nilai yang terkandung dalam variabel atau hasil ekspresi implisit.

Ini memiliki tiga atribut: nilai, default, dan escapeXML. The escapeXML atribut output tag XML mentah yang terkandung dalam nilai atribut atau kandang.

Contoh dari tag akan menjadi:

3.2. Itu Menandai

Itutag digunakan untuk mendeklarasikan variabel cakupan di JSP. Kita juga bisa mendeklarasikan nama variabel dan nilainya masing-masing di atribut var dan value .

Contoh akan berbentuk:

3.3. Itu Menandai

Itutag menghapus variabel cakupan yang setara dengan menetapkan null ke variabel. Dibutuhkan atribut var dan scope dengan cakupan yang memiliki nilai default untuk semua cakupan.

Di bawah ini, kami menunjukkan contoh penggunaan menandai:

3.4. Itu Menandai

Itutag menangkap pengecualian apa pun yang dilemparkan ke dalam kandangnya. Jika pengecualian dilemparkan, nilainya disimpan dalam atribut var dari tag ini.

Penggunaan biasa akan terlihat seperti:

Dan untuk memeriksa apakah pengecualian dilempar, kami menggunakan tag seperti yang ditunjukkan di bawah ini:

The exception is : ${exceptionThrown}

There is an exception: ${exceptionThrown.message}

3.5. Itu Menandai

Ituadalah tag bersyarat yang menampilkan atau mengeksekusi scriptlet yang diapit olehnya hanya jika atribut pengujiannya bernilai true. Hasil evaluasi dapat disimpan dalam atribut var -nya .

3.6. , dan Tag

Itu adalah tag induk yang digunakan dalam melakukan ekspresi switch-like atau if-else. Ini memiliki dua sub tag;dan yang masing-masing mewakili if / else-if dan else.

mengambil atribut uji yang menampung ekspresi untuk dievaluasi. Di bawah ini, kami menunjukkan contoh penggunaan tag ini:


    

3.7. Itu Menandai

Itu tag menangani pengambilan dan pemaparan konten dari URL absolut atau relatif.

Kita dapat menggunakan atribut url dan var untuk menampung URL, dan konten diambil dari URL masing-masing. Misalnya, kita dapat mengimpor konten dari URL dengan:

3.8. Itu Menandai

Itu Tag ini mirip dengan sintaks for, while atau do-while pada Java. The item atribut memegang daftar barang yang akan mengulangi lebih, sementara mulai dan akhir atribut memegang mulai dan berakhir indeks masing-masing (nol pengindeksan).

tag juga memiliki atribut langkah yang mengontrol ukuran kenaikan indeks setelah setiap iterasi. Di bawah ini, kami menunjukkan contoh penggunaan:

 Item 

3.9. Itu Menandai

Itu tag digunakan untuk memisahkan String menjadi token dan mengulanginya.

Mirip dengan tag, ia memiliki item atribut dan tambahan delim atribut yang merupakan pembatas untuk String seperti ini:

3.10. dan Tag

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