自定义标签的使用jsp实例_JSP自定义标签示例教程

自定义标签的使用jsp实例

Today we will look into JSP custom tags. Earlier we learned about JSP Action Elements, JSP EL and JSTL to avoid scripting elements in JSP pages. But sometimes even these are not enough and we might get tempted to write java code to perform some operations in JSP page. Fortunately JSP is extendable and we can create our own custom tags to perform certain operations.

今天,我们将研究JSP定制标记。 先前我们了解了JSP Action ElementsJSP ELJSTL,以避免在JSP页面中编写脚本元素。 但是有时甚至这些还不够,我们可能很想编写Java代码以在JSP页面中执行一些操作。 幸运的是,JSP是可扩展的,我们可以创建自己的自定义标签来执行某些操作。

JSP中的自定义标签 (Custom Tags in JSP)

Let’s say we want to show a number with formatting with commas and spaces. This can be very useful for user when the number is really long. So we want some custom tags like below:

假设我们要显示带有逗号和空格格式的数字。 当数字非常长时,这对用户非常有用。 所以我们想要一些自定义标签,如下所示:

<mytags:formatNumber number="100050.574" format="#,###.00"/>

<mytags:formatNumber number="100050.574" format="#,###.00"/>

Based on the number and format passed, it should write the formatted number in JSP page, for above example it should print 100,050.57

根据传递的数字和格式,它应该在JSP页面中写入格式化的数字,例如,上面的示例应该打印100,050.57

We know that JSTL doesn’t provide any inbuilt tags to achieve this, so we will create our own custom tag implementation and use it in the JSP page. Below will be the final structure of our example project.

我们知道JSTL不提供任何内置标签来实现此目的,因此我们将创建自己的自定义标签实现并在JSP页面中使用它。 下面是示例项目的最终结构。

JSP自定义标记处理程序 (JSP Custom Tag Handler)

This is the first step in creating custom tags in JSP. All we need to do is extend javax.servlet.jsp.tagext.SimpleTagSupport class and override doTag() method.

这是在JSP中创建自定义标签的第一步。 我们需要做的就是扩展javax.servlet.jsp.tagext.SimpleTagSupport类并重写doTag()方法。

The important point to note is that we should have setter methods for the attributes we need for the tag. So we will define two setter methods – setFormat(String format) and setNumber(String number).

需要注意的重要一点是,我们应该为标记所需的属性提供设置方法。 因此,我们将定义两个setter方法-setFormat(String format)setNumber(String number)

SimpleTagSupport provide methods through which we can get JspWriter object and write data to the response. We will use DecimalFormat class to generate the formatted string and then write it to response. The final implementation is given below.

SimpleTagSupport提供了一些方法,通过这些方法,我们可以获取JspWriter对象并将数据写入响应。 我们将使用DecimalFormat类生成格式化的字符串,然后将其写入响应。 最终实现如下。

NumberFormatterTag.java

NumberFormatterTag.java

package com.journaldev.jsp.customtags;

import java.io.IOException;
import java.text.DecimalFormat;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.SkipPageException;
import javax.servlet.jsp.tagext.SimpleTagSupport;

public class NumberFormatterTag extends SimpleTagSupport {

	private String format;
	private String number;

	public NumberFormatterTag() {
	}

	public void setFormat(String format) {
		this.format = format;
	}

	public void setNumber(String number) {
		this.number = number;
	}

	@Override
	public void doTag() throws JspException, IOException {
		System.out.println("Number is:" + number);
		System.out.println("Format is:" + format);
		try {
			double amount = Double.parseDouble(number);
			DecimalFormat formatter = new DecimalFormat(format);
			String formattedNumber = formatter.format(amount);
			getJspContext().getOut().write(formattedNumber);
		} catch (Exception e) {
			e.printStackTrace();
			// stop page from loading further by throwing SkipPageException
			throw new SkipPageException("Exception in formatting " + number
					+ " with format " + format);
		}
	}

}

Notice that I am catching exception thrown by format() method and then throwing SkipPageException to prevent further loading of the JSP page.

请注意,我正在捕获format()方法引发的异常,然后引发SkipPageException以防止进一步加载JSP页面。

创建JSP定制标记库描述符(TLD)文件 (Creating JSP Custom Tag Library Descriptor (TLD) File)

Once the tag handler class is ready, we need to define a TLD file inside the WEB-INF directory so that container will load it when application is deployed.

标记处理程序类准备就绪后,我们需要在WEB-INF目录中定义一个TLD文件,以便容器在部署应用程序时将其加载。

numberformatter.tld

numberformatter.tld

<?xml version="1.0" encoding="UTF-8" ?>

<taglib xmlns="https://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="https://java.sun.com/xml/ns/j2ee https://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd"
    version="2.0">
<description>Number Formatter Custom Tag</description>
<tlib-version>2.1</tlib-version>
<short-name>mytags</short-name>
<uri>https://journaldev.com/jsp/tlds/mytags</uri>
<tag>
	<name>formatNumber</name>
	<tag-class>com.journaldev.jsp.customtags.NumberFormatterTag</tag-class>
	<body-content>empty</body-content>
	<attribute>
	<name>format</name>
	<required>true</required>
	</attribute>
	<attribute>
	<name>number</name>
	<required>true</required>
	</attribute>
</tag>
</taglib>

Notice the URI element, we will have to define it in our deployment descriptor file. Also notice the attributes format and number that are required. body-content is empty means that the tag will not have any body.

注意URI元素,我们将必须在我们的部署描述符文件中对其进行定义。 还要注意所需的属性格式和编号。 body-content为空表示标签将没有任何正文。

JSP定制标记部署描述符配置 (JSP Custom Tag Deployment Descriptor Configuration)

We will include the jsp custom tag library in web application using jsp-config and taglib elements like below.

我们将使用如下所示的jsp-configtaglib元素在Web应用程序中包含jsp定制标记库。

web.xml

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xmlns="https://java.sun.com/xml/ns/javaee" xsi:schemaLocation="https://java.sun.com/xml/ns/javaee https://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
  <display-name>JSPCustomTags</display-name>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  
  <jsp-config>
  <taglib>
  	<taglib-uri>https://journaldev.com/jsp/tlds/mytags</taglib-uri>
  	<taglib-location>/WEB-INF/numberformatter.tld</taglib-location>
  </taglib>
  </jsp-config>
</web-app>

taglib-uri value should be same as defined in the TLD file. All the configuration is done now and we can use it in the JSP page.

taglib-uri值应与TLD文件中定义的值相同。 现在已完成所有配置,我们可以在JSP页面中使用它。

使用JSP自定义标签的页面 (Page using JSP Custom Tag)

Here is a sample JSP page where I am using our number formatter jsp custom tag.

这是一个示例JSP页面,我在其中使用我们的数字格式器jsp自定义标记。

index.jsp

index.jsp

<%@ page language="java" contentType="text/html; charset=US-ASCII"
    pageEncoding="US-ASCII"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "https://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Custom Tag Example</title>
<%@ taglib uri="https://journaldev.com/jsp/tlds/mytags" prefix="mytags"%>
</head>
<body>

<h2>Number Formatting Example</h2>

<mytags:formatNumber number="100050.574" format="#,###.00"/><br><br>

<mytags:formatNumber number="1234.567" format="$# ###.00"/><br><br>

<p><strong>Thanks You!!</strong></p>
</body>
</html>

Now when we run our web application, we get JSP page like below image.

现在,当我们运行我们的Web应用程序时,我们将获得下图所示的JSP页面。

The JSP response page is showing the formatted number, similarly we can create more jsp custom tag handler classes. We can have multiple tags defined in the tag library.

JSP响应页面显示了格式化的数字,类似地,我们可以创建更多的jsp自定义标记处理程序类。 我们可以在标签库中定义多个标签。

If you have a lot of custom tag handler classes or you want it to provide as a JAR file for others to use, you need to include TLD files in the META-INF directory of the JAR file and include it in the web application lib directory. In that case, we don’t need to configure them in web.xml also because JSP container takes care of that.

如果您有很多自定义标记处理程序类,或者希望将其作为JAR文件提供给他人使用,则需要在JAR文件的META-INF目录中包含TLD文件,并将其包含在Web应用程序li​​b目录中。 在这种情况下,我们也不需要在web.xml中对其进行配置,因为JSP容器会处理这些问题。

That’s why when we use JSP Standard Tags, we don’t need to configure them in web.xml and we can declare them in JSP and use them. If you are not convinced, unzip the JSTL Tomcat standard.jar and you will find a lot of TLD files in the META-INF directory. 🙂

这就是为什么当我们使用JSP标准标记时,我们不需要在web.xml中对其进行配置,而可以在JSP中声明它们并使用它们。 如果您不确定,请解压缩JSTL Tomcat standard.jar并在META-INF目录中找到许多TLD文件。 🙂

That’s all for custom tags in JSP, I hope you liked it.

这就是JSP中自定义标记的全部,希望您喜欢它。

翻译自: https://www.journaldev.com/2099/jsp-custom-tags-example-tutorial

自定义标签的使用jsp实例

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值