How can group routes/actions into several classes?

28 views
Skip to first unread message

Anton Onischenko

unread,
Mar 25, 2011, 5:55:06 AM3/25/11
to scalatra-user
Is there a way to avoid having all routes/actions in a single class
but still having one entry point in web.xml? I would like to have my
actions logically grouped into several classes. Maybe someone can give
a clue in how it can be implemented?

Thanks.

Wille Faler

unread,
Mar 25, 2011, 6:04:57 AM3/25/11
to scalat...@googlegroups.com
Bowler does exactly this on top of Scalatra, if you look at the example further down the page here, you'll see that it is basically Scalatra route-definitions with a few minor cosmetic differences, but in a class instead of Servlet/Filter: http://bowlerframework.org/

Your Controllers are initialized in a Bootstrap class that you define that is instantiated from a ScalatraFilter/Servlet (Bowler does depend on Scalate and Lift-JSON in addition to Scalatra, but using these features is highly optional).

Leif Warner

unread,
Mar 25, 2011, 3:51:34 PM3/25/11
to scalatra-user
Those get(){}, post(){}, etc things are method calls in the
constructor of your Servlet.

So if you have some route,action pairs in some external structure, you
could loop over them to declare them all.
e.g. something like
for (route <- routes) {
get(route.path){route.action}
}

What I've done in the past, as I was declaring consistent restful
actions for all the different resources like default Rails routes, was
something like

for (resource <- resources) {
get(resource.name)( index(resource.Type) )
get(resource.name + "/:id") ( renderTemplate( resource.Type,
param("id") )
post(resource.name) { create new... }
put(resource.name + "/:id")( update... )

}

-Leif Warner

On Mar 25, 2:55 am, Anton Onischenko <anton.onishche...@gmail.com>
wrote:

Ross A. Baker

unread,
Mar 25, 2011, 4:52:51 PM3/25/11
to scalatra-user
Wille and Leif both present good options. A third choice is to take
advantage of Scala's trait system:

trait A { this: ScalatraKernel =>
// routes go here
}

trait B { this: ScalatraKernel =>
// more routes go here
}

// This will serve the routes in both A and B
class MyServlet extends ScalatraServlet with A with B

A fourth choice is to just create multiple ScalatraServlets and map
them to different paths in the same web.xml.

On Mar 25, 5:55 am, Anton Onischenko <anton.onishche...@gmail.com>
wrote:

Wille Faler

unread,
Mar 28, 2011, 6:09:40 AM3/28/11
to scalat...@googlegroups.com
I'd second Ross's solution, didn't think of that, very elegant!
Reply all
Reply to author
Forward
0 new messages