這也是個開源的標簽庫^_^,因為老外總是很專業些寫了很多好東西,可是我基本上是和他們相反,即沒有時間也比較懶得。Struts-layout是一個用來擴充Struts的html標簽的作用的,我以前寫過(blog里)了怎么安裝使用的,這里就不說了。
1.這次我們先看JSP的結構:
兩個select,其中第二個是<layout:optionsDependent/>它的dependsFrom的屬性需要和上面的那個select的property一致。countries是在request域的一個collection,而cities是countries的一個屬性,但是類型也是collection。
<head>
<script src="/WebSample/config/javascript.js"></script>
</head>
<body>
<html:form action="/country.do">
<layout:select key="Country" property="countryId">
<layout:option value=""/>
<layout:options collection="countries" property="countryId" labelProperty="name" sourceOf="cityId"/>
</layout:select>
<layout:select key="City" property="cityId">
<layout:optionsDependent collection="cities" property="cityId" labelProperty="cityName" dependsFrom="countryId"/>
</layout:select>
<html:submit /><html:reset />
</html:form>
</body>
2.Action:你需要Action來初始化countries,
這樣你基本上就好了,夠簡單吧!下面還有兩個類的結構就是Country類和CityBean類:
public ActionForward execute(ActionMapping mapping,ActionForm form,HttpServletRequest request,HttpServletResponse response) {
List countries = new ArrayList();
for(int i = 0 ;i< 10 ;i++){
Country c = new Country();
c.setCountryId(new Integer(i));
c.setName("country"+i);
for(int j = 0;j< 5 ;j++){
c.addCity("city"+i+j,new Integer(i*10+j));
}
countries.add(c);
}
request.setAttribute("countries",countries);
return mapping.findForward("success");
}
Country類:3個如下屬性,外加Setter/Getter方法。
private String name;
private List cities = new ArrayList();
private Integer countryId;
CityBean類:2個如下屬性,外加Setter/Getter方法。
private Integer cityId;
private String cityName;
這些東西你當然還可以和數據庫結合起來使用,或是和XML文件結合起來使用?;旧弦粋€應用最要需要考慮好
類似Country類這個結構就可以了。
這個標簽的方法是把所有的數據都會寫入到html文件中,并寫入相應的JavaScript,你可以查看源碼。
<script>var countries = new Array();
countries[0] = new Object();
countries[0].value = "0";
countries[0].cities = new Array();
countries[0].cities[0] = new Object();
countries[0].cities[0].value = "0";
countries[0].cities[0].label = "city00";
countries[0].cities[1] = new Object();
countries[0].cities[1].value = "1";
countries[0].cities[1].label = "city01";
countries[0].cities[2] = new Object();
countries[0].cities[2].value = "2";
countries[0].cities[2].label = "city02";
countries[0].cities[3] = new Object();
countries[0].cities[3].value = "3";
countries[0].cities[3].label = "city03";
countries[0].cities[4] = new Object();
countries[0].cities[4].value = "4";
countries[0].cities[4].label = "city04"
.....
</script>
個人總結,水平有限。主要是最近在論壇里看到不少關于這方面的問題,然后有沒有最后的答案,所以借助開源標簽可以做到通用性,希望對您有所幫助。