如何從後臺傳數據到前臺顯示

       這不是什麼很難的問題,只是我接觸java,struts2,hibernate不久,所以這裏遇到了很大問題,經過一天半的艱辛測試,終於實現了功能,所以肯定要留個腳印了。

目標:在後臺從java中查詢數據庫,查出結果集,然後通過struts2傳送的前臺,並在jsp頁面上顯示。

後臺代碼:

	private List<DeviceTypeAttribute> typeanames;
	public String list() throws Exception {
		AccessDB db = new AccessDB();//打開數據庫連接
		try {
			typeanames=new ArrayList<DeviceTypeAttribute>();
			List anames=db.query("from DeviceTypeAttribute where DeviceTypeID='"+deviceDeviceTypeId+"'");//查詢特定類型設備的屬性名稱
			if(anames!=null && anames.size()>0){
				for(int i=0;i<anames.size();i++){
					DeviceTypeAttribute aname=(DeviceTypeAttribute)anames.get(i);
					DeviceTypeAttribute anamevo=new DeviceTypeAttribute();
					anamevo.setDeviceTypeAttributeName(aname.getDeviceTypeAttributeName());
					typeanames.add(anamevo);//將結果進行封裝,得到結果集
					
				}
			}
			return SUCCESS;//返回到頁面
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return ERROR;
		} finally {
			// 釋放數據庫連接
			db.close();
		}
	}
	public List<DeviceTypeAttribute> getTypeanames() {
		return typeanames;
	}
	public void setTypeanames(List<DeviceTypeAttribute> typeanames) {
		this.typeanames = typeanames;
	}

上面的代碼不全,結果集DeviceTypeAttribute的結構肯定也要另外寫的。

前臺代碼:

<s:iterator value="typeanames">
	<td>						 
	<s:property value="%{DeviceTypeAttributeName}" />
	</td>
</s:iterator>
<s:if test="typeanames==null || typeanames.size() == 0">
<tfoot>
	<tr>
		<td colspan="8" class="noRecord">
			沒有相關記錄。
		</td>
	</tr>
</tfoot>
</s:if>

簡單寫一下,遍歷結果集即可。

錯誤原因:前前後後錯誤不下40次,感覺快要崩潰了,總是後臺能夠查到數據,但是前臺取不到。最後終於找到錯誤原因,關鍵在下面這段代碼,我以前寫的是:

	public List<DeviceTypeAttribute> getDeviceTypeanames() {
		return typeanames;
	}
	public void setDeviceTypeanames(List<DeviceTypeAttribute> typeanames) {
		this.typeanames = typeanames;
	}

這樣就取不到,set和get的名字必須和結果集的名稱一樣才能夠取到,正確代碼如下:

	public List<DeviceTypeAttribute> getTypeanames() {
		return typeanames;
	}
	public void setTypeanames(List<DeviceTypeAttribute> typeanames) {
		this.typeanames = typeanames;
	}

這個內容也算最常用的,現在終於掌握住了要點,嘿嘿,功夫不負有心人!



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章