所謂modeldriven,意思是直接把實體類當成頁面資料的收集物件。比如,有實體類user如下:
packagecn.com.leadfar.struts2.actions;
public
classuser
public
voidsetusername(string username)
publicstring getpassword()
public
voidsetpassword(string password)
public
intgetage()
public
voidsetage(intage)
publicstring getaddress()
public
voidsetaddress(string address)
public
intgetid()
public
voidsetid(intid) }
假如要寫乙個action,用來新增user。
第一種做法是直接在action中定義所有需要的屬性,然後在jsp中直接用屬性名稱來提交資料:
useraction:
public
classuseraction
public
intgetid()
public
voidsetid(intid)
publicstring getusername()
public
voidsetusername(string username)
publicstring getpassword()
public
voidsetpassword(string password)
public
intgetage()
public
voidsetage(intage)
publicstring getaddress()
public
voidsetaddress(string address) }
add_input.jsp:
<
form
action
="test/user.action"
method
="post"
>
<
input
type
="hidden"
name
="method:add"
>
username:<
input
type
="text"
name
="username"
>
<
br/>
password:<
input
type
="text"
name
="password"
>
<
br/>
age:<
input
type
="text"
name
="age"
>
<
br/>
address:<
input
type
="text"
name
="address"
>
<
br/>
<
input
type
="submit"
name
="submit"
value="
新增使用者
">
form
>
<
br/>
上述做法不好之處是:如果實體類的屬性非常多,那麼action中也要定義相同的屬性。
第二種做法是將user物件定義到useraction中,然後在jsp中通過user屬性來給user賦值:
useraction:
public
classuseraction
publicuser getuser()
public
voidsetuser(user user) }
add_input.jsp:
<
form
action
="test/user.action"
method
="post"
>
<
input
type
="hidden"
name
="method:add"
>
username:<
input
type
="text"
name
="user.username"
>
<
br/>
password:<
input
type
="text"
name
="user.password"
>
<
br/>
age:<
input
type
="text"
name
="user.age"
>
<
br/>
address:<
input
type
="text"
name
="user.address"
>
<
br/>
<
input
type
="submit"
name
="submit"
value="
新增使用者
">
form
>
<
br/>
這種做法不好的地方是:jsp頁面上表單域中的命名變得太長
第三種做法是利用modeldriven機制,讓useraction實現乙個modeldriven介面,同時實現介面中的方法:getmodel()。如下所示:
public
classuseractionimplementsmodeldriven
returnuser; }
publicstring add()
publicuser getuser()
public
voidsetuser(user user) }
jsp的**如下:
<
form
action
="test/user.action"
method
="post"
>
<
input
type
="hidden"
name
="method:add"
>
username:<
input
type
="text"
name
="username"
>
<
br/>
password:<
input
type
="text"
name
="password"
>
<
br/>
age:<
input
type
="text"
name
="age"
>
<
br/>
<
input
type
="submit"
name
="submit"
value="
新增使用者
">
form
>
<
br/>
可見,第三種做法是比較好的,action和jsp寫起來都比較簡單。
模型驅動 ModelDriven
modeldriven 模型驅動,對所有action的模型物件進行批處理.我們在開發中,在action中一般是用實體物件,然後給實體物件get,set方法。regaction 然後在jsp頁面中給action中的user屬性繫結值是通過如下方式 這樣都要加上user.因為在值棧中action進入值棧...
Struts中ModelDriven的使用
它是struts2種獨有的一種接收使用者輸入的機制,想在專案中使用模型驅動 modeldriven 需要讓action實現com.opensymphony.xwork2.modeldriven 介面,使用它 的getmodel 方法來通知struts2要注入的屬性型別,並且宣告屬性時一定要例項化,但...
Struts中ModelDriven的使用
它是struts2種獨有的一種接收使用者輸入的機制,想在專案中使用模型驅動 modeldriven 需要讓action實現com.opensymphony.xwork2.modeldriven 介面,使用它 的getmodel 方法來通知struts2要注入的屬性型別,並且宣告屬性時一定要例項化,但...