在jsp中使用自定义标签 实现反射机制
[code="java"][/code]其中存在两张表A和B,其中表B中字段的值是表A的某个字段,现在给你B中某字段的值和对象A,要你取出它在对象A中对应的属性值。在这种情况下你若选择使用反射机制会非常方面。一下是相应的代码: [code="java"] import java.io.IOException; import java.lang.reflect.Field; import javax.servlet.jsp.JspException; import javax.servlet.jsp.JspWriter; import javax.servlet.jsp.tagext.TagSupport; public class RFTag extends TagSupport { private static final long serialVersionUID = -2360561035810220875L; private Object object; private String property; public Object getObject() { return object; } public void setObject(Object object) { this.object = object; } public String getProperty() { return property; } public void setProperty(String property) { this.property = property; } public int doStartTag() throws JspException { JspWriter out = this.pageContext.getOut(); try { if (object == null) { out.println(""); } else { //get the object of this field Field f = object.getClass().getDeclaredField(property); f.setAccessible(true); //get the value of this field Object value = f.get(object); out.println(value == null ? "" : value.toString()); } } catch (IOException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (SecurityException e) { e.printStackTrace(); } catch (NoSuchFieldException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } return SKIP_BODY; } } [/code] 下面是WEB-INF目录下的文件fs.tld文件的内容,主要是定义的在jsp中使用的标签。代码如下: [code="java"] 1.0 2.0 foundTag http://www.foundersoftware.com/founder/tags page com.founder.abgent.core.web.tag.PageTag action true true param false true color false rf com.founder.bcimp.core.web.tag.RFTag object true true property true true [/code] 具体的在jsp中的应用实例.代码如下: [code="java"] <%@ page language="java" contentType="text/html; charset=UTF-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <%@ taglib uri="http://www.foundersoftware.com/founder/tags" prefix="fs"%>
${enterpriseCustomField.columnLabel } "/[/b]>
[/code]