Howard Lee wrote:
>
> Hi guys,
>
> Someone here said awhile ago that useBean and getAttribute is the same
> thing. e.g. I setAttribute(someBean, "myBean") in a servlet, and then I
> forward it to a JSP. Inside the JSP, I do getAttribute("myBean") and I can
> get the someBean, but he mentioned that I can also get the someBean by using
> <jsp:useBean id="myBean" type="someBean" scope="session" />. But when I
> tried it, it didn't work. What am I missing here? Can I access a variable
> from session that was defined in a servlet by using useBean? Thanks.
Yes, you can. Actually, that's main principle which lets developers
separate data preparation (servlet) from their presentation (JSP). The
famous Model 2 is based just on that - so one can define *one* servlet
controller which after doing some data preparation forwards requests to
appropriate JSPs in order to present that data to a user. Besides, JSPs
are translated to servlets, so what you can do in servlets, you can in
JSP too. All <jsp:...> tags are just to decrease amount of Java code in
JSP, so HTML guru is able to maintain JSP pages as long as JSP guru will
provide enough information about new tags (JSP owned and the new ones).
So, to address your doubts, let's see at some examples:
*) In controller servlet, you could write:
my.package.Foo foo = new my.package.Foo();
HttpSession session = new HttpSession(true);
if (session != null) {
session.setAttribute("foo", foo);
}
getServletContext().getRequestDispatcher("/view.jsp")
.forward(request, response);
*) In view.jsp page, you then access "foo" bean as follows:
<jsp:useBean id="foo" class="my.package.Foo" scope="session" />
<jsp:getProperty name="foo" property="bar" />
What it's done above is that view.jsp retrieves "foo" variable of
my.package.Foo type. It's been stored in session in above controller
server, so to access it, one *must* use correct scope (in that case -
session).
Then <jsp:getProperty> invoke appropriate getter method:
public String getBar()
You could also use other scopes (i.e. page, request or application), but
doing so, you'll change availability of particular bean and it needs to
be matched to the same scope in servlet (i.e. local variable,
HttpServletRequest or ServletContext respectively).
Jacek Laskowski
===========================================================================
To unsubscribe: mailto [EMAIL PROTECTED] with body: "signoff JSP-INTEREST".
Some relevant FAQs on JSP/Servlets can be found at:
http://java.sun.com/products/jsp/faq.html
http://www.esperanto.org.nz/jsp/jspfaq.html
http://www.jguru.com/jguru/faq/faqpage.jsp?name=JSP
http://www.jguru.com/jguru/faq/faqpage.jsp?name=Servlets