September 17, 2007

Waffle and JRuby: Accessing parameters and attributes from request, session and servlet context

In the last post I quickly explained how easy it is to access a component registered with Waffle from your JRuby based controllers. Now we need to understand how to access GET and POST parameters in order service a visitor's request. This is easily done through the parameters variable (also aliased as params) on your Ruby based Controllers. This variable is a simple Hash, so looking up parameter values from your Actions as easy as:
def example_one
foo = params['foo'] # request parameter
return "<h1>FOO: #{foo}</h1>"
end

Accessing Request, Session and ServletContext attributes

It might also be useful to access attribute values from either javax.servlet.ServletRequest, javax.servlet.http.HttpSession or javax.servlet.ServletContext. This is, as you should expect, very easy to do. But Waffle automatically wraps each of these as a Ruby Hash. This provides the correct Ruby "feel" when writing your Actions. The following code snippet give an example of how you can access attribute values from each of the 3 contexts:
def example_two
foo = params['foo'] # request parameter
fuu = request['fuu'] # request attribute
bar = session['bar'] # session attribute
baz = application['baz'] # servlet context attribute
return "<h1>FOO: #{foo} FUU: #{fuu} BAR: #{bar} BAZ: #{baz}</h1>"
end
Additionally, you can also call any of the Java methods these instances provide (you are NOT limited to methods exposed by Hash).

Auto-resolve values

Now those of you familiar with Waffle realize that Waffle provides a built-in means to auto-resolve a variables value. Waffle will search each of the following (in order) until the value is found, otherwise null (or in the case of JRuby nil) will be returned:
  1. HttpServletRequest Parameter (HttpServletRequest.getParameter("foo"))
  2. HttpServletRequest Attribute (HttpServletRequest.getAttribute("foo"))
  3. HttpSession Attribute (HttpSession.getAttribute("foo"))
  4. ServletContext Attribute (ServletContext.getAttribute("foo"))
  5. return nil

So with that in mind we can simplify the previous example down to one line. Waffle will attempt to resolve the value of any unknown variable through this means. The following shows the previous method simplified because it relies on Waffle auto resolving each value:
def example_three
return "<h1>FOO: #{foo} FUU: #{fuu} BAR: #{bar} BAZ: #{baz}</h1>"
end
In my next blog post I'll begin discussing how you can integrate JSPs or even RHTML with your applications.

1 comment:

Dave Hoover said...

Oooooo, deep magic!