0

Let's say I want to do the same thing the Masterpage's code behind does on ASP.NET side. I'm currently learning Spring MVC and Im using JSP for my views. I know for the JSP side, everytime I create a page I include header.jsp and footer.jsp.

Lets say I have this var in my header.jsp ${ItemsQty} I would have to tho this in all controllers request mappings to get the value inserted.

model.addAttribute("ItemsQty", ItemsServices.count());

What's the correct way to set this value? adding the attribute in all controllers, all request methods?

Regards.

4

2 回答 2

0

What's the correct way to set this value? adding the attribute in all controllers, all request methods?

No. These attributes are session scoped attributes. Session scoped attributes are specified in Spring MVC using @SessionAttributes. So in your case it would be

@SessionAttributes({"ItemsQty"})

So the first time you add "ItemsQty" to the model, it will stay there (across multiple requests) until SessionStatus.setComplete() is called.

于 2013-08-02T19:37:50.903 回答
0

You could create an interceptor that adds the attribute to the modelmap. Interceptors can be mapped to any URL you like.

<mvc:annotation-driven>
    <mvc:interceptors>
        <mvc:mapping path="/items/**" />
        <bean="my.package.items.ItemsInterceptor"/>
    </mvc:interceptors>
</mvc:annotation-driven>

When the url matches mapping /items/** this interceptor will add the attribute to the modelmap after the handler is called.

class ItemsInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private ItemsServices service;

    public void postHandle(
                HttpServletRequest request,
                HttpServletResponse response,
                Object handler,
                ModelAndView modelAndView) 
                throws Exception {

        if (modelAndView != null) {
            modelAndView.addObject("ItemsQty", service.count());
        }
    }
}
于 2013-08-02T23:30:24.987 回答