Struts ActionForm简单理解
要想明確struts的控制流程以及它核心API的實(shí)現(xiàn)原理(比方?Action/DispatchAction/ActionForm的實(shí)現(xiàn)原理),玩轉(zhuǎn)struts1.2的關(guān)鍵就是可以玩轉(zhuǎn)?ActionForm。
ActionForm的應(yīng)用
1、——ActionForm的特性
1.創(chuàng)建一個form類必須繼承于四個父類中的一個,比方ActionForm、ValidatorForm。
2.一個form類中的每個屬性都將和頁面中form表單中的每個表單元素一一相應(yīng)
Example:
一個表單為:
<form>
?<input type="text" name="username"></input>
?<input type="password"name="password"></input>
?<input type="text" name="email"></input>?
</form>
一個與之相應(yīng)的form類
public class UserForm extends ActionForm{
??private String username;
??private String password;
??private String email;
??private String address;
??
??//以下省略getter和setter方法
}
一個引用了該form類的appAction:
<form-beans>
?<form-bean name="userForm"type="form.UserForm"></form-bean>
</form-beans>
<action-mappings>
<action path="/test" type="action.TestAction"name="userForm" attribute="uf" scope="request"></action>
</action-mappings>
3.在引用了form-bean的action中name屬性的值就是form-bean中name的值
4.這個userForm默認(rèn)會被放在session中,使用scope能夠指定存儲該form對象的地方
?
2、——普通HTML表單使用Form的工作原理
ActionServlet?對struts-config進(jìn)行解析時,當(dāng)解析到某個action中存在一個屬性name,那么ActionServlet中的 RequestProcessor就會依據(jù)該name的值找到相應(yīng)的form-bean然后創(chuàng)建一個相應(yīng)的form類實(shí)例,放在我們定義的存儲范圍中,當(dāng)表單提交到action相應(yīng)的appAction之前也就是到達(dá)FC的時候,FC會做下面事情:
1.依據(jù)路徑找到相應(yīng)的內(nèi)存中存放著的配置對象中的action
2.依據(jù)action中的attribute屬性,從session中得到一個相應(yīng)的form實(shí)例
3.該form實(shí)例調(diào)用reset方法對自己進(jìn)行清空
4.用表單中的值去填充該form實(shí)例
?
?
3、——Form與實(shí)體對象之間的關(guān)系
有的時候我們?yōu)榱朔奖銜讶〉降膄orm中的值直接復(fù)制到實(shí)體對象中去然后把實(shí)體對象再存儲到數(shù)據(jù)庫中,這樣給我們的編程帶來了非常多的方便,但前提是實(shí)體對象中須要拷貝的屬性,form中要拷貝過去的屬性,與form相應(yīng)的表單元素他們?nèi)弑仨氁灰?相應(yīng).這樣我們就能夠把表單中的值得到封裝到form中然后再把form中與實(shí)體對象中屬性同樣的值復(fù)制到實(shí)體對象中。
Example:
entity:
public class User{
?private String name;
?private String password;
?private double salary;
?private String address;
?//省略getter和setter方法
}
form:
public class UserForm{
?private String name;
?private String password;
?private String salary;
?//省略getter和setter方法
}
表單:
<form>
?<input type="text" name="name"></input>
?<input type="password"name="password"></input>
?<input type="text" name="salary"></input>
</form>
1.把表單中的值賦值給UserForm
2.把UserForm中的值復(fù)制到User對象中:
//以下這條語句是在action的某個方法中做的所以form直接能夠用
BeanUtils.copyProperties(user,form);
3.將user對象存放在數(shù)據(jù)庫中
總結(jié)
以上是生活随笔為你收集整理的Struts ActionForm简单理解的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 转译特殊字符
- 下一篇: Inspector a Progress