Fork this page on GitHub

Jog

Using Scalate with JAXRS (Jersey) on Guice

Overview

Jog is a way of using Scalate with JAXRS (using the Jersey reference implementation) for the RESTful controller layer along with Guice for dependency injection

The quickest way to get up to speed on Jog is trying the getting started guide. Though rather than creating the jersey archetype, create the guice archetype. So follow the instructions to install the Scalate Tool then run

scalate create guice mygroup myartifactid

Dependency Injection

Jog uses the Guice Servlet approach to configuring your web application along with configuring Scalate and Jersey.

This lets you use dependency injection with Guice to configure your web application, the servlets and servlet filters and all the other resources and services used in your application without any icky XML configuration files and keeping a minimal simple web.xml.

If you try the getting started guide guide, then your running application will have a src/main/webapp/WEB-INF/web.xml file which contains the Guice Servlet initialisation configuration.

The ServletContextListener class configured in this part of the web.xml file

<listener>
  <listener-class>somePackage.ServletContextListener</listener-class>
</listener>

is the Scala class which creates the Guice Module that performs all the dependency injection for your application which is in the src/main/scala directory.

So if you need to inject any new services via Guice, just add a new @Provides annotated method to the ServletContextListener class. See the comments in the code for samples.

Scalate and JAXRS

Scalate operates as an implicit view provider in Jersey. So if create a JAXRS resource which is annotated with @ImplicitProduces then your Jog web application will look for Scalate templates to render a HTML.

This uses a naming convention where Scalate will look in your web application for the view to use based on the class name of the resource bean being rendered.

For example if you had a resource bean like this

package somePackage

import com.sun.jersey.api.view.ImplicitProduces
import javax.ws.rs.{GET, Path, Produces}

@ImplicitProduces(Array("text/html;qs=5"))
@Path("/foo")
@Produces(Array("text/xml", "application/json"))
class MyResource {

  @GET
  def get = new SomeDTO(this)
}

If you ask for the URI /foo this resource can be rendered using SomeDTO as XML/JSON, or if a web browser or REST client asks for media type text/html Scalate will look for the template called somePackage/MyResource.index.ssp or somePackage/MyResource.index.scaml.

You can have multiple HTML views of the resource by appending the view name. For example requesting /foo/edit would look for templates somePackage/MyResource.edit.ssp or somePackage/MyResource.edit.scaml.

See Also