Search code examples
javajspservletsjavabeans

Why I can't use <jsp:getProperty> without <jsp:useBean>?


Say there is servlet that has code:

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    foo.Person p = new foo.Person("Evan");
    req.setAttribute("person", p);

    RequestDispatcher view = req.getRequestDispatcher("/result.jsp");
    view.forward(req, resp);
}

, that goes to result.jsp to print given name (Evan). Here is a picture of how it would look (source Head First Servlets and JSP):

enter image description here

I know that <jsp:useBean> returns same Person object by calling getAttribute()- since they are in same request scope. While on the other side, <jsp:getProperty> will call findAttribute() to literally try to find attribute of value "person".. and eventually print Evan.

But what if I didn't use <jsp:useBean>? Does that mean I couldn't access "person" attribute at scope request? I mean it would still be there, even if I didn't use <jsp:useBean>. So why I must have same value("person") inside both id in <jsp:useBean> and name inside <jsp:getProperty>? Simple removing <jsp:useBean> breaks my program.

Knowing that <jsp:getProperty> calls findAttribute(), wouldn't it be more logical if there was a single attribute (like attribute-name), that will be used as an argument to find attributes in scopes page>request>session>application? Why I must "tie" those two tags: <jsp:useBean> and <jsp:getProperty>?


Solution

  • What do you think of the following code?

    public class Main {
        public static void main(String[] args) {
            System.out.println(person);
        }
    }
    

    You must have already correctly guessed that it won't be compiled successfully.

    Now, what about the following code?

    public class Main {
        public static void main(String[] args) {
            Person person = new Person();// Declaring person
            System.out.println(person);
        }
    }
    

    Of course, it will be compiled successfully1 because now the compiler understands what person is.

    Similarly, using

    <jsp:getProperty name="person" property="name">
    

    without declaring person as

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

    won't be compiled successfully.


    1 Assuming Person.class is there.