2016年6月20日 星期一

前端取資料庫的 method (DWR 二)

※vo

public class Chess {
    private Long id;
    private String name;
    private Date date;
    // setter/getter...
}


※interface和Impl

public boolean save(Chess chess);
public Chess getChess(Long id);
public List<Chess> getAllChess();
    
    
    
@Override
public boolean save(Chess chess) {
    System.out.println("新增成功!");
    return true;
}
    
@Override
public Chess getChess(Long id) {
    Chess chess = new Chess();
    chess.setId(id);
    chess.setName("象棋");
    chess.setDate(new Date());
    return chess;
}
    
@Override
public List<Chess> getAllChess() {
    List<Chess> chList = new ArrayList<>();
    for (long i = 1; i < 4; i++) {
        Chess chess = new Chess();
        chess.setId(i);
        if (i == 1) {
            chess.setName("象棋");
        } else if (i == 2) {
            chess.setName("跳棋");
        } else if (i == 3) {
            chess.setName("五子棋");
        }
        try {
            chess.setDate(new SimpleDateFormat("yyyyMMdd").parse("2010061" + i));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        chList.add(chess);
    }
    return chList;
}

※模擬資料庫


※dwr.xml

<dwr>
    <allow>
        <create creator="new" javascript="dao">
            <param name="class" value="dao.impl.DaoImpl" />
        </create>
        <convert match="vo.Chess" converter="bean" javascript="ch" />
    </allow>
</dwr>

※bean不能亂打,這裡可參考官網



※index.html

var bean = {
    id : 100,
    name : "象棋",
    date : new Date()
};
    
//     dao.save(bean, saveCallback);
//     function saveCallback(rtn){
//         document.getElementById('sp1').innerHTML = rtn;
//     }
    
dao.save(bean, {
    callback : function saveCallback(rtn){
        document.getElementById('sp1').innerHTML = rtn;
    }
});
    
dao.getChess(100, {
    callback : function getChessCallback(rtn){
        document.getElementById('sp2').innerHTML = 
            rtn.id + "<br />" + 
            rtn.name + "<br />" + 
            rtn.date;
    }
});
    
dao.getAllChess({
    callback : function getgetAllChessCallback(rtnList){
        var sp3 = document.getElementById('sp3');
        for(var i=0; i<rtnList.length; i++){
            var temp = document.createElement('temp');
            temp.appendChild(document.createTextNode(
                rtnList[i].id + ", " + 
                rtnList[i].name + ", " + 
                rtnList[i].date
            ));
            sp3.appendChild(temp);
            sp3.appendChild(document.createElement("br"));
        }
    }
});
----------
<h1 id="sp1"></h1>
<h2 id="sp2"></h2>
<h3 id="sp3"></h3>



上一篇的xxx,這裡已經改dao了,要注意,先設定dwr.xml,然後debug=true確定有看到再寫



這次的專案圖:

沒有留言:

張貼留言