自定义标签的使用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;}@Overridepublic 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 SkipPageExceptionthrow 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实例_JSP自定义标签示例教程相关推荐

  1. servlet过滤器 实例_Java Servlet过滤器示例教程

    servlet过滤器 实例 Java Servlet Filter is used to intercept the client request and do some pre-processing ...

  2. java ldap操作实例_Java Spring Security示例教程中的2种设置LDAP Active Directory身份验证的方法...

    java ldap操作实例 LDAP身份验证是世界上最流行的企业应用程序身份验证机制之一,而Active Directory (Microsoft为Windows提供的LDAP实现)是另一种广泛使用的 ...

  3. jsf入门实例_JSF错误消息示例教程

    jsf入门实例 In this section, we will see how to use the default JSF validators to shoot out the built in ...

  4. jsp if else c标签 总结

    JSTL标签使用方法 keyword:JSTL标签.<c:choose>.<c:forEach>.<c:forTokens>.<c:if>.<c: ...

  5. java程序设计颜志军_JSP 自定义标签之一 简单实例

    在JSP中使用自定义标签可以达到这样的目的,事实上,我们所熟知的各类框架基本上都是通过自定义标签的形式来实现的. 通过使用自定义标签,我们可以将实现复杂的逻辑在页面用简单的标签来加以展示.下面我们来实 ...

  6. java自定义标签简单_JSP 自定义标签之一 简单实例

    在jsp中使用自定义标签可以达到这样的目的,事实上,我们所熟知的各类框架基本上都是通过自定义标签的形式来实现的. 通过使用自定义标签,我们可以将实现复杂的逻辑在页面用简单的标签来加以展示.下面我们来实 ...

  7. jsp中用java写标签id_jsp中自定义标签用法实例分析

    本文实例讲述了jsp中自定义标签用法.分享给大家供大家参考.具体如下: 这里简单的写了一个自定义标签,自己定义标签的好处就是在jsp页面中可以使用自己定义的功能,完全与Java代码分离 1. tld文 ...

  8. java jsp 自定义标签_JSP自定义标签

    在本章中,我们将讨论JSP中的自定义标签.自定义标签是用户定义的JSP语言元素.当包含自定义标签的JSP页面被转换成一个servlet时,标签被转换为一个名为标签处理程序的对象的操作. 然后,Web容 ...

  9. 深入体验JavaWeb开发内幕——简述JSP中的自定义标签叫你快速学会

    转载自   深入体验JavaWeb开发内幕--简述JSP中的自定义标签叫你快速学会 自定义标签,顾名思义,就是自己定义的标签.那么我们为什么要自己定义一些标签呢? 我们知道,如果要在JSP中获取数据我 ...

最新文章

  1. 360金融首席科学家张家兴:我们如何做数据AI融合中台?
  2. Python中from...import与import......as的区别
  3. 【9704】【9109】麦森数
  4. oracle for dotnet
  5. boost::fusion::none用法的测试程序
  6. SpringCloud微服务带来的问题
  7. 我在德国做SAP CRM One Order redesign工作的心得
  8. 前仓后仓是什么意思_高支纱到底是什么?镰仓衬衫面料全解析
  9. 720P实时超分和强悍的恢复效果:全知视频超分OVSR
  10. SpringSecurity Filter
  11. keil删除工程_RTT 是如何管理和构建工程的?
  12. rocketmq 部署启动指南-Docker 版
  13. 来给你的CSDN博客换个皮肤~
  14. 信创终端违规外联案例分析及防控措施
  15. matlab互相关函数并画图,自相关函数和互相关函数的matlab计算和作图
  16. html设置列表编号起始值,Word多级编号怎么设置,要按我的要求作为起始值?
  17. 新手接触使用Hashcat 破解Office加密文档
  18. MOOC-浙江大学-博弈论基础-学习笔记(四)
  19. 成长路上破局思维:工具化时间管理
  20. html----烟花代码

热门文章

  1. VB MSFlexGrid控件使用问题
  2. 扩展 delphi 泛型 以实现类似lambda功能 , C#中的any count first last 等扩展方法
  3. ubuntu下安装beanstalkd
  4. (zt)svn 随服务器启动
  5. Sql 语句:显示 Sql Server 中所有表中的信息
  6. [转载] python difference用法_set.difference() 的用法(python3)_举例说明python3 set方法功能
  7. [转载] Java中方法不可以有默认参数
  8. css标准流/非标准流 盒子模型
  9. excel冻结标题栏,让标题栏不滚动的方法
  10. 带你玩转JavaWeb开发之四 -如何用JS做登录注册页面校验