自定义标签:在JSP页面中动态执行Spring Bean的方法

来源:互联网 发布:网络运维投标书 编辑:程序博客网 时间:2024/05/01 08:57

自定义标签:在JSP页面中动态执行Spring Bean的方法

     使用该自定义标签,可以在JSP页面中动态执行某个Spring Bean对象的一个方法,方法返回的结果存储在ValueStack中。该自定义标签在Spring2、Struts2、Hibernate3环境下测试通过。

一、java源代码

    1、ServiceTag源代码

Java代码

 

    2、ServiceParamTag源代码

Java代码

 

    3、公共方法源代码

Java代码

 <pre> 
 * 一定要在spring.xml中加上: 
 * &lt;bean id="SpringContextUtil " class="com.hmw.spring.SpringContextUtil" singleton="true" /&gt; 
 * 当对SpringContextUtil 实例时就自动设置applicationContext,以便后来可直接用applicationContext 
 * </pre> 

  1. package org.company.xxx;   
  2.   
  3. import org.springframework.beans.BeansException;    
  4. import org.springframework.context.ApplicationContext;    
  5. import org.springframework.context.ApplicationContextAware;    
  6.     /**   
  7.      *   
  8.      * 获取spring容器,以访问容器中定义的其他bean   
  9.      * @author lyltiger  
  10.      * @since MOSTsView 3.0 2009-11-16  
  11.      */  
  12. public class SpringContextUtil implements ApplicationContextAware {   
  13.   
  14.     // Spring应用上下文环境   
  15.     private static ApplicationContext applicationContext;   
  16.   
  17.     /**  
  18.      * 实现ApplicationContextAware接口的回调方法,设置上下文环境  
  19.      *   
  20.      * @param applicationContext  
  21.      */  
  22.     public void setApplicationContext(ApplicationContext applicationContext) {   
  23.         SpringContextUtil.applicationContext = applicationContext;   
  24.     }   
  25.   
  26.     /**  
  27.      * @return ApplicationContext  
  28.      */  
  29.     public static ApplicationContext getApplicationContext() {   
  30.         return applicationContext;   
  31.     }   
  32.   
  33.     /**  
  34.      * 获取对象  
  35.      * 这里重写了bean方法,起主要作用  
  36.      * @param name  
  37.      * @return Object 一个以所给名字注册的bean的实例  
  38.      * @throws BeansException  
  39.      */  
  40.     public static Object getBean(String name) throws BeansException {   
  41.         return applicationContext.getBean(name);   
  42.     }   
  43.   
  44. }  

二、tld文件源代码

Xml代码

 

三、范例

    1、java源代码

Java代码

    2、JSP页面源代码

Html代码
  1. <cjm:serviceBean beanName="roleService" methodName="getRole" id="result">  
  2.     <cjm:serviceParam name="roleId" value="ADMIN" type="java.lang.String"/>  
  3. </cjm:serviceBean>  
  4.   
  5. <s:property value="#result.roleName"/>  

原创粉丝点击