利用struts2标签实现数据库信息绑定
1、准备一个数据访问对象(DAO),该类中有个一个方法返回一个List集合,集合中封装要绑定到下拉框中的数据。
public List findAll() { log.debug("finding all Collegetype instances"); try { String queryString = "from Collegetype"; return getHibernateTemplate().find(queryString); } catch (RuntimeException re) { log.error("find all failed", re); throw re; } }
2、在struts2的action中调用带方法并把list集合存储在request中,代码如下:
public String toAddCollege(){ List list=collegeTypeDAO.findAll(); ActionContext.getContext().put("collegeTypes", list); return "toAddCollege"; }
3、在页面中引入struts提供的标签库,如下:
<%@ taglib uri="/struts-tags" prefix="s" %>
4、在页面中使用<s:select>标签实现数据绑定
<s:select name="college.collegetype.id" headerKey="-1" headerValue="请选择一个用户角色" list="collegeTypes" listKey="id" listValue="name" required="true"></s:select>
注:headerKey和listKey是页面传递给action的实际值; headerValue和listValue是实际值对应的显示值,即我们在页面上看到的东西; list="roles",roles是在action中set()后传到页面的,可在跳转页面的方法中设置; name="user.R_ID",user是action中的一个属性bean,R_ID又是user的一个属性
还有一种是list直接在jsp页面中写,不用从action中读取
1)传递的实际值是字符串
<s:select name="isRecommend" list="#{'2':'全部','1':'推荐','0':'未推荐'}" value="'2'"/>
2)传递的实际值是int
<s:select name="isRecommend" list="#{2:'全部',1:'推荐',0:'未推荐'}" value="2"/>