Friday, January 23, 2009

Spring Web MVC registering multiple controllers

I've recently been working on an OGC Sensor Observation Service (SOS) and wanted to split out some of the request mapping for different underlying data sources into separate controllers.

So for example I may have a separate controller for each SOS that is instantiated and which may have different presentations and models to support that view. It wasn't entirely obvious how to 'register' separate controllers into one web app using the Spring servlet config files and web.xml so thought I'd post an example. Note I am using Spring 2.5.x at the time of writing this post and using an annotation based controller.

First, we need to setup our web.xml file to register the Spring dispatcher servlet with the webapp and map which incoming URL requests will be handled by the Spring dispatcher. In the example below I've named the Spring DispatcherServlet sensorObsImpl and registered to incoming URL request /osmcObsService and /nosaObsService to the dispatcher.

Next we need to set-up the WebApplicationContext configuration file for Spring. This file has the same name as your dispatcher servlet with the addition of -servlet.xml extension, so in our case we will have a sensorObsImpl-servlet.xml file. This file sits in the same directory as web.xml. In our file we'll register two controllers one for our OSMC project and one for our NOSA project. Since we are going to leverage Spring's support of annotation based programming we'll begin by enabling auto detection of our annotated controllers by adding component scanning to our config file, followed by defining our to controller beans.

Now our controllers are registered with the dispatcher servlet and we can begin to handle incoming request params with the addition of some annotated methods in our controller classes. In our example below incoming URL requests like /nosaObsService?request=sosInitialize will map to the NosaObsController and be handled by the sosInitialize method.

@Controller
@RequestMapping("/nosaObsService")
public class NosaObsController {

@RequestMapping(params = "request=sosInitialize")
public ModelAndView sosInitialize(@RequestParam("request") String cmd){
.....
}

}


For more information check out the Spring docs at :
http://static.springframework.org/spring/docs/2.5.x/reference/mvc.html

2 comments:

Anonymous said...

Hello, I develop a complete and "different" GIS web portal using Spring Web MVC. I use the following APIS: Spring, Hibernate, JTS, DWR, Openlayers, etc, etc. You can view in http://pv2.homelinux.com
Regards.

Anonymous said...
This comment has been removed by a blog administrator.