JSP 最终生成为.java
编译为 servlet 的类。检查服务器的工作文件夹。在 Tomcat 的情况下,将在 Tomcat 的文件夹中/test.jsp
生成一个文件。/org/apache/jsp/test_jsp.java
/work
以下几行
<jsp:useBean id="dog" class="com.example.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()
。最后,它使用反射 API来调用该方法。