Untitled
unknown
plain_text
2 years ago
2.3 kB
3
Indexable
Demo tag Lib Đầu tiên khởi tạo xml: <taglib xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_1.xsd" version="2.1"> <tlib-version>1.0</tlib-version> <short-name>message-taglib</short-name> <uri>http://example.com/message-taglib</uri> <tag> <name>message</name> <tag-class>com.example.MessageTagHandler</tag-class> <body-content>empty</body-content> </tag> </taglib> Trong tệp tin mô tả thư viện thẻ này ta định nghĩa một thẻ tùy chỉnh có tên là "message". Thẻ này có một lớp xử lý tên là "com.example.MessageTagHandler" và kiểu nội dung body-content là "empty". Tiếp theo cần tạo một lớp xử lý (com.example.MessageTagHandler) để xử lý thẻ "message". package com.example; import javax.servlet.jsp.JspException; import javax.servlet.jsp.tagext.SimpleTagSupport; import java.io.IOException; public class MessageTagHandler extends SimpleTagSupport { @Override public void doTag() throws JspException, IOException { getJspContext().getOut().write("This is a custom message from the message tag."); } } Lớp xử lý kế thừa từ SimpleTagSupport và ghi đè phương thức doTag(). Trong phương thức này, ta sử dụng getJspContext().getOut().write() để ghi thông báo tùy chỉnh lên trang JSP. Tiếp theo, ta cần tham chiếu đến thư viện thẻ trong trang JSP của ta. Chèn chỉ thị <%@ taglib %> vào đầu trang JSP : <%@ taglib uri="http://example.com/message-taglib" prefix="msg" %> Trong ví dụ này, chúng ta đang tham chiếu đến thư viện thẻ với URI "http://example.com/message-taglib" và tiền tố "msg". Bây giờ, ta có thể sử dụng thẻ tùy chỉnh từ thư viện thẻ trong trang JSP của ta. Ví dụ, để hiển thị thông báo, ta có thể viết mã như sau: <msg:message/> Trong ví dụ trên, chúng ta sử dụng thẻ "message" từ thư viện thẻ được gán nhãn "msg". Khi trang JSP được hiển thị, thông báo "This is a custom message from the message tag." sẽ được hiển thị.
Editor is loading...