Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring MVC inject agent variable into model

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)?

like image 569
MichelReap Avatar asked Jul 31 '26 11:07

MichelReap


2 Answers

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.

like image 69
Martin Frey Avatar answered Aug 03 '26 05:08

Martin Frey


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.

like image 25
Michał Rybak Avatar answered Aug 03 '26 05:08

Michał Rybak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!