JSP自定义标签
虽然html很好,尤其是html5越来越火,但仍有很多网站是用JSP做的,JSP里面虽然有很多标签,但我们是否可以自己定义自己的呢?当然可以,参考代码如下:
1. 写自己的taglib类,并重写里面的方法
public class DropDownBoxTaglib extends TagSupport {
private static final long serialVersionUID = 1L;
@Override
public int doStartTag() throws JspTagException {
return SKIP_BODY;
}
@Override
public int doEndTag() throws JspTagException {
HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
RequestTypeService requestTypeService = (RequestTypeService) applicationContext.getBean("requestTypeService");
List<RequestType> requestTypes = requestTypeService.query();
request.setAttribute("REQUESTTYPES", requestTypes);
try {
pageContext.include("/component/request_type_select.jsp");
} catch (ServletException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return EVAL_PAGE;
}
@Override
public void release() {
super.release();
}
}
2. 对应的tld文件
<?xml version="1.0" encoding="UTF-8"?> <taglib 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" version="2.0"> <tlib-version>1.0</tlib-version> <jsp-version>1.1</jsp-version> <short-name>aug</short-name> <tag> <name>select</name> <tag-class>cn.bridgeli.DropDownBoxTaglib</tag-class> <body-content>empty</body-content> <!-- <attribute> <name>formatKey</name> <required>false</required> <rtexprvalue>true</rtexprvalue> </attribute> --> </tag> </taglib>
3. 具体哪个文件使用该taglib
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%
List<RequestType> requestTypes = (List<RequestType>)request.getAttribute("REQUESTTYPES");
%>
<select name = "requestTypeId" id="requestTypeId" style="width: 608px;">
<option >--Select a request type Please--</option>
<%
for(int i = 0; i < requestTypes.size(); i++) {
RequestType requestType = requestTypes.get(i);
%>
<option value =<%= requestType.getId() %>><%= requestType.getName() %></option>
<%
}
%>
</select>
全文完,如果本文对您有所帮助,请花 1 秒钟帮忙点击一下广告,谢谢。
作 者: BridgeLi,https://www.bridgeli.cn
原文链接:http://www.bridgeli.cn/archives/36
版权声明:非特殊声明均为本站原创作品,转载时请注明作者和原文链接。
作 者: BridgeLi,https://www.bridgeli.cn
原文链接:http://www.bridgeli.cn/archives/36
版权声明:非特殊声明均为本站原创作品,转载时请注明作者和原文链接。
分类: Java
近期评论