1. 程式人生 > >Struts2中迭代器的使用

Struts2中迭代器的使用

***show.jsp***
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv
="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title> </head> <body> <h1>User list</h1> <!-- 當使用了s:iterator之後,會將相應的迭代物件放置到CompoundRoot中 --> <!-- 當定義了var="u"之後,會將這個迭代的物件再在actionContext中存一份,ActionContext中的key就是u --> <s:iterator
value="#users" var="u" status="st">
<div <s:if test="#st.odd">style="background:#ff0"</s:if>> <s:property value="#u.id" /> --- <s:property value="username" /> --- <s:property value="nickname" /> --- <s:property
value="#st.odd" />
-- <s:property value="#st.last" /> --- <s:property value="#root[1].username" /> </div> <br/> </s:iterator> <!-- 當使用了s:iterator之後,會將相應的迭代物件放置到CompoundRoot中 因為不在actionContext中所以不需要# 預設訪問#root[0]的內容--> <s:iterator value="#users"> <s:property value="id" /> --- <s:property value="username" /> --- <s:property value="nickname" /> <br/> </s:iterator> <s:property value="username"/> <s:debug/> </body> </html>
***UserAction.java***
package org.zttc.itat.action;

import java.util.ArrayList;
import java.util.List;

import org.apache.struts2.ServletActionContext;
import org.zttc.itat.model.User;

import com.opensymphony.xwork2.ActionContext;


public class UserAction {
    private String username;
    private String password;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String addInput(){
        System.out.println(username+","+password);
        return "success";
    }

    public String add(){
        System.out.println("add");
        return "r_list";
    }

    public String list(){
        ActionContext.getContext().put("aaa", 12345);
        ActionContext.getContext().put("bbb", 23456);
        ActionContext.getContext().put("ccc", "abc");
        ServletActionContext.getRequest().setAttribute("ddd", "123");

        User u = new User("1","laozhang","老張");
        ActionContext.getContext().getValueStack().push(u);
        return "success";
    }
    public String show() {
        ActionContext.getContext().put("age",20);
        this.setUsername("老李");
        this.setPassword("123");
        List<User> users = new ArrayList<User>();
        users.add(new User("1","ts","唐僧"));
        users.add(new User("2","ss","沙僧"));
        users.add(new User("3","bj","八戒"));
        users.add(new User("4","wk","悟空"));
        ActionContext.getContext().put("users", users);
        return "success";
    }

}