JSP は最終的に.java
、サーブレットとしてコンパイルされるクラスに生成されます。サーバーの作業フォルダを確認してください。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()
ます。最後に、Reflection APIを使用してメソッドを呼び出します。