将验证放到Action和ActionForm中去

1 首先放到ActionForm中,这里重写validate()方法

public ActionErrors validate(ActionMapping mapping,HttpServletRequest request) {

        ActionErrors messages = new ActionErrors();

        if(acount.length() == 0 ) {//对接受到得参数进行验证

            ActionMessage message = new ActionMessage("errors.acount","acount");//new一个message

            messages.add("acount",message);

        } else if(acount.length() < 5 || acount.length() > 10){

            ActionMessage message = new ActionMessage("errors.acount.length","acount","5","7");

            messages.add("acount",message);

        }

       

        if(password.length() < 5 || password.length() > 7){

            ActionMessage message = new ActionMessage("errors.password","password","5","7");

            messages.add("password" ,message);

        }

       

        return messages;

    }

ActionMessage message = new ActionMessage("errors.acount","acount");//

"errors.acount"是从配置文件中读取的,acount是配置文件中相应记录的第一个参数

需要将message 放到messages中进行保管就可以了,然后再页面调用要显示的信息

<html:form action="/login">

            <bean:message key="info.input.acount" />

            <html:text property="acount" />

            <html:errors property="acount" />//这里显示出错的信息

            <br />

            <bean:message key="info.input.password" />

            <html:text property="password" />

            <html:errors property="password" />//这里显示出错的信息

            <br />

            <html:submit />

            <html:cancel />

        </html:form>

怎样在Action中进行验证

 

public ActionForward execute(ActionMapping mapping, ActionForm form,

            HttpServletRequest request, HttpServletResponse response) {

        LoginForm loginForm = (LoginForm) form;

        String acount = loginForm.getAcount();

 

        if (acount.equals("abcdefg")) {//在此进行验证

            ActionMessages messages = new ActionMessages();

            ActionMessage message = new ActionMessage("errors.login", acount);

            messages.add("login.errors", message);//这里与ActionForm验证是一样的

            this.saveErrors(request, messages);//这里不同,需要保存到request

            return mapping.getInputForward();//返回struts配置中的input页面

        }

 

        return null;

    }

这里是Struts-config 文件中对于Action进行配置的信息

<action-mappings >

    <action

      attribute="loginForm"

      input="/login1.jsp"//这里就是如果表单验证,不成功那么就返回的页面,

//action中如果不能验证成功,那么return mapping.getInputForward();也是返回这个页面   name="loginForm"

      path="/login"

      scope="request"

      type="com.feidaochuanqing.struts.action.LoginAction"

      cancellable="true" />

 

注意

1 在进行验证的过程中,首先进行表单的验证然后进行Action的验证,只有ActionForm验证通过之后才进行Action的验证。所以,显示的时候,form验证的错误先进行显示。

2 Action验证要保存到request或是session中,而form验证就不用了。

3 Action验证要进行返回,跳转到input页面。

4 表单验证时对形式进行的验证,而Action验证是对于内容进行的验证。

 

你可能感兴趣的:(html,jsp,bean,struts)