如何从后台传数据到前台显示

如题所述

这不是什么很难的问题,只是我接触java,struts2,hibernate不久,所以这里遇到了很大问题,经过一天半的艰辛测试,终于实现了功能,所以肯定要留个脚印了。
目标:在后台从java中查询数据库,查出结果集,然后通过struts2传送的前台,并在jsp页面上显示。
后台代码:
[java] view plain copy
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的结构肯定也要另外写的。
前台代码:
[html] view plain copy
<span style="font-size:12px;"><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></span>
简单写一下,遍历结果集即可。
错误原因:前前后后错误不下40次,感觉快要崩溃了,总是后台能够查到数据,但是前台取不到。最后终于找到错误原因,关键在下面这段代码,我以前写的是:
[java] view plain copy
public List<DeviceTypeAttribute> getDeviceTypeanames() {
return typeanames;
}
public void setDeviceTypeanames(List<DeviceTypeAttribute> typeanames) {
this.typeanames = typeanames;
}
这样就取不到,set和get的名字必须和结果集的名称一样才能够取到,正确代码如下:
[java] view plain copy
public List<DeviceTypeAttribute> getTypeanames() {
return typeanames;
}
public void setTypeanames(List<DeviceTypeAttribute> typeanames) {
this.typeanames = typeanames;
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2016-03-10
视图渲染,把你的数据发到前端
相似回答