I want the view to know what controller and what action were called to generate it. In fact, I want to do something like this in the view:
<script>
var controller = "${controllerName}";
var controllerAction = "${controllerAction}";
</script>
and, in a later included .js,
<script src="/public/script.js"></script>
... in this .js I want to have access to both variables:
if(controller == "UserController" && controllerAction == "Edit")
{
// ...
}
else
{
// ...
}
My question: what would be the best way to automatically pass those controller and action names to the view?
My controllers extend an abstract "BaseController", so I guess the best place to add those variables to the ModelAttribute would be there. I would prefere the concrete controllers to have nothing to do for those variables to be added. But how could the parent controller know the name of the child concrete controller and the name of the action?
I could check the StackTrace in BaseController, but I don't really like this solution...
Do you have a better solution to suggest?
Why can't you just get this information from your url? normally a url maps to a controller and action in Spring. In javascript why not just parse the url to get this info? If the problem is that the action is different depending on a post, get or header information then you can probably append this in the url as a parameter.
I found a solution.
Using Spring 3.1, I use those beans:
And in BaseInterceptor's postHandle() method, the "Object handler" becomes a HandlerMethod instance, which contains all the information I need! I then simply have to add this information to the ModelAndView object.