【发布时间】:2016-04-30 14:42:41
【问题描述】:
我正在创建一个自定义标签指令,我必须在其中打印数据库中的数据表。
到目前为止我已经创建了:
JSP 页面:
<%@taglib uri="/WEB-INF/tlds/fact.tld" prefix="veritis"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1><veritis:print name="emp" /></h1>
</body>
</html>
TLD 文件:
<?xml version="1.0" encoding="UTF-8"?>
<taglib version="2.1" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_1.xsd">
<tlib-version>1.0</tlib-version>
<short-name>factorial</short-name>
<tag>
<name>print</name>
<tag-class>com.veritis.jsp.FactTag</tag-class>
<body-content>empty</body-content>
<attribute>
<name>name</name>
<required>false</required>
</attribute>
</tag>
</taglib>
和一个Class 文件,它使用其他Class 文件从数据库中获取数据。此类文件还扩展了 TagSupport 以覆盖所需的 TLD 方法。
public class FactTag extends TagSupport{
String value="emp";
public String getValue() {
return value; }
public void setValue(String value) {
this.value = value;
}
public int doStartTag(){
return Tag.SKIP_BODY;
}
public int doEndTag() throws JspTagException{
String emp1=getValue();
try{
//The following line is to get the JSP Writer Object
//similar to PrintWriter in Servlet
JspWriter out=pageContext.getOut();
TableData tbd=new TableData();
List<Employee> listOfEmp=tbd.getAllEMployees();
for(Employee emp:listOfEmp)
{
System.out.println(emp);
}
}catch(Exception e){}
return Tag.SKIP_PAGE;
}
}
现在我的List<emp> 中有数据,我想将其打印到 JSP 文件中。我可以通过使用 out 对象来打印它,但我的要求是不要使用 out 对象,而是通过包含其他 JSP 文件或任何其他方式来打印。
注意:虽然我从 JSP 中获取了input(emp),但我暂时没有使用它。相反,我正在生成一个静态查询来获取数据。
【问题讨论】:
-
还有什么JSP文件?有很多方法可以做到,请说明您的要求。
-
就像将此员工列表对象发送到一个 jsp 文件以打印它并包含它。需要明确的是,我不想编写 Java 代码打印表,而是想使用 JSTL 打印它
-
自定义标签不适合您的工作。 RomanC 朝正确的方向开了一枪,这个方向已经被淘汰了多年。另见 a.o. stackoverflow.com/q/5003142 MVC 框架将减少样板代码。
标签: java jsp tld custom-tags