2015年7月5日 星期日

Struts 使用DynaActionForm(Struts二)

DynaActionForm分成要不要validate()兩部分:

※不要validate()

struts-config.xml在HelloWorld的例子改成如下
1.ActionForm刪除,不需要了,就是因為不需要validate,所以不寫
2.struts-config.xml修改
<form-beans>
    <form-bean name="ooo" type="org.apache.struts.action.DynaActionForm"><!--type要改-->
        <!--對應jsp的屬性寫在這-->
        <form-property name="username" type="java.lang.String" />
        <form-property name="password" type="java.lang.String" />
    </form-bean>
</form-beans>
<action-mappings>
    <action path="/xxx" type="controller.LoginAction" name="ooo" scope="request" validate="false">--validate變false,所以input也不要了
        <forward name="success" path="/success.jsp"></forward>
        <forward name="fail" path="/fail.jsp"></forward>
    </action>
</action-mappings>

3.Action要強轉
DynaActionForm laForm = (DynaActionForm) form;
// 和struts-config.xml裡的form-bean,裡面的form property的name和type一樣
String username = (String) laForm.get("username");
String password = (String) laForm.get("password");

※要validate()

1.struts-config.xml修改
<form-beans>
    <!--看起來一樣,但必需繼承DynaActionForm-->
    <form-bean name="ooo" type="controller.LoginActionForm">
        <!--對應jsp的屬性寫在這-->
        <form-property name="username" type="java.lang.String" />
        <form-property name="password" type="java.lang.String" />
    </form-bean>
</form-beans>
<action-mappings>
    <action path="/xxx" type="controller.LoginAction" name="ooo" scope="request" validate="true" input="/index.jsp">
        <forward name="success" path="/success.jsp"></forward>
        <forward name="fail" path="/fail.jsp"></forward>
    </action>
</action-mappings>
    

2.Action要強轉 因為在struts-config.xml已經設定屬性,所以不用寫屬性和setter/getter了
public class LoginActionForm extends DynaActionForm {
    private static final long serialVersionUID = -9011126116308228383L;
    @Override
    public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {
        // 還是和struts-config.xml裡的form-bean,裡面的form property的name和type一樣
        String username = (String) this.get("username");
        String password = (String) this.get("password");
        
        ActionErrors errors = new ActionErrors();
        if(!username.equals("aaa")){
            errors.add("user", new ActionMessage("error.actionForm.user"));
        }
        if(!password.equals("bbb")){
            errors.add("pass", new ActionMessage("error.actionForm.pass"));
        }
        return errors;
    }
}

沒有留言:

張貼留言