在JSP中自动装配Spring Beans的最简洁方法是什么? [英] What is the cleanest way to autowire Spring Beans in a JSP?

查看:201
本文介绍了在JSP中自动装配Spring Beans的最简洁方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们目前正在为一个旧的webapp添加一些新功能,这个旧的webapp只使用了JSP而没有任何框架。我们最近添加了Spring,我们希望在修改后的JSP中自动装配bean,而不是重写所有内容以使用SpringMVC,Struts2或Tapestry5。

We're currently adding some new features to an old webapp which was using only JSP without any framework for the front. We have added Spring recently, and we would like to autowire our beans in our modified JSP, while not rewriting everything to use SpringMVC, Struts2 or Tapestry5.

我们正在使用按类型自动装配,因此它导致在JSP中获得这样的代码,而以前获取Web应用程序上下文(作为wap):

We're using autowiring by type, so it leads to get some code like this in the JSP, while previously getting the web application context ( as "wap") :

MyDao myDao = (MyDao) wap.getBeansOfType(MyDao.class).values().toArray()[0];

我们不想使用这样的代码,而是直接在我们的JSP中自动注入我们的bean将在使用@Autowired注释的业务bean中。

We would like not to use such a code but rather automagically inject our beans directly in our JSPs as we would in a business bean using @Autowired annotation.

事实上,我们正在寻找在JSP中注入bean的最简洁方法。你用什么?

In fact we're looking to the cleanest ways to inject our beans in our JSPs. What do you use ?

推荐答案

你可以使用Spring的 ContextExposingHttpServletRequest

You can use Spring's ContextExposingHttpServletRequest:


HttpServletRequest装饰器,
使得给定的
WebApplicationContext中的所有Spring bean都可以作为
请求属性访问,一旦属性获得
,通过lazy
检查访问。

HttpServletRequest decorator that makes all Spring beans in a given WebApplicationContext accessible as request attributes, through lazy checking once an attribute gets accessed.

这将要求您的控制器代码包装原始的 HttpServletRequest in a ContextExposingHttpServletRequest ,然后将 转发给JSP。它可以暴露特定的命名bean,也可以暴露上下文中的每个bean。

This would require your controller code to wrap the original HttpServletRequest in a ContextExposingHttpServletRequest, and then forward that to the JSP. It can either expose specific named beans, or every bean in the context.

当然,这只是将问题从JSP转移到控制器代码,但这可能是一个更容易管理的问题。

Of course, this just shifts the problem from your JSPs to your controller code, but that's perhaps a more manageable problem.

这篇关于在JSP中自动装配Spring Beans的最简洁方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆