日期:2014-05-16  浏览次数:20508 次

[实用技巧] jsp页面直接调用spring中定义的Bean的属性方法
    blog迁移至:http://www.micmiu.com

    也许你会问:为什么我要在页面里调用bean里的方法呢?请你耐心看下去,希望对你有帮助。
   1.在项目中经常会遇到动态下拉框的情况,比如角色列表、部门列表、分类....,当然你也可以选择把这些变量request、session或者application 但是这就涉及到何时放入变量、何时更新等问题,同时会占用容器的内存。特别是在查询条件的列表,运用下面的方法<ct:call/>再配合之前有一篇文章中的htmlx 标签就能非常好的解决此问题。
   2.我们经常会遇到用户id关联到其他表比如:消息表,作为消息的创建人,我们在展现消息表时,可以用下面介绍的方法在页面得到Map<userId,userName>,配合el表达式就能显示创建人的姓名,并不需要我们去关联查询。又比如我们经常会遇到给出用户id,显示用户本身的详细信息,同样我们可以用下面介绍的方法<ct:call/>结合jstl或el表达式就能取得用户这个对象来完成此需求。
   这里举了几个简单的例子,基于上面的情况我们才需要这样的方法,下面就对这个方法的整个步骤进行详细的描述:

   对于在spring xml配置文件中的bean里的属性方法,如果符合Java Bean规范,直接用EL表达式调用,例如srpingctx.userAccountService.userList 这个代表调用userAccountService中的方法getUserList();
   如果不符合Java Bean规范(不是getXxxxx()或者isXxxx())或者带有参数的方法,可以采用taglib标签
<ct:call object="beanName" method="xxx" param1="p1" param2="p2" return="RT_VAR" />此标签lib见附件
其中beanName对应于spring中定义的名字,xxx对应于beanName中定义的方法,如果xxx方法没有参数,则param1、param2...等都省略,调用的结果保存在return定义的变量名RT_VAR中,以后可以用EL表达:$(RT_VAR)直接访问.
 
  1.需要写一个类把spring context中定义的bean放在web application中
/**
 * 将spring context 中定义的bean放到Web的Application中.
 */
public class SpringCtxLoader extends WebApplicationObjectSupport {
    /**
     * Logger for this class
     */
    private static final Logger logger = Logger
            .getLogger(CodeTableLoader.class);
    /**
     * Web application 中的常量集合Map的名字.
     */
    private static final String SPRING_CONTEXT = "springctx";
    /**
     * initialize application context .
     */
    @SuppressWarnings("unchecked")
    protected void initApplicationContext() {
        try {
            final WebApplicationContext ctx = this.getWebApplicationContext();
            HashMap springServices = new HashMap() {
            private static final long serialVersionUID = -1759893921358235848L;

                public Object get(Object key) {
                    return ctx.getBean((String) key);
                };
                public boolean containsKey(Object key) {
                    return true;
                }
            };
            logger.info("load code table (spring  beans");
            // 放入到Web全局变量中,供页面使用.
            this.getServletContext().setAttribute(SPRING_CONTEXT,
                    springServices);
        } catch (IllegalStateException e) {
            logger.warn("not web app application context ,can't be load "
                    + e.getLocalizedMessage());
        }
    }
}

  2.spring 配置文件如下:(只显示本文相关的一些配置)
<!-- web application 全局常量列表 对象 -->
	<bean name="springCtxLoader" class="utils.SpringCtxLoader"
		lazy-init="false">
	</bean>

<!-- UserAccountService 事务管理 -->
	<bean name="userAccountService" parent="baseTransactionProxy">
		<property name="target">
			<bean class="service.UserAccountService">
				<property name="sessionFactory" ref="sessionFactory" />
			</bean>
		</property>
	</bean>


3.别忘了在jsp页面里引入标签:
<%@ taglib prefix="ct" uri="http://devsphere.com/articles/calltag/CallTag.tld"%>

具体页面的引用例子:
<ct:call object="userAccountService" method="getUserList" return="USER_LIST" />
所有的用户列表:<br>
<c:forEach var="vo" items="${USER_LIST}">
        用户ID:${vo.userID},姓名:${vo.userName}<br>
</c:forEach>

<ct:call object="userAccountService" method="getUserMapByRole" param1="admin" return="USER_LIST" />
遍历管理员列表:<br>
<c:forEach var="vo" items="${USER_LIST}">
        用户ID:${vo.key},姓名:${vo.value}<br>
</c:forEach