/struts-tags中自帶了很多標簽
比如一個簡單的登錄表單,其中自帶了很多的樣式,實際上如果你不需要用到struts的實際功能的時候不建議使用
1
2
3
4
5
6
|
<s:form action= "user_save" > <s:token></s:token> <s:textfield name= "username" label= "用戶名" ></s:textfield> <s:textfield name= "pwd" label= "密碼" ></s:textfield> <s:submit value= "提交" ></s:submit> </s:form> |
你可以通過設置屬性 theme="simple"來取消他自帶的樣式
其次是ModelDriven,意思是直接把實體類當成頁面數據的收集對象。在Action實現ModelDriven接口,可以很方便的對實體類對象的屬性賦值,不過在Action中實體類對象要new出來并且重寫ModelDriven的getModel方法,返回值是你的實體類對象代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
package com.xinzhi.action; import java.util.List; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionSupport; import com.opensymphony.xwork2.ModelDriven; import com.opensymphony.xwork2.util.ValueStack; import com.xinzhi.dao.impl.UserDaoImpl; import com.xinzhi.entity.UserEntity; public class UserAction extends ActionSupport implements ModelDriven<UserEntity> { private static final long serialVersionUID = 1L; private UserEntity userEntity = new UserEntity(); UserDaoImpl userDaoImpl = new UserDaoImpl(); public UserEntity getUserEntity() { return userEntity; } public void setUserEntity(UserEntity userEntity) { this .userEntity = userEntity; } public UserEntity getModel() { return userEntity; } } |
然后是表單的數據回顯,在Action當中把你的實體類對象壓入(ValueStack)堆棧中,然后在頁面中取出堆棧你要的值,方法如下
1
2
3
4
5
6
7
8
|
public String view() { UserEntity selectAUserEntity = userDaoImpl.selectAUserEntity(userEntity .getId()); ValueStack valueStack = ActionContext.getContext().getValueStack(); valueStack.pop(); valueStack.push(selectAUserEntity); return "view" ; } |
最后是防止表單重復提交的方法token,我對他的理解是,在表單中如果有<token>標簽的時候,提交表單的同時在表單頁和action中隨機生成一個相同的ID值,當第一次提交過來的表單被接收時這個ID將被刪除,當被重復提交時就會找不到對應的ID值導致無法重復提交,并且發出無效指令的錯誤代碼如下
表單代碼
1
2
3
4
5
6
|
<s:form action= "user_save" > <s:token></s:token> <s:textfield name= "username" label= "用戶名" ></s:textfield> <s:textfield name= "pwd" label= "密碼" ></s:textfield> <s:submit value= "提交" ></s:submit> </s:form> |
然后要在struts.xml配置文件中使用對應的攔截器,并指出重復提交時,無效的指令將會跳轉到哪一個頁面代碼如下:
1
2
3
4
5
6
|
<action name= "user_*" class = "com.xinzhi.action.UserAction" method= "{1}" > <interceptor-ref name= "defaultStack" ></interceptor-ref> <interceptor-ref name= "token" > <param name= "includeMethods" >save</param> </interceptor-ref> </action> |
以上所述是小編給大家介紹的J2EE中的struts2表單細節處理,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對服務器之家網站的支持!
原文鏈接:http://www.cnblogs.com/ShaoXin/p/7068952.html