1


我需要你对过滤器使用的建议。只是想知道我在想什么是一种可能的好方法。
所以我的任务是使用 JSP、Spring MVC 2.5、javascript 等开发 5-6 个屏幕。
所有这些屏幕共享许多常见的数据元素,例如下拉列表等。
我正在考虑实现一个过滤器并在里面填充这些下拉值过滤器中的一个弹簧 ModelMap ,以便过滤器的 URL 模式下的每个屏幕都获取此数据。
这是一个正确的方法吗?

4

2 回答 2

2

我相信过滤器可以解决问题,但是我会远离这种方法。您也可以使用 Spring 的拦截器来做同样的事情,并且仍然利用 Spring 的特性,例如依赖注入、事务管理和 Spring Data 包。

在调度程序的配置中设置拦截器。

<mvc:interceptors>
    <mvc:interceptor>
       <mvc:mapping path="/**"/>
       <bean class="org.my.domain.interceptors.LookupHandlerInterceptor" />
    </mvc:interceptor>
</mvc:interceptors>

然后定义你的拦截器类:

public class LookupHandlerInterceptor extends HandlerInterceptorAdapter {

        @Autowired
        LookupLoaderApplicationListener loader;

        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {
             request.setAttribute("lookupList", loader.getCategories());
             return super.preHandle(request, response, handler);
        }
    }

这种方法将允许您利用您可能在应用程序中使用的其他 Spring 功能,例如您可能已设置的任何持久性。然后你可以在你的数据库中管理这个列表。

于 2013-03-08T19:01:39.617 回答
1

I think violating the principle of least surprise and hiding code that is critical to the correct function of a controller in a separate part of the application is not worth whatever bit of "magic"/cleverness is squeezed out of doing this.

Why hide the code that sets up the screens from future developers?

Just because they all share common reference data now, will they forever and for all time? As soon as the requirements for the different screens start to diverge, it gets ugly fast.

You basically have all the drawbacks of using inheritance instead of composition to make a controller, plus on top of that you can't even see the code from the controller. I would simply make a utility bean that does the common work, inject it on the controller, and write the one line @ModelAttribute method to call it. There will be much less mess when their individual requirements change in the future.

于 2013-03-08T19:10:44.283 回答