`
raymond.chen
  • 浏览: 1425447 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

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

阅读更多

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

 

一、java源代码

    1、ServiceTag源代码

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;
	}
}

 

    2、ServiceParamTag源代码

public class ServiceParamTag extends BaseBodyTagSupport {
	private String name;
	private Object value;
	private String type;
	
	public void setName(String name) {
		this.name = name;
	}

	public void setValue(Object value) {
		this.value = value;
	}

	public void setType(String type) {
		this.type = type;
	}

	public int doEndTag() throws JspException {
		Tag parent = getParent();
		if(parent instanceof ServiceTag){
			Map p = new HashMap();
			p.put("paramName", name);
			p.put("paramValue", value);
			p.put("paramType", type);
			((ServiceTag)parent).params.add(p);
		}
		
		return EVAL_PAGE;
	}
}

 

    3、公共方法源代码

//参数类型数组
public static Class[] getParameterTypes(List params) throws Exception{
	Class[] c = new Class[params.size()];
	
	for(int i=0;i<params.size();i++){
		Map p = (Map)params.get(i);
		String type = (String)p.get("paramType");
		c[i] = Class.forName(type);
	}
	
	return c;
}

//参数值数组
public static Object[] getParameterValues(List params) throws Exception{
	Object[] o = new Object[params.size()];
	
	for(int i=0;i<params.size();i++){
		Map p = (Map)params.get(i);
		o[i] = p.get("paramValue");
	}
	
	return o;
}

 

二、tld文件源代码

<tag>
	<name>serviceBean</name>
	<tag-class>com.cjm.web.taglib.ServiceTag</tag-class>
	<body-content>JSP</body-content>
	<attribute>
		<name>beanName</name>
		<required>true</required>
		<rtexprvalue>true</rtexprvalue>
	</attribute>
	<attribute>
		<name>methodName</name>
		<required>true</required>
		<rtexprvalue>true</rtexprvalue>
	</attribute>
	<attribute>
		<name>id</name>
		<required>true</required>
		<rtexprvalue>true</rtexprvalue>
	</attribute>
</tag>

<tag>
	<name>serviceParam</name>
	<tag-class>com.cjm.web.taglib.ServiceParamTag</tag-class>
	<body-content>JSP</body-content>
	<attribute>
		<name>name</name>
		<required>true</required>
		<rtexprvalue>true</rtexprvalue>
	</attribute>
	<attribute>
		<name>value</name>
		<required>true</required>
		<rtexprvalue>true</rtexprvalue>
	</attribute>
	<attribute>
		<name>type</name>
		<required>true</required>
		<rtexprvalue>true</rtexprvalue>
	</attribute>
</tag>

 

三、范例

    1、java源代码

public class RoleService extends BaseService {
	private RoleDao roleDao;
	
	public RoleDao getRoleDao() {
		return roleDao;
	}

	public void setRoleDao(RoleDao roleDao) {
		this.roleDao = roleDao;
	}

	public Role getRole(String roleId){
		return (Role)get(Role.class, roleId);
	}
}

    2、JSP页面源代码

<cjm:serviceBean beanName="roleService" methodName="getRole" id="result">
	<cjm:serviceParam name="roleId" value="ADMIN" type="java.lang.String"/>
</cjm:serviceBean>

<s:property value="#result.roleName"/>

 

2
1
分享到:
评论
2 楼 itc10 2015-10-21  
//取得bean对象 
24.        try{ 
25.            bean = SpringContextUtil.getBean(beanName); 
26.        }catch(Exception ex){ 
27.            throw new JspException("get bean error: " + beanName); 
28.        } 


SpringContextUtil  ????,再加载applicationContext.xml一次??这在web项目会不会造成两个spring容器?,我也是醉了。
1 楼 dayang2001911 2008-10-07  
你也可以用ajax方式来实现吧,或者用dwr框架,直接就和spring集成的,可以调用bean的方法的啊,当然你这么做也应该可以了。

相关推荐

    JSP Struts之HTML标签库详解

    Struts 是一个经典的Java Web开发框架,它提供了一套丰富的标签库来简化JSP页面的编写,特别是对于处理用户输入和展示数据。其中,HTML标签库是Struts中非常重要的一部分,它专门用于创建与Struts框架交互的HTML输入...

    3.springSecurity源码分析1

    3. spring-security.xml配置:在这个文件中,我们通常会看到`&lt;http&gt;`标签的使用,它是SpringSecurity自定义的命名空间,允许我们声明各种安全策略。这些配置会被SpringSecurity的`SecurityNamespaceHandler`处理,它...

    Struts Spring Hibernate整合实践

    - 在 Struts 中,可以创建自定义标签来增强视图层的功能。例如,创建一个显示所有用户的标签,可以封装查询用户列表的逻辑,使JSP页面更简洁。 整合这三个框架的目的是提高开发效率,降低维护成本,通过Spring的...

    Spring-Reference_zh_CN(Spring中文参考手册)

    6.8.1. 在Spring中使用AspectJ来为domain object进行依赖注入 6.8.1.1. @Configurable object的单元测试 6.8.1.2. 多application context情况下的处理 6.8.2. Spring中其他的AspectJ切面 6.8.3. 使用Spring IoC来...

    jsp标签库文档说明

    本篇将详细介绍如何创建和使用自定义标签库,以及在实际应用中如何与Spring框架结合,实现数据的XML格式化展示。 首先,为了支持XML格式化的数据展示,我们需要在Spring配置文件中引入`XmlViewResolver`。如文件所...

    Struts2标签梳理

    当在Action类中使用`addActionError`方法添加错误后,可以在JSP页面上使用此标签显示: ```jsp &lt;s:actionerror/&gt; ``` 4. **actionmessage标签**:`&lt;s:actionmessage&gt;` 显示Action级别的普通消息或提示信息,与`...

    JSP Web应用程序开发.doc

    接着,详细阐述了JSP的基本语法,包括如何在页面中嵌入Java代码、声明变量和方法、以及使用指令和动作标签。 JSP的内置对象是其强大功能的一部分,如request、response、session、application等,它们提供了处理...

    Spring中文帮助文档

    6.8.1. 在Spring中使用AspectJ进行domain object的依赖注入 6.8.2. Spring中其他的AspectJ切面 6.8.3. 使用Spring IoC来配置AspectJ的切面 6.8.4. 在Spring应用中使用AspectJ加载时织入(LTW) 6.9. 更多资源 7...

    Spring Boot 学习笔记完整教程.docx

    - **配置 JSP**:在 Spring Boot 中启用对 JSP 的支持,设置视图解析器,理解 `addResourceHandlers` 和 `addViewControllers` 方法。 这个教程不仅适合初学者,也适合有一定经验的开发者,全面覆盖了 Spring Boot...

    struts1标签中文详解

    Struts1的标签设计旨在提高可读性和可维护性,减少JSP页面中的Java代码,使开发者能够更专注于业务逻辑。然而,随着技术的发展,Struts1已经逐渐被更新的框架,如Spring MVC或Play Framework所替代,但仍有很多遗留...

    最详细的Struts2标签.pdf

    Struts2是一个强大的MVC框架,它提供了丰富的标签库,使得开发者在JSP页面中能够更方便地操作数据和展示视图。以下是对Struts2中一些关键标签的详细解释: 1. **a 标签**:这个标签用于创建HTML超链接,与HTML的`...

    Spring in Action(第二版 中文高清版).part2

    16.4.3 在JSF页面中使用Spring Bean 16.4.4 在JSF中暴露应用程序环境 16.5 Spring中带有DWR的支持Ajax的应用程序 16.5.1 直接Web远程控制 16.5.2 访问Spring管理的Bean DWR 16.6 小结 附录A 装配Spring A.1 ...

    Spring in Action(第二版 中文高清版).part1

    16.4.3 在JSF页面中使用Spring Bean 16.4.4 在JSF中暴露应用程序环境 16.5 Spring中带有DWR的支持Ajax的应用程序 16.5.1 直接Web远程控制 16.5.2 访问Spring管理的Bean DWR 16.6 小结 附录A 装配Spring A.1 ...

    spring的使用方法

    在Spring MVC中,处理请求的基本单位是Controller接口,它定义了一个名为handleRequest的方法,返回一个ModelAndView对象,包含了视图名称和模型数据。虽然Controller接口很基础,但在实际应用中,通常会使用如...

    Spring 2.0 开发参考手册

    6.8.1. 在Spring中使用AspectJ来为domain object进行依赖注入 6.8.2. Spring中其他的AspectJ切面 6.8.3. 使用Spring IoC来配置AspectJ的切面 6.8.4. 在Spring应用中使用AspectJ Load-time weaving(LTW) 6.9. ...

    Spring MVC基础搭建方法

    3. **配置 ContextLoaderListener**:这个监听器会在应用启动时加载 Spring 的全局上下文(ApplicationContext),一般用于配置应用范围内的 Bean。同时,通过 `&lt;context-param&gt;` 指定配置文件的位置。 4. **创建 ...

    JavaEE企业级应用开发教程(Spring+SpringMVC+MyBatis)习题(2022).pdf

    18. Spring 与 MyBatis 的整合:Spring 与 MyBatis 框架的整合时,可以通过 Spring 的编程式事务管理,然后调用实例对象中的查询方法来执行 MyBatis 映射文件中的 SQL 语句。 19. Spring 的 JAR 包:Spring 开发所...

    javaee课后习题规格化整理

    15. **Spring配置**:Spring配置文件中的&lt;bean&gt;标签可以只使用id属性,但class属性通常是必须的。 16. **Spring对象获取**:Spring容器管理的对象可以通过多种方式获取,如依赖注入。 17. **Spring单元测试**:...

    Spring in Action(第2版)中文版

    16.4.3在jsf页面中使用springbean 16.4.4在jsf中暴露应用程序环境 16.5spring中带有dwr的支持ajax的应用程序 16.5.1直接web远程控制 16.5.2访问spring管理的beandwr 16.6小结 附录a装配spring a.1下载spring ...

    spring URL配置

    `&lt;bean id="methodNameResolver" class="org.springframework.web.servlet.mvc.multiaction.ParameterMethodNameResolver"&gt;`定义了`methodNameResolver`,它是一个Spring MVC中的多动作控制器方法名解析器。...

Global site tag (gtag.js) - Google Analytics