Question

I would like to take certain decissions on my views depending on the user-agent, but I don't want to do it with JavaScript.

So I decided to do it on the server side by reading the HttpServletRequest in my controller methods then inject the user agent into the model, and show the jsp accordingly using JSTL to check on the injected variable.

The thing is, I want to do this for all of my views (some of the decisions might be in the base Layout of all pages), but I don't want to go through all my controller methods and put the model.addAttrbiute() on every single one of them. Is there any way that I can make this variable available for all views?

I though about using @ModelAttribute but there I don't have access to the request information (or do I)?

Was it helpful?

Solution

Have you tried it? As far as i know "all" possible parameters that can be used on a requestmapping method can also be used on modelattribute methods. You can even chain these methods. I havent used httprequest yet myself. Give it a try.

Combine this with a class @ControllerAdvice and you will have it available in all models.

OTHER TIPS

You can use @ControllerAdvice annotation on class level, which will in result affect all controllers. Combine it with @ModelAttribute on method level and you'll get the expected result.

On accessing request information:
One way to do this is to save User-Agent value in session (when a first request is made) and then get it from session in method annotated with @ModelAttribute:

This way you'll have User-Agent value available in every view that is returned from any of your controllers.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top