views:

89

answers:

3

Hi All

I was wondering if someone has already solved this. I have a SpringMVC app and we are adding support to WebKit type mobiles (iPhone and Android basically) so I was wondering someone has found an elegant way of defining specific views depending on the client that sent the request.

I know that a simple if in a Controller implementation can do the trick, but I'm looking for something more flexible/elegant (a specific ViewResolver implementation, or an interceptor maybe).

Help will be greatly appreciated... as always =)

+4  A: 

It would be pretty simple to create a custom ViewResolver that resolves views based on the User-Agent header.

  • here is a list of mobile user agents. Check the header against it, and resolve a mobile view.
  • if the user-agent is not a mobile, then return null, thus letting other resolvers resolve a view.
  • make sure your resolvers are defined (in the spring xml) in the proper order, so that the mobile resolver is consulted first.
Bozho
Ok, just one concern about this... Do I still have access to the HTTP request on the ViewResolver, If so, how do I access it without specifically passing it on each and every Controller?
Chepech
You can get the request from `RequestAtrributesHolder` (cast the attributes to `ServletRequestAttributes`)
Bozho
Yep, but that can only be done at Controller level, ViewResolver no longer get the HTTPServletRequest unless you pass it in the model, which is something that may not be desirable.
Chepech
@Chepech so you say there is nothing in `RequestAttributeHolder` in the ViewResolver? That's surprising.
Bozho
No, it works but Its kind of dirty
Chepech
it's not :) The RequestAttributeHolder is a perfectly valid class
Bozho
+1  A: 

I think this is a good idea.

I created a JIRA issue for this.

James Earl Douglas
I read it an I think you expressed it better than I did =)
Chepech
A: 

Ok I found a more specific answer. There is a problem with the solution that Bozho proposed. the fact that the ViewResolvers no longer have access to the HttpServletRequest. There is a way to access the request but its kind of dirty IMHO.

So that said, this is a very elegant and easy to implement solution. Basicly it involves a custom ViewResolver (as Bozho proposed) but it adds an handlerInterceptor that adds the User-Agent to the model so you no longer have to add it manually.

Chepech