15.2 Installing WebMacro

Java Servlet Programming, 2nd Edition > 15. WebMacro > 15.2 Installing WebMacro

 
< BACKCONTINUE >

15.2 Installing WebMacro

To execute a WebMacro servlet and template requires a little installation work. First, download the distribution from http://www.webmacro.org and unpack it. Include webmacro.jar and collections.jar in your server's classpath.[1] Then locate the WebMacro.properties file found within the distribution and copy it to a directory in your server's classpath. Note that because the classes in webmacro.jar rely on their class loader to locate the file, the file must be in the classpath of the class loader that loads webmacro.jar. To ensure you have this right, either put both in the system classpath where they'll be found by the primordial class loader, or put both under the WEB-INF directory where they'll be found by the web application class loader. (Put webmacro.jar in the WEB-INF/lib directory; put the WebMacro.properties file in the WEB-INF/classes directory.)

[1] The collections.jar archive contains the Java Collections classes (introduced in JDK 1.2) built for use with the earlier JDK 1.1. This JAR isn't required if you're using a build of WebMacro compiled specifically for JDK 1.2; however, at the time of this writing the default build held in the webmacro.jar archive was built for JDK 1.1.7 and therefore this JAR is required even when running JDK 1.2 or later.

The default WebMacro.properties in the distribution contains a long list of configuration options, the first portion of which is shown in Example 15-4. Most aspects of this file are well documented within the file. All you need to configure for now is the TemplatePath parameter, specifying the directory or directories where your templates are stored.

Example 15-4. A Standard WebMacro.properties File
# NOTE FOR NT USERS # # Beware that the \ character is the escape character in a Java # properties file. You must either double it (\\) or use the Unix # style (/) file separator in this file. Both should work. Also # when you set TemplatePath, be sure and use the NT path # separator (;) rather than the Unix separator (:). ########################################################### # # BASIC CONFIGURATION: # # You should set TemplatePath, at the very least! It is a list of # directories which will be searched for your templates, if you # give a relative filename. It is a list of directories separated # by a : (on Unix) or a ; (on NT). TemplatePath = /tomcat/webapps/webmacro/WEB-INF/templates;/local/webmacro/templates # WebMacro compiles and caches templates for efficiency. During development # you will want to turn this off by setting the following value to 0, so # that your template changes are immediately reflected on the website. In # production systems, this it the number of milliseconds of idle time # that a cached template will be retained, ie: 600000 is ten minutes. TemplateExpireTime = 0 # TemplateExpireTime == 600000 # LogLevel can be: ALL, DEBUG, EXCEPTION, ERROR, WARNING, INFO, or NONE # in order of most information to least information displayed. LogLevel = EXCEPTION # LogTraceExceptions causes exception stack traces to be included in the log, # this causes exceptions to be verbose, but may point out the exact line # or method which is causing a fault. LogTraceExceptions = TRUE # Uncomment the following to log to a file rather than stderr. If your # standard error writes to a useful log already, you don't need this, # but many servlet runners simply eat standard error. # LogFile = /usr/local/webmacro/wm.log # Set the template (relative to TemplateDirectory) used for errors. You # can edit this template to customize the way script failures appear ErrorTemplate = error.wm # The file continues with "ADVANCED CONFIGURATION" features...

A power user can create multiple versions of this file and swap between versions to quickly and completely alter the look and feel of a site (changing TemplatePath) or to just move from development to production mode (changing things like TemplateExpireTime). This swap-out can be done at a servlet-by-servlet level as well because the WM( ) constructor takes an optional String argument that specifies the location of the configuration file it should read. If a servlet needs direct access to the properties in this file, that's available through the getConfig(String key) method present in both the WebMacro interface and the WMServlet class. This lets the config file hold the equivalent of context init parameters, except these parameters are tied to a particular configuration perhaps pointing during development at a test database and on deployment at a production database.

Once everything has been properly installed, invoking WebMacro-enabled servlets is done like invoking any other servlet. Invoke the servlet as http://localhost:8080/servlet/WMHello or, with the servlets and templates that are placed under the /webmacro context as shown in the WebMacro.properties file, the URL would be http://localhost:8080/webmacro/servlet/WMHello. See Figure 15-1.

Figure 15-1. Testing WebMacro

15.2.1 The WebMacro Template Language

The WebMacro template language leverages the syntax of Perl and the C preprocessor to create a markup that looks familiar to many. Variables begin with a dollar sign ($) and end implicitly with whitespace or various punctuation characters like <, /, and ". This lets you write fairly readable substitutions, for example:

$Request.ContextPath/servlet/WMHello <A HREF="$url">$url</A>

Where needed, you can use parentheses to explicitly surround a variable name and disambiguate the parsing. The parentheses are consumed and not printed.

For example:

#set $prefix = "for" #set $suffix = "give" To err is human, to $(prefix)$suffix divine.

The WebMacro engine doesn't use the java.beans.Introspector class to access object properties; instead, it performs a more exhaustive reflective search. When you write $Request.ContextPath, the WebMacro engine first locates the object referred to by $Request, then attempts to locate the property using the following search pattern:

request.ContextPath request.getContextPath() request.get("ContextPath");

If you write a longer substitution, such as $Request.Header.Accept, WebMacro adds the following search pattern to the end of the list:

request.getHeader("Accept")

Variable assignment follows a similar search pattern.

You have the ability with WebMacro to directly invoke methods on all the objects in scope (something you explicitly couldn't do in Tea). For example, the following substitution locates the list of products in inventory, looks up the hinge product, and returns its part number:

$Inventory.Products.findProduct("hinge").PartNumber

This can prove useful when accessor methods don't follow the naming pattern expected by WebMacro. On the other hand, the direct invocation of methods means there can be no complete sandboxing of a WebMacro template.

15.2.2 WebMacro Context Tools

One powerful trait of WebMacro is that the WebContext can make available a small number of variables, called context tools , to all templates, and these tools are always included without the calling servlet having to place them within the context. The list of which tools to include is maintained in the WebMacro.properties file as WebContextTools. By default, WebMacro provides the following tools:

$Request

A reference to the servlet HttpServletRequest. Can be used to access the request's Accept header with $Request.Header.Accept or equivalently $Request.getHeader("Accept").

$Response

A reference to the servlet HttpServletResponse. Can be used to set the response's Content-Type with #set $Response.ContentType = "text/html".

$Session

A reference to the user's HttpSession. Can be used to retrieve a value from the session with $Session.Attribute.Count or equivalently $Session.getAttribute("Count").

$Form

A tool for accessing the request's form data. Can be used to retrieve the partnumber parameter as $Form.partnumber. Shorthand for $Request.getParameter("partnumber") or $Request.Parameter.partnumber.

$FormList

A tool for accessing the request's form data, when the form data has values with more than one value. Used in conjunction with the #foreach directive.

$Cookie

A tool for retrieving and setting cookies. Can be used to set a cookie with $Cookie.set("name", "value") or #set $Cookie.name = "value". Cookies are retrieved as $Cookie.get("name").Value or $Cookie.name.Value.

$CGI

A tool for accessing request information using CGI-style names. Can be used by template engineers familiar with CGI to access variables like the document root: $CGI.DOCUMENT_ROOT.

Additional context tools can be made available by simply writing a class that implements org.webmacro.ContextTool and adding the class to the WebContextTools list. One could write or download tools to do math, internationalization, database access, or even create HTML objects using ECS from the next section. In many ways, context tools behave for WebMacro like tag libraries behave for JSP.

Example 15-5 shows a simple context tool that performs integer arithmetic. This MathTool often comes in handy because the WebMacro template language has been so simplified that it doesn't include even basic arithmetic operations.[2]

[2] Although due to popular demand, arithmetic operations are being added and may be available by the time you read this.

Example 15-5. A Context Tool for Integer Arithmetic (A Complicated Calculator)
import org.webmacro.*; public class MathTool implements ContextTool {   /**     * A new tool object will be instantiated per-request by calling     * this method.  A ContextTool is effectively a factory used to     * create objects for use in templates.  Some tools may simply return     * themselves from this method; others may instantiate new objects     * to hold the per-request state.     */   public Object init(Context c) {     return this;   }   public static int add(int x, int y) {     return x + y;   }   public static int subtract(int x, int y) {     return x - y;   }   public static int multiply(int x, int y) {     return x * y;   }   public static int divide(int x, int y) {     return x / y;   }   public static int mod(int x, int y) {     return x % y;   }   public static boolean lessThan(int x, int y) {     return (x < y);   }   public static boolean greaterThan(int x, int y) {     return (x > y);   } }

With this tool added to the WebContextTools list (don't forget that step), all templates can perform basic math. For example, to print the year of a Date object requires adding 1900 to the Year property:

The current year is $Math.add($date.Year, 1900).


Last updated on 3/20/2003
Java Servlet Programming, 2nd Edition, © 2001 O'Reilly

< BACKCONTINUE >


Java servlet programming
Java Servlet Programming (Java Series)
ISBN: 0596000405
EAN: 2147483647
Year: 2000
Pages: 223

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net