hqt*_*hqt 2 java jsp javabeans
例如,我有这个代码:
<jsp:useBean id="dog" class="Dog" scope="application">
<jsp:setProperty name="dog" property="breed" value="House Dog !!!"/>
</jsp:useBean>
Run Code Online (Sandbox Code Playgroud)
我知道它是如何工作的.但是,有时候,我在这里更改了一些代码,例如:"dog"到"newDog",我会遇到错误或未经编辑的结果(和我一起).
请告诉我如何将上面的代码生成到Java中.(也许只是一个主要想法)
谢谢 :)
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>
Run Code Online (Sandbox Code Playgroud)
(我唯一的改变就是添加一个包;无包装类是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');
}
}
Run Code Online (Sandbox Code Playgroud)
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);
}
Run Code Online (Sandbox Code Playgroud)
你看,它java.beans.Introspector用于获取bean信息和属性BeanInfo#getPropertyDescriptors().所需的<jsp:setProperty>方法如获得java.lang.reflect.Method通过PropertyDescriptor#getWriteMethod().最后,它使用Reflection API来调用该方法.