JSP标签的作用?如何定义?
参考答案
JSP标签的作用主要是将与 页面的显示和控制
相关的逻辑进行封装和重用。
参考示例
1. 首先编写java类,继承SimpleTagSupport类,并重写doTag()方法:
package web;
import java.io.IOException;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.SimpleTagSupport;
public class HelloTag extends SimpleTagSupport {
private String message;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
@Override
public void doTag() throws JspException, IOException {
JspWriter out = this.getJspContext().getOut();
out.println("<h1>Hello, " + message + "</h1>");
}
}
2. 编写helloTag.tld文件,放入WEB-INF目录下
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE taglib PUBLIC
"-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"
"http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd" >
<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>1.2</jsp-version>
<short-name>short-name</short-name>
<uri>http://www.xingxue.com</uri>
<tag>
<name>helloTag</name>
<tag-class>web.HelloTag</tag-class>
<attribute>
<name>message</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<body-content>empty</body-content>
</tag>
</taglib>
3. 编写jsp,通过uri引用tag
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="m" uri="http://www.xingxue.com" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>标签示例</title>
</head>
<body>
<m:helloTag message="Tom"/>
</body>
</html>