做了一多年的程序员,还是第一次写点东西,呵呵,先保存个以后可能用到的实例:
这里写个简单的jsp标记实例.
1.java类:
package com.hjglddok.tag;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.JspFragment;
import javax.servlet.jsp.tagext.SimpleTagSupport;
public class MyTagHandler extends SimpleTagSupport {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public void doTag() throws JspException {
JspWriter out = getJspContext().getOut();
try {
/**如果用的是netbeans的话,除了以下一句根据自己需求编写的,其它的都是netbeans自动生成代码.
* out.println(string)是将string内容打印到web页面.
*/
out.println(URLEncoder.encode(getName(),"UTF-8"));
JspFragment f = getJspBody();
if (f != null) f.invoke(out);
} catch (java.io.IOException ex) {
throw new JspException("Error in MyTagHandler tag", ex);
}
}
}
2.tld文件内容
<taglib>
<tlib-version>1.0</tlib-version>
<short-name>my</short-name>
<uri>/WEB-INF/tlds/my</uri>
<tag>
<name>MyTagHandler</name>
<!--类路径-->
<tag-class>com.hjglddok.tag.MyTagHandler</tag-class>
<body-content>scriptless</body-content>
<attribute>
<!--MyTagHandler类的name属性-->
<name>name</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
</taglib>
3.web.xml文件配置
<web-app>
<jsp-config>
<taglib>
<taglib-uri>/my</taglib-uri>
<taglib-location>/WEB-INF/tlds/my.tld</taglib-location>
</taglib>
</jsp-config>
</web-app>
4.实际应用
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib uri="/my" prefix="my" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>Hello World!</h1>
<my:MyTagHandler name="阿光" />
</body>
</html>