今天有位以前的同学咨询我关于jsp
标签的问题,花了大概一个小时整理一下
maven项目结构
maven项目依赖
新建一个maven项目,pom依赖
<!-- 标签依赖度库 -->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.1</version>
<scope>provided</scope>
</dependency>
<!-- 测试依赖的库-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- 测试依赖的库-->
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
标签开发
标签开发实际需要依赖于后台的java文件,新增三种不同类型的文件,都是直接继承类SimpleTagSupport
即可
- 默认输出
public class HelloTag extends SimpleTagSupport {
public void doTag() throws JspException, IOException {
JspWriter out = getJspContext().getOut();
out.println("Hello Custom Tag!");
}
}
- 标签体输出
public class BodyTag extends SimpleTagSupport {
StringWriter sw = new StringWriter();
public void doTag() throws JspException, IOException {
getJspBody().invoke(sw);
getJspContext().getOut().println(sw.toString());
}
}
- 属性输出
public class PropertyTag extends SimpleTagSupport {
private String name;
// 不能缺少set方法
public void setName(String name) {
this.name = name;
}
public void doTag() throws JspException, IOException {
if (name != null) {
/* 从属性中使用消息 */
JspWriter out = getJspContext().getOut();
out.println(name);
}
}
}
配置标签文件
custom.tld,也可以分三个不同的文件都可以
<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>2.0</jsp-version>
<short-name>Example TLD</short-name>
<tag>
<name>test</name>
<tag-class>priv.dengjili.tag.HelloTag</tag-class>
<body-content>empty</body-content>
</tag>
<tag>
<name>bodycontent</name>
<tag-class>priv.dengjili.tag.BodyTag</tag-class>
<body-content>scriptless</body-content>
</tag>
<tag>
<name>propertyTest</name>
<tag-class>priv.dengjili.tag.PropertyTag</tag-class>
<body-content>scriptless</body-content>
<attribute>
<name>name</name>
<required>false</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
</taglib>
使用标签
- 新建
index.jsp
文件,测试我们新建的三种类型的标签
<%@ taglib prefix="hello" uri="WEB-INF/custom.tld"%>
<html>
<body>
<h2>base tag</h2>
<hello:test/>
<hr/>
<hello:bodycontent>3245678</hello:bodycontent>
<hr/>
<hello:propertyTest>35y</hello:propertyTest>
<hr/>
<hello:propertyTest name="zhangsan">35y</hello:propertyTest>
</body>
</html>
- 新建
validate.jsp
文件,测试标签与JSP
表达式
<%@ taglib prefix="hello" uri="WEB-INF/custom.tld"%>
<%
String name = "xiaowang";
%>
<html>
<body>
<h2>test tag</h2>
<hello:propertyTest name="<%=name %>"/>
</body>
</html>
- 新建
validate.jsp
文件,测试标签与JSTL
表达式
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<%@ taglib prefix="hello" uri="WEB-INF/custom.tld"%>
<%
// 设置页面有效域
pageContext.setAttribute("name", "xiaowang");
%>
<html>
<body>
<h2>jstl tag</h2>
<c:set var="age" value="2345"></c:set>
<p>年龄 : ${age}</p>
<p>姓名 : ${name}</p>
<hello:propertyTest name="${name}"/>
</body>
</html>