jsp 标签

一:web.xml 里引入配置
 <!-- 配置标签 -->
 <jsp-config>  
    <taglib>  
        <taglib-uri>myjsp_tag(任意标识名称)</taglib-uri>  
        <taglib-location>/WEB-INF/tld/mytld.tld</taglib-location>  
    </taglib>  
</jsp-config>

二:编写.tld 文件:
<?xml version="1.0" encoding="UTF-8"?>
<taglib version="2.0" xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee web-jsptaglibrary_2_0.xsd">
<tlib-version>1.0</tlib-version>
<jsp-version>2.0</jsp-version>
<short-name></short-name>
<uri>/myjsp_tag</uri><!-- 引入url 唯一标识-->
<tag>
<name>test</name><!--标签名称-->
<tag-class>com.azcsoft.tool.HelloTag</tag-class>
<body-content>empty</body-content>
<attribute>
<name>id</name>
<required>false</required>
</attribute>
<attribute>
<name>name</name>
<required>true</required>
</attribute>
<attribute>
<name>code</name>
<required>true</required>
</attribute>
<attribute>
<name>value</name>
<required>false</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
</taglib>

当在<attribute>标签里指定<rtexprvalue>true</rtexprvalue>时, 表示该自定义标签的某属性的值可以直接指定或者通过动态计算指定
<myTag:cupSize cupSize="${nameid}" cupSizes="${result}"></myTag:cupSize>

三:编写标签类:
public class HelloTag extends SimpleTagSupport{
private String id;
private String name;
private String code;
private String value;
@Override
public void doTag() throws JspException, IOException {
System.out.println(name);
JspWriter jw = super.getJspContext().getOut();
jw.write("hello");
}
set 、get ......

-------------struts 和spring 结合时,service 是无法注入到此处的,该处初始化时既开始

获取方式:
ServletContext servletContext = ((PageContext) this.getJspContext()).getServletContext();
     WebApplicationContext wac =
WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
    DictitemService dictitemService = (DictitemService)
wac.getBean("dictitemService");
    String str = dictitemService.getDictitemname(dictcode, itemcode);
    JspWriter jw =
super.getJspContext().getOut();
    jw.write(str);
 

四:页面引用:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<%@ taglib prefix="t" uri="/myjsp_tag" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">    
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
  </head>
  <body>
  <t:test id="" name="ZZD" value="" code=""/>
  aaaaaaaaaaaaaaaaaaaaaaa
  </body>
</html>
原文地址:https://www.cnblogs.com/leonkobe/p/3611414.html