O'Reilly logo

Head First Servlets and JSP, 2nd Edition by Bert Bates, Bryan Basham, Kathy Sierra

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

<jsp:useBean> can also CREATE a bean!

If the <jsp:useBean> can’t find an attribute object named “person”, it can make one! It’s kind of the way request.getSession() (or getSession(true)) works—it first searches for an existing thing, but if it doesn’t find one, it creates one.

Look at the code from the generated servlet, and you’ll see what’s happening—there’s an if test in there! It checks for a bean based on the values of id and scope in the tag, and if it doesn’t get one, it makes an instance of the class specified in class, assigns the object to the id variable, then sets it as an attribute in the scope you defined in the tag.

This tag

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

Turns into this code in the _jspService() method

image with no caption

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required