tags:

views:

133

answers:

2
+3  Q: 

useBean tag

Hi,

I'm really confused in the following two lines of Head First servlets & JSP book of page no. 349:

  1. The is a way of declaring and initializing the actual bean object you're using in .

2.Declare and intializea bean attribute with

<jsp:useBean> <jsp:useBean id="person"class="foo.Person" scope="request"/>

In the first line, why they've called an attribute as an object?

Since attribute is name/value pair bound to scope,like request, session.

A: 
<jsp:useBean id="person" class="foo.Person" scope="request"/>

In this line, the attribute "person" in the request scope will be an object instance of type "foo.Person".

The Apache Tomcat 6 implementation translates the tag to this Java code:

  foo.Person person = null;
  synchronized (request) {
    person = (foo.Person) _jspx_page_context.getAttribute("person", 
                            PageContext.REQUEST_SCOPE);
    if (person == null){
      person = new foo.Person();
      _jspx_page_context.setAttribute("person", person,
                            PageContext.REQUEST_SCOPE);
    }
  }

_jspx_page_context is an instance of PageContext.

McDowell
I think you're going wrong since object is an instance, but you're considering instance as a reference rather than as an object. Correct me if I wrong.
Greenhorn
+1  A: 
<jsp:useBean id="person"class="foo.Person" scope="request"/>

This calls the default constructor for foo.Person

The id "person" allows you to reference the Bean on your jsp page

<div>   
    <c:out value="${person.name}" />
</div>

The scope is the scope for the Bean foo.Person

JSP syntax reference for useBean has definitions for each scope.

So your JavaBean would look something like this

package foo;

public class Person {

    private String name;

    public Person() {
        this.name = "jack"
    }

    public String getName() {
       return name;
    }

    public void setName(String n) {
        this.name = n;
    }

}

If the Person Bean has already been instantiated in your referenced scope, the useBean will locate and make available the Bean for use in expressions and scriplets on your JSP page.

Mark Robinson