Kelvin,
Originally posted by Kelvin Hung:
The following code is taken from P.225 of Professional SCWCD Certification by Wrox:
<jsp:useBean id="user" class="com.wrox.scwcd.chapter10.UserBean" />
<jsp:setProperty name="user" property="firstName" value="Wrox" />
...
...
... make JSP pages more readable and to aid maintainability:
<%
UserBean user = (UserBean) page.findAttribute("user");
if( user != null) {
user.setFirstName("Wrox");
}
%>
Ok, my question is, the implicit object page doesn't have the method findAttribute(). Should it be pageContext.findAttribute("user") instead?
I think the truth is far from what the book said. I tested with one JSP page, on JavaBean Class, and I checked the translated
java class for the JSP page:
JSP page is test.jsp:
<jsp irective.page isELIgnored="false" />
<jsp irective.include file="header.jspf" />
<br/>
<jsp:useBean id="gr" class="com.hover.Htest"/>
<jsp:setProperty name="gr" property="greeting" value="The art of jsp"/>
${gr.greeting}
<%@include file="footer.jspf" %>
the JavaBean is:
package com.hover;
import java.io.Serializable;
public class Htest implements Serializable {
private String greeting;
public void setGreeting(String g){
greeting = g;
}
public String getGreeting(){
return greeting;
}
}
Now mostly insteresting, the following is relative part from what is generated for test.jsp:
synchronized (pageContext) {
gr = (com.hover.Htest) pageContext.getAttribute("gr", PageContext.PAGE_SCOPE);
if (gr == null){
gr = new com.hover.Htest();
pageContext.setAttribute("gr", gr, PageContext.PAGE_SCOPE);
}
}
As we see:
- "pageContext" is used to retrieve the JavaBean
- Another parameter must specified for pageContext.getAttribute is the scope of the JavaBean, "PageContext.PAGE_SCOPE". The reason for page scope is we didn't specify scope in <jsp:useBean>, and the default scope value is "page".
- if the JavaBean has not existed, it will be created at this phase
Hope this is helpful.
( btw, kelvin, do I know you before? )
[ January 17, 2004: Message edited by: hover cheng ]