Adding Javabeans

Sometimes you just need to add some bit of Java to the page and you don't want, or can't involve java developers. You know the classname, the class is available to your application (through system libraries or being added to the WEB-INF directories) and all you want to do is reference it. This is the function of the $javabeans objects.

The BeanFactory $javabeans object provides a simplified equivalent to the <jsp:useBean> and <jsp:setProperty> features in JSP, allowing page designers to add arbitrary Java objects to their templates without requiring updates to the Java webapp libraries or any other java programmer intervention.

To support Java beans, SportPage adds two context utility objects, $params and $javabeans:

Inside a Velocity template, we can use constructs like

   #set ($now = $javabean.getBean("java.util.Date"))

or, if the bean supports it, have a form handler selecting weather cities and use

   #set ($weather = $javabean.getBean($context, "cbc.utilities.weather" ))
   $params.setProperties( $weather )

Any configuration file dot-variables ending in “.bean” will be interpreted as a fully-qualified Java classname and instanced as a Java bean; like any dot-property, you can specify these per-topic and inherit bean variables from a parent topic

   default.weather.bean=cbc.utilities.weather

will define a global $weather variable using the specified class

   sports.luge.history.weather.bean=cbc.utilities.weather_history

would mean that, in sports/luge/history only, the $weather refers to a different class of object.

[Caution]Caution

Because dot-variable and BeanFactor constructors are evaluated as each template is accessed, they are expensive to invoke; the beans should cache themselves or be singleton objects where ever practical, and constructors should be lightening quick.



[3] Java beans can also be created under an applications scope by attaching bean instances to the $global application configuration Map object. Because Velocity templates are all, to Java, the same servlet, there is no equivalent to a page scope without extra programming to cache the object based on the $path; examples of such caching can be found in the JDOMFile source code.