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 =)
This is a pretty old question. What you need to do is use Spring-Mobile to achieve this in a standard elegant manner
Update: look at spring-mobile
Original answer:
It would be pretty simple to create a custom ViewResolver
that resolves views based on the User-Agent
header.
null
, thus letting other resolvers resolve a view.Like @Bohzo and yourself already said spring-mobile is the way to go.
As of version 1.1 you can use the LiteDeviceDelegatingViewResolver to configure the type of behavior you're describing.
http://static.springsource.org/spring-mobile/docs/current/reference/html/device.html#device-aware-view-management
Spring Mobile includes AbstractDeviceDelegatingViewResolver, an abstract ViewResolver wrapper that delegates to another view resolver implementation, allowing for resolution of device specific view names without the need for a dedicated mapping to be defined for each view. A lightweight implementation is provided, which supports adjusting view names based on whether the calling device is normal, mobile, or tablet based.
Within your application, you can then create alternate views for normal, mobile or tablet devices, and given the proper configuration, Spring Mobile will adjust the view name to resolve to the correct one. This happens internally, without the need to add conditional logic through your controllers.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With