For now, jsp is often used to create screens. To some extent, JSP custom tags may be required. This article explains how to easily create a JSP custom tag.
In this article, we will develop JSP custom tags based on the web project. It also summarizes a little knowledge about JSP custom tags.
-** SimpleTagSupport class : A class that implements the interface SimpleTag. It is often used as a parent class when developing JSP custom tags. - doTag () method : Override this method to realize the actual business logic. - tld file **: Where to define information such as tag names, tag attributes, and tag classes for JSP custom tags.
This article creates a custom tag called ** \ <hyman: hello name = ""> **. The tag name is hello and the tag attribute is name. If you use this tag, the value of name will be included in the output on the screen.
Simply put, create a new java class that inherits from the parent SimpleTagSupport class and implements the doTag method. The source code is as follows.
HymanTag.java
package tag;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.SimpleTagSupport;
public class HymanTag extends SimpleTagSupport {
private String name;
@Override
public void doTag() throws JspException {
try {
getJspContext().getOut().println("Hello, " + name);
} catch (Exception e) {
throw new JspException(e);
}
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Fill in the tag name, attributes, class and other information as shown below. Then store the hyman.tld file under the / webapps / WEB-INF directory. ** Example: /webapps/WEB-INF/hyman.tld **
hyman.tld
<?xml version="1.0" encoding="UTF-8" ?>
<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>2.0</jsp-version>
<short-name>Example TLD</short-name>
<tag>
<name>hello</name>
<tag-class>tag.HymanTag</tag-class>
<body-content>empty</body-content>
<info>Hello tag with parameters.</info>
<attribute>
<name>name</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
</taglib>
Assumption: Store the hyman.tld file under the / webapps / WEB-INF directory. ** Example: /webapps/WEB-INF/hyman.tld **
First, create a jsp file, install the JSP custom tag, and use it. Introduction:
<%@ taglib prefix="hyman" uri="/WEB-INF/hyman.tld"%>
The source code of jsp is as follows.
index.jsp
<%@page pageEncoding="UTF-8"%>
<%@ taglib prefix="hyman" uri="/WEB-INF/hyman.tld"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Easy way to create JSP custom tags</title>
</head>
<body>
<h2 style="color:red;">
<hyman:hello name="hyman's custom tag"/>
</h2>
</body>
</html>
So far, all the implementation of JSP custom tags is completed, let's start the project and check it on the screen. The image should look like this:
Thank you for reading to the end. Please do not hesitate to point out any parts that you think are strange. Thank you.
Recommended Posts