自定义标签中获取Spring Bean
2014-04-14 15:47
239 查看
public class ServiceTag extends BaseBodyTagSupport { private String beanName; private String methodName; private String id; public List params = new ArrayList(); public void setBeanName(String beanName) { this.beanName = beanName; } public void setMethodName(String methodName) { this.methodName = methodName; } public void setId(String id) { this.id = id; } public int doEndTag() throws JspException { Object bean = null; Method method = null; //取得bean对象 try{ bean = SpringContextUtil.getBean(beanName); }catch(Exception ex){ throw new JspException("get bean error: " + beanName); } //通过反射取得方法 if(bean != null){ try { method = bean.getClass().getMethod(methodName, TagUtil.getParameterTypes(params)); }catch(Exception e) { throw new JspException("get method error: " + beanName + "." + methodName); } }else{ throw new JspException("ServiceTag Error: bean [" + beanName + "] is null"); } //通过反射执行方法,得到结果 Object result = null; if(method != null){ try { result = method.invoke(bean, TagUtil.getParameterValues(params)); }catch(Exception e){ throw new JspException("method invoke error"); } } //将结果存储在ValueStack中 ValueStack vs = TagUtils.getStack(pageContext); vs.getContext().put(id, result); return EVAL_PAGE; } }
package org.search.api.util; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; /** * 获取spring容器,以访问容器中定义的其他bean * * <pre> * 一定要在spring.xml中加上: * <bean id='SpringContextUtil ' class='org.search.api.util.SpringContextUtil' singleton='true'/> * 当对SpringContextUtil 实例时就自动设置applicationContext,以便后来可直接用applicationContext * </pre> * * @author Administrator * */ public class SpringContextUtil implements ApplicationContextAware { private static ApplicationContext applicationContext; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { SpringContextUtil.applicationContext = applicationContext; } public static ApplicationContext getApplicationContext() { return applicationContext; } public static Object getBean(String name) throws BeansException { return applicationContext.getBean(name); } }
相关文章推荐
- 通过javascript获取HTML标签自定义属性
- 自定义函数标签:实现前台小数据的获取
- 获取Input标签自定义属性的值
- Javascript获取标签的自定义属性值
- 工作总结 获取html 标签 自定义属性值 根据html 自定义属性 获取 到标签
- 如何获取Input标签自定义属性的值
- 分享一个dedecms自定义获取上级栏目名称和链接的标签
- dedecms自定义获取上级栏目名称和链接的标签 (返回上级栏目按钮)
- 自定义freemarker标签实现TemplateDirectiveModel时获取request
- HTML标签自定义属性,并怎么获取
- s 点击a标签 获取a的自定义属性方法_javascript技巧
- 自定义标签:在JSP页面中动态执行Spring Bean的方法
- jquery的attr方法与ie7不兼容,js获取html标签自定义属性
- jquery获取自定义的标签属性的值
- DTCMS自定义标签:获取所有栏目以及不显示指定栏目
- JQUERY获取html标签自定义属性值或data值
- spring自定义标签及获取注释里面的值
- 如何获取Input标签自定义属性的值ie 8 9 10下取值
- Struts中自定义标签中获取值栈valuestack
- js 点击a标签 获取a的自定义属性