struts2框架从数据库批量取得数据集并在前台页面循环显示

时间:2022-03-09 19:32:38

1.定义实体类

package bean;

public class book {
    
private String bookname;
private String bookwriter;
private int price;
private String pic;

public void setBookname(String bookname) {
    this.bookname = bookname;
}
public String getBookname() {
    return bookname;
}
public void setBookwriter(String bookwriter) {
    this.bookwriter = bookwriter;
}
public String getBookwriter() {
    return bookwriter;
}
public void setPrice(int price) {
    this.price = price;
}
public int getPrice() {
    return price;
}
public void setPic(String pic) {
    this.pic = pic;
}
public String getPic() {
    return pic;
}

}

 

 

2.action

package action;

import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import DAO.dao;
import bean.book;

import com.opensymphony.xwork2.ActionSupport;

public class display extends ActionSupport{
    private List<book> bk;
    private List<book> bk1=new ArrayList<book>();
    private ResultSet rs=null;
    
    public void setBk(List<book> bk) {
        this.bk = bk;
    }
    public List<book> getBk() {
        return bk;
    }
    
    public String execute()throws Exception
    {
        dao da =new dao();
        rs=da.displaydata();
        
        while(rs.next())
        {
        book bk2=new book();
        bk2.setBookname(rs.getString("bookname"));
        bk2.setBookwriter(rs.getString("bookwriter"));
        bk2.setPrice(rs.getInt("price"));
        bk2.setPic(rs.getString("pic"));
        bk1.add(bk2);
        
        }
        this.setBk(bk1);
        return "sucess";
    }
}
3.Struts.xml 配置

        <action name="display" class="action.display">
            <result name="sucess">
            /display.jsp
            </result>
       </action>

4.jsp显示

    <s:iterator value="bk">
书名:    <s:property value="bookname"/><br>
作者:    <s:property value="bookwriter"/><br>
价格:    <s:property value="price"/><br>
简介:    <s:property value="pic"/><br>
    <br><br><br><br>
    </s:iterator>