Panduan untuk Perpustakaan JSTL

1. Gambaran keseluruhan

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

Dalam tutorial ini, kita akan membincangkan cara menyiapkan JSTL dan bagaimana menggunakan banyak tagnya.

2. Persediaan

Untuk mengaktifkan ciri JSTL, kami harus menambahkan perpustakaan ke projek kami. Untuk projek Maven, kami menambahkan kebergantungan dalam fail pom.xml :

 javax.servlet jstl 1.2 

Dengan perpustakaan yang ditambahkan ke projek kami, persediaan terakhir adalah dengan menambahkan tag JSTL teras dan fail ruang nama tag lain ke JSP kami menggunakan arahan taglib seperti ini:

Seterusnya, kita akan melihat tanda-tanda ini yang secara umum dikelompokkan menjadi lima kategori.

3. Tag Teras

Pustaka tag inti JSTL mengandungi tag untuk melakukan operasi asas seperti nilai percetakan, deklarasi pemboleh ubah, pengendalian pengecualian, melakukan lelaran, dan menyatakan pernyataan bersyarat antara lain.

Mari kita lihat pada tag inti.

3.1. The Tag

digunakan untuk menampilkan nilai yang terdapat dalam pemboleh ubah atau hasil ekspresi tersirat.

Ia mempunyai tiga atribut: nilai, lalai, dan escapeXML. The escapeXML atribut output tag XML mentah yang terkandung dalam nilai atribut atau kandang.

Contoh mengenai teg akan:

3.2. The Tag

Thetag digunakan untuk menyatakan pemboleh ubah skop dalam JSP. Kami juga dapat menyatakan nama pemboleh ubah dan nilainya dalam atribut var dan nilai masing-masing.

Contohnya adalah seperti:

3.3. The Tag

Thetag membuang pembolehubah skop yang setara dengan menetapkan nol kepada pemboleh ubah. Ia memerlukan atribut var dan lingkup dengan skop yang mempunyai nilai lalai dari semua ruang lingkup.

Di bawah ini, kami menunjukkan contoh penggunaan teg:

3.4. The Tag

Thetag menangkap sebarang pengecualian yang dilemparkan dalam kandangnya Sekiranya pengecualian dilemparkan, nilainya disimpan dalam atribut var tag ini.

Penggunaan biasa mungkin seperti:

Dan untuk memeriksa apakah pengecualian dilemparkan, kami menggunakan tag seperti gambar di bawah:

The exception is : ${exceptionThrown}

There is an exception: ${exceptionThrown.message}

3.5. The Tag

Theadalah tag bersyarat yang memaparkan atau melaksanakan skrip yang dilampirkan hanya apabila atribut ujiannya dinilai menjadi benar. Hasil penilaian dapat disimpan dalam atribut varnya .

3.6. , dan Teg

The adalah teg induk yang digunakan dalam melakukan ungkapan seperti suis atau jika-lain Ia mempunyai dua subteg;dan yang mewakili jika / lain-jika dan yang lain masing-masing.

mengambil atribut ujian yang menahan ungkapan yang akan dinilai. Di bawah ini, kami menunjukkan contoh penggunaan tag ini:


    

3.7. The Tag

The tag menangani pengambilan dan pendedahan kandungan dari URL mutlak atau relatif.

Kami dapat menggunakan atribut url dan var untuk menahan URL, dan kandungan yang diambil dari URL masing-masing. Sebagai contoh, kami dapat mengimport kandungan dari URL dengan:

3.8. The Tag

The tag serupa dengan sintaks Java untuk, sementara atau do-while. The barangan atribut memegang senarai barangan yang hendak mengulangi lebih, sementara mula dan akhir sifat-sifat tahan bermula dan masing-masing berakhir indeks (sifar pengindeksan) itu.

tag juga mempunyai atribut step yang mengawal ukuran kenaikan indeks setelah setiap lelaran. Di bawah ini, kami menunjukkan contoh penggunaan:

 Item 

3.9. The Tag

The tag digunakan untuk membagi String menjadi token dan berulang melalui mereka.

Sama seperti tag, ia mempunyai atribut item dan atribut delim tambahan yang merupakan pembatas bagi String seperti ini:

3.10. dan Teg

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