tobik
tobik

Reputation: 7198

Spring MVC - how to pass data from filter to controller

I use Spring MVC in my web application. For every request I'd like to prepare the environment, for example load some data from the datastore and save it so every controller could access that information. I assume that's what filters are for (among other things). I can attach an information to the request variable in a filter, but how do I access it from the controller? Or is there a generally better way to do this?

Upvotes: 1

Views: 6432

Answers (3)

Japan Trivedi
Japan Trivedi

Reputation: 4483

I think your problem at the moment is how to get the data set in request inside your filter( already done by you) and then accessing it inside the hamdlerMapping method of your controller( you want to achieve).

I agree with both the previous answers but if you have decided to do it this way only then I think you should follow my answer.

In the handler method you have mapped your request to in your controller you can have a parameter in method signature for HttpServletRequest request and it will contain the request parameter you have set in your filter. And you can get that from this request object in your controller.

Hope this helps you. Cheers.

Upvotes: 2

storm_buster
storm_buster

Reputation: 7568

@duffymo is right, but if you really want to do that I suggest you to use interceptor http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/mvc.html#mvc-handlermapping-interceptor

Upvotes: 0

duffymo
duffymo

Reputation: 308948

I don't see why this is a good thing to do, filter or no.

If you truly have read-only data that every controller needs, I think a caching solution that is loaded on startup is a better idea. I wouldn't do that with a filter, and I wouldn't burden every single request with such a thing. Once it's done, why keep repeating the action?

Upvotes: 2

Related Questions