Spring MVC : What is the best way to pass the cont

2019-06-14 05:14发布

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?

2条回答
我命由我不由天
2楼-- · 2019-06-14 06:02

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.

查看更多
再贱就再见
3楼-- · 2019-06-14 06:11

I found a solution.

Using Spring 3.1, I use those beans:

<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping">
    <property name="interceptors">
        <bean id="baseInterceptor" class="xxx.xxx.xxx.BaseInterceptor" />
    </property>
</bean>

<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"></bean>

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.

public class BaseInterceptor extends HandlerInterceptorAdapter
{
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception 
    {
        HandlerMethod handlerMethod = (HandlerMethod)handler;

        modelAndView.addObject("controllerName", handlerMethod.getBean().getClass().getName());
        modelAndView.addObject("controllerAction", handlerMethod.getMethod().getName());
    }
}
查看更多
登录 后发表回答