<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

Get Head First Servlets and JSP, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.