ComponentTagSupport和Component自定义struts标签

来源:互联网 发布:2016美容行业数据 编辑:程序博客网 时间:2024/06/07 01:06

首先说明一个大概的作用:
继承ComponentTagSupport类是为了获得标签中的属性值,并包装成Component对象。继承Component类是为了从Struts2中的ValueStack中获得相对应的值。

首先定义一个entity,为了简便,只定义一个属性。
Product类

package com.ghy.struts;public class Product {    private String content;    public String getContent() {        return content;    }    public void setContent(String content) {        this.content = content;    }}

tld文件(放到WEB-INF下)

<taglib>    <tlib-version>1.0</tlib-version>    <jsp-version>2.0</jsp-version>    <short-name>modelTag</short-name>    <uri>自己定义uri和jsp页面对应</uri>    <tag>        <description>        </description>        <name>product</name>        <tag-class>com.ghy.struts.ProductTag</tag-class>        <body-content>JSP</body-content>    </tag></taglib>

ProductTag类

package com.ghy.struts;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.apache.struts2.components.Component;import org.apache.struts2.views.jsp.ComponentTagSupport;import com.opensymphony.xwork2.util.ValueStack;public class ProductTag extends ComponentTagSupport{    @Override    public Component getBean(ValueStack arg0, HttpServletRequest arg1, HttpServletResponse arg2) {        // TODO Auto-generated method stub        return new ProductComponent(arg0);    }}

ProductComponent类

package com.ghy.struts;import java.io.Writer;import org.apache.struts2.components.Component;import com.opensymphony.xwork2.util.ValueStack;public class ProductComponent extends Component{    public ProductComponent(ValueStack stack) {        super(stack);        this.stack = stack;    }    @Override    public boolean start(Writer writer) {        // TODO Auto-generated method stub        Product product = new Product();        product.setContent("产品内容");        stack.set("product", product);        return super.start(writer);    }}

jsp页面

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%@taglib prefix="s" uri="/struts-tags"%><%@taglib prefix="t" uri="和tld页面的uri对应 "%><%    String path = request.getContextPath();    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE html><html><head>    <title>产品首页</title>    <meta charset=utf-8></head><body>    <t:product>    <h1>产品简介</h1>        <s:property value="product.content" />        </t:product></body></html>

完。

1 0
原创粉丝点击