在自定义的标签中,传递的是字符串,而不是我们真正需要的对象。
但是我们可以通过传递过去的字符串,从ValueStack中取得我们真正需要的对象。
例如:
1.下面是需要传递的对象类
public class Node implements Iterable<Node>,Serializable{
private static final long serialVersionUID = 1L;
private List<Node> nodes;//子节点
private String name;//节点名
private String css;//节点CSS
private String js;//节点onclick事件的js方法
public Node(String name){
this(name,"","");
}
public Node(String name,String css,String js){
this.setName(name);
this.setCss(css);
this.setJs(js);
nodes = new ArrayList<Node>();
}
......
}
2.在Action中把要传递的对象保存到ActionContext中
public class UserManageAction extends BaseAction {
@Override
public String execute() throws Exception {
Node topNode = userService.getTree();
ActionContext ctx = ActionContext.getContext();
//把要传递的对象,保存到ActionContext,key是“topNode”
ctx.put("topNode", topNode);
return super.execute();
}
......
}
3.在jsp中调用自己写的标签,把对象在ActionContext的key即“topNode”当参数传递
<bset:tree id="user_tree" node="%{topNode}"/>
4.tag类
public class TreeTag extends ComponentTagSupport {
private static final long serialVersionUID = 1L;
//在tag类中,接收到的是字符串“%{topNode}”
private String node;
@Override
public Component getBean(ValueStack arg0, HttpServletRequest arg1,
HttpServletResponse arg2) {
// TODO Auto-generated method stub
return new Tree(arg0);
}
@Override
protected void populateParams() {
super.populateParams();
Tree tree = (Tree)component;
tree.setNode(node);
}
public void setNode(String node) {
this.node = node;
}
public String getNode() {
return node;
}
}
5.Component类
public class Tree extends Component {
private String node;
public Tree(ValueStack stack) {
super(stack);
// TODO Auto-generated constructor stub
}
@Override
public boolean start(Writer writer) {
//解析从jsp中传递过来的字符串,是否带有%{和}.
if(node.startsWith("%{")&&node.endsWith("}")){
//取得key值,和之前在ActionContext的key一致
node = node.substring(2,node.length()-1);
//根据Key值,从ValueStack 中取得之前保存在ActionContext的对象
Node topNode = (Node)this.getStack().findValue(node);
try {
createTree(writer,topNode);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return super.start(writer);
}
public void setNode(String node) {
this.node = node;
}
public String getNode() {
return node;
}
......
}
这其实没有真正实现,直接在标签中传递对象。
而是利用,在Component 的ValueStack 对象中,包含着ActionContext,通过ActionContext来实现对象的传递。
如果大家有更好的方法,如能直接在标签中传递对象,麻烦告知一下啊。