Expression Language and JavaBeans

It is easy to access a JavaBean in a JSP page, if the bean itself does not represent a complex entity.

It gets a bit more akward if we our bean has attributes other than Strings or primitives. Expression Language is a key feature in this context.

Let's write an example that uses a Person JavaBean, designed in this way:
package ch08;

public class Person {
    private String name;
    private Dog dog;

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

    public String getName() {
        return name;
    }

    public void setDog(Dog dog) {
        this.dog = dog;
    }

    public Dog getDog() {
        return dog;
    }
}
Where the Dog class is this:
package ch08;

public class Dog {
    private String name;

    public String getName() {
        return name;
    }

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

Given that, in a servlet we write the doPost() method in this way:
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
    Person p = new Person();
    p.setName("Evan");

    Dog dog = new Dog();
    dog.setName("Spike");
    p.setDog(dog);

    request.setAttribute("person", p);
    RequestDispatcher view = request.getRequestDispatcher("person.jsp");
    view.forward(request, response);
}
We create a person, Evan, who has a dog named Spike, and we put it as attribute named "person" in the request scope. Then we forward the call to the person.jsp page.

In our JSP page we want to display the dog's name to the user. We can do that quite easily, but verbosely, using the scripting capabilities:
<h2>Using scripting</h2>
Dog's name is:
<%= ((ch08.Person) request.getAttribute("person")).getDog().getName() %>
This should be easy to understand, at least for a Java developer. Maybe not so for a HTML expert.

Trying to use the standard actions, we could think to rewrite that piece of code in this way:
<h2>Using standard actions</h2>
<jsp:useBean id="person" class="ch08.Person" scope="request" />
Dog's (object) name is: <jsp:getProperty name="person" property="dog" />
But the result is not what one usually expects. The issue is that the property "dog" of "person" is printed using the toString() method. We'd better add an override to it in the Dog class:
@Override
public String toString() {
    return name;
}
We don't need to modify our Dog class if we use the Expression Language (EL) instead. And we get a code that is way simpler to write, read, and mantain:
<h2>Using EL - Expression Language</h2>
Dog's name is: ${person.dog.name}
See the eighth chapter of Head First Servlet and JSP for more on the matter.

No comments:

Post a Comment