Tuesday, August 29, 2006

Spring MVC and Servlets

I've been using Spring MVC for a variety of web applications. It really does have a lot of nice advantages over Struts making it one of the better request-based frameworks (as opposed to the component based frameworks like Seam.) I came across an interesting use case that doesn't seem to be covered by Spring MVC.

I had a URL mapped to a controller. The URL needed to work for a variety of devices, not just
"full" web browsers like IE and Firefox. In particular it needed to work with a J2ME application. The controller needed to inspect the user agent of the HTTP request, build a model based on this information, and then forward to a view. The view would be different for different devices.

The wrinkle came when the developer working on the J2ME application told me he wanted the view to output a binary data stream. This could be done in a JSP, but is more suited to using a servlet. So I needed to configure a view in Spring MVC that was a servlet.

Spring MVC includes many view implementations. Several JSP-variants, and many other specialized views for working with various technologies such as Jasper Reports, Free Market, POI, PDF, etc. But nothing for a user built servlet like the one I needed to forward to. Seems like kind of a hole in Spring MVC.

Turns out it is not too hard to work around. The key is using the "forward:" prefix. Simply append this to the URL path specified in your servlet mapping, and it will short-circuit the Spring view lookup and forward directly to the desired servlet. So for example, if in your web.xml you had specified "/myServlet" as the mapping to your servlet, then having your controller return something like new ModelAndView("forward:/myServlet", "myModel", model) would forward to your servlet, and allow you to retrieve the model you had built in your controller using a simple request.getAttribute("myModel").

So it was easy to work around, but it still seems like Spring should have a servlet view. Maybe I will try to submit one to them...



technorati tags:,



Blogged with Flock

4 comments:

SomeOnehere said...

"Mostly technical and political,the stuff that bores everyone"

pal,you really wanna tell you're so much different than others..and I think it's too cliche:D

Anonymous said...

Thank you! I was wondering how to use it with servlets! Great!

Rajapriya R said...

great blog to read

job oriented java training | java training course contents | java training topics | best java j2ee training institute in chennai

for IT the said...

Interesting Article

Spring online training Spring online training Spring Hibernate online training Spring Hibernate online training

spring training in chennai spring hibernate training in chennai