struts2 自定义tag标签

在项目中可能有很多相同的jsp页面表示功能,这时可以使用自定义的tag进行定义,渐少重复的工作量便于日后维护!

下面就基于struts2进行自定义标签的定义与实现:

首先:自定义类MyTag继承struts2的Component

package cookielogin;

import java.io.IOException;
import java.io.Writer;

import org.apache.struts2.components.Component;

import com.opensymphony.xwork2.util.ValueStack;

public class MyTag extends Component {
	private ValueStack stack;
	private String text;
	private String name;
	private String defaultValue;

	@Override
	public boolean start(Writer writer) {
		//这里进行页面的输出
		try {
			writer.write("

" + this.text + "

"); writer.write(""); } catch (IOException e) { e.printStackTrace(); } return super.start(writer); } public MyTag(ValueStack stack) { super(stack); this.stack = stack; } public ValueStack getStack() { return stack; } public void setStack(ValueStack stack) { this.stack = stack; } public String getText() { return text; } public void setText(String text) { this.text = text; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDefaultValue() { return defaultValue; } public void setDefaultValue(String defaultValue) { this.defaultValue = defaultValue; } }

2:指定标签类MyTagSupport继承ComponentTagSupport

package cookielogin;

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 MyTagSupport extends ComponentTagSupport {

	private static final long serialVersionUID = 3586338980857274359L;

	String name;
	String text;

	@Override
	public Component getBean(ValueStack stack, HttpServletRequest req,
			HttpServletResponse res) {
		return new MyTag(stack);
	}

	@Override
	// 设置bean值
	protected void populateParams() {
		System.out.println("开始设置参数!populateParams");
		MyTag tag = (MyTag) getComponent();
		tag.setName(name);
		tag.setText(text);
		tag.setDefaultValue("我就是默认值!咋滴!!");
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getText() {
		return text;
	}

	public void setText(String text) {
		this.text = text;
	}

}

java代码完成后,进行配置文件的编写,在WEB-INF/tlds 新建自定义文件tags-custom.tld






	2.0
	1.2
	ctags
	http://www.cml.com/tags-custom
	
	This is custom tag.

]]>
myTag cookielogin.MyTagSupport JSP text true name true defaultValue false false


前提基础工作完成后,在页面引用:

<%@taglib prefix="d" uri="http://www.cml.com/tags-custom"%>
使用:


访问页面后出现:

struts2 自定义tag标签_第1张图片

基于struts2的自定义标签实现完毕!虽然功能很简单,但是基本功能已经实现,可以根据项目的实际需要进行编辑!



你可能感兴趣的:(工作,工作)