栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Java Bean:如何 在 被生成为Java代码

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java Bean:如何  在  被生成为Java代码

JSP最终生成为

.java
类,这些类被编译为Servlet。检查服务器的工作文件夹。对于Tomcat,
/test.jsp
/org/apache/jsp/test_jsp.java
在Tomcat的
/work
文件夹中生成一个文件。

以下几行

<jsp:useBean id="dog"  scope="application">     <jsp:setProperty name="dog" property="breed" value="House Dog !!!"/></jsp:useBean>

(我所做的唯一更改是添加了一个程序包;无程序包类是Bad™)

生成为

  com.example.Dog dog = null;  synchronized (application) {    dog = (com.example.Dog) _jspx_page_context.getAttribute("dog", javax.servlet.jsp.PageContext.APPLICATION_SCOPE);    if (dog == null){      dog = new com.example.Dog();      _jspx_page_context.setAttribute("dog", dog, javax.servlet.jsp.PageContext.APPLICATION_SCOPE);      out.write("n");      out.write("     ");      org.apache.jasper.runtime.JspRuntimeLibrary.introspecthelper(_jspx_page_context.findAttribute("dog"), "breed", "House Dog !!!", null, null, false);      out.write('n');    }  }

Tomcat是开源的,根据其源代码,

JspRuntimeLibrary#introspecthelper()
方法委托
internalIntrospecthelper()
最终实现此目的:

Method method = null;Class<?> type = null;Class<?> propertyEditorClass = null;try {    java.beans.BeanInfo info        = java.beans.Introspector.getBeanInfo(bean.getClass());    if ( info != null ) {        java.beans.PropertyDescriptor pd[] = info.getPropertyDescriptors();        for (int i = 0 ; i < pd.length ; i++) { if ( pd[i].getName().equals(prop) ) {     method = pd[i].getWriteMethod();     type   = pd[i].getPropertyType();     propertyEditorClass = pd[i].getPropertyEditorClass();     break; }        }    }    if ( method != null ) {        if (type.isArray()) { if (request == null) {     throw new JasperException(         Localizer.getMessage("jsp.error.beans.setproperty.noindexset")); } Class<?> t = type.getComponentType(); String[] values = request.getParameterValues(param); //XXX Please check. if(values == null) return; if(t.equals(String.class)) {     method.invoke(bean, new Object[] { values }); } else {     createTypedArray (prop, bean, method, values, t, propertyEditorClass);  }        } else { if(value == null || (param != null && value.equals(""))) return; Object oval = convert(prop, value, type, propertyEditorClass); if ( oval != null )     method.invoke(bean, new Object[] { oval });        }    }} catch (Exception ex) {    Throwable thr = ExceptionUtils.unwrapInvocationTargetException(ex);    ExceptionUtils.handleThrowable(thr);    throw new JasperException(ex);}

您会看到,它

java.beans.Introspector
用于通过获取bean信息和属性
BeanInfo#getPropertyDescriptors()
。所需的
<jsp:setProperty>
方法如获得
java.lang.reflect.Method
通过
PropertyDescriptor#getWriteMethod()
。最后,它使用Reflection
API
调用该方法。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/421979.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号