09-01
20

SSH使用Validator框架对DispatchAction不同方法使用不同的字段验证

reference: http://blog.csdn.net/qjyong/archive/2008/11/16/3311688.aspx

能解决这个问题还真是要感谢 http://blog.csdn.net/qjyong/archive/2008/11/16/3311688.aspx这篇文章的作者qjyong。参照他的方法我在SSH中完成了不同方法验证需求不同的操作。

1. 自定义的FileChecks类。这里对qjyong的FileChecks稍微做了一下改动。应该使用SSH框架以后,使用的Action都写成org.springframework.web.struts.DelegatingActionProxy。所以在这种情况下Class.forName(className).newInstance() instanceof DispatchAction永远都为false.下面只把改动的代码注释出来,其它的都参考qjyong的。

/**
     * 方法说明: 判断in是否出现在source中
     *
     * @param source
     * @param in
     * @return
     */
    private static boolean isIn(String source, String in) {
    if("".equals(in) || in == null)
    {
       return true;
    }
        source = SEPARATOR + source + SEPARATOR;
        if (source.indexOf(SEPARATOR + in + SEPARATOR) != -1) {
            return true;
        } else {
            return false;
        }
    }

   /**
     * 判断需要验证
     *
     * @param field
     * @param request
     * @return
     */
    private static boolean isNeedValidate(Field field,
            HttpServletRequest request) {
        boolean flag = true;

        // 查找到当前请求对应的actionMapping
        ActionMapping mapping = (ActionMapping) request
                .getAttribute(Globals.MAPPING_KEY);
        // 得到处理该请求的Action类名
        String className = mapping.getType();

        String input = request.getHeader("Referer");
        if (input != null) {
            // mapping.setInput(input);
        }

        try {
            // 这里不要判断是否为 DispatchAction的实例
           // if (Class.forName(className).newInstance() instanceof DispatchAction) {
                // 得到<action>标记的parameter属性的值
                String parameter = mapping.getParameter();
                //如果没有设置parameter也就是没有使用DispatchAction的类则,parameter为空
                if("".equals(parameter) || parameter == null)
                {
                return true;
                }
                else
                {
                // 得到当前要执行方法名
                String currentMethodName = request.getParameter(parameter);
                // 获取配置文件中需要验证的方法名列表串
                String methods = field.getVarValue("methodsNeedValidation");
                // 如果没有配置需要验证的方法或不在需要验证的方法列表中,则把flag改为false
                if (!isIn(methods, currentMethodName)) {
                    flag = false;
                } }
        //    }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return flag;
    }

   //其它的几个设置都一样,不全部粘贴出来了。可以看qjyong的文章。

    public static boolean validateRequired(Object bean, ValidatorAction va,
            Field field, ActionMessages errors, Validator validator,
            HttpServletRequest request) {

        if (isNeedValidate(field, request)) {
            return FieldChecks.validateRequired(bean, va, field, errors,
                    validator, request);
        } else {
            return true;
        }
    }

    。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。

2、修改validate-rules.xml,使用自定义的字段验证类:注意这里的validate-rules.xml中他没有重写validateWhen,因此,validateWhen还是使用org.apache.struts.validator.validwhen.ValidWhen这个方法

      <validator name="required"
            classname="org.diamond.validator.MyFieldChecks"
               method="validateRequired"
         methodParams="java.lang.Object,
                       org.apache.commons.validator.ValidatorAction,
                       org.apache.commons.validator.Field,
                       org.apache.struts.action.ActionMessages,
                       org.apache.commons.validator.Validator,
                       javax.servlet.http.HttpServletRequest"
                  msg="errors.required"/>

      <validator name="validwhen"
          msg="errors.required"
                 classname="org.apache.struts.validator.validwhen.ValidWhen"
                 method="validateValidWhen"
                 methodParams="java.lang.Object,
                       org.apache.commons.validator.ValidatorAction,
                       org.apache.commons.validator.Field,
                       org.apache.struts.action.ActionMessages,
                       org.apache.commons.validator.Validator,
                       javax.servlet.http.HttpServletRequest"/>
               。。。。。。。。。。。。。。。。。。。。。。。。

3、配置具体的验证规则validation.xml。暂时只需要对需要继承DispatchAction的类并且该类中某些方法满足需要验证某些方法不需要验证。就可以在这个文件里进行设置。这里只有loginOn需要验证methodsNeedValidation需要跟前面MyFieldChecks.java设置的一致。

<form-validation>
<global>
</global>
   <formset>
      <form name="customerLoginForm">
         <field property="email" depends="required">
            <arg0 key="customerLoginForm.email"/>
            <var>
            <var-name>methodsNeedValidation</var-name>
            <var-value>loginOn</var-value>
            </var>

         </field>
         <field property="password" depends="required">
         <arg0 key="customerLoginForm.customerPassword"/>
         <var>
            <var-name>methodsNeedValidation</var-name>
            <var-value>loginOn</var-value>
            </var>
         </field>
      </form>
   </formset>
/form-validation>

4、struts-config.xml文件

<action
      attribute="customerLoginForm"
      input="/form/customerLogin.jsp"
      name="customerLoginForm"
      path="/customerLogin"
      scope="request"
      validate="true"
      parameter="method"
      type="org.springframework.web.struts.DelegatingActionProxy">
      <forward name="loginSuccess" path="/form/index.jsp" />
      <forward name="loginFailed" path="/form/customerLogin.jsp"></forward>
   </action>

5、CustomerLoginAction。主要要注意的也就是方法名必须和jsp中定义的一致

public class CustomerLoginAction extends DispatchAction
{
public ActionForward loginOn(ActionMapping mapping, ActionForm form,
    HttpServletRequest request, HttpServletResponse response)
{
   DynaActionForm customerLoginForm = (DynaActionForm) form;
  
   if(isCancelled(request))
   {
    return mapping.findForward(MessageUtil.LoginSuccess);
   }
  
   String email = customerLoginForm.getString(MessageUtil.Email);
   String tuserpassword = customerLoginForm.getString(MessageUtil.Password);
   Testuser testUser;
  
   try
   {
    Boolean isExist = testUserService.isExist(email, tuserpassword);
    List list = testUserService.findByProperty(MessageUtil.Email, email);
    if(isExist && list.size()==1)
    {
     testUser = (Testuser)list.get(0);
     request.getSession().setAttribute(MessageUtil.Email, email);
     request.getSession().setAttribute(MessageUtil.NickName, testUser.getNickname());
     return mapping.findForward(MessageUtil.LoginSuccess);
    }
    else
    {
     errorMessageShow(request,"errors.accessIllegal",MessageUtil.AccessIllegal);
     return mapping.findForward(MessageUtil.LoginFailed);
    }
   }
   catch(Exception e)
   {
    errorMessageShow(request,"errors.accessIllegal",MessageUtil.AccessIllegal);
    return mapping.findForward(MessageUtil.LoginFailed);
   }
  
}

public ActionForward getSQuestionList(ActionMapping mapping, ActionForm form,
    HttpServletRequest request, HttpServletResponse response)
{
   DynaActionForm customerLoginForm = (DynaActionForm) form;
   return mapping.findForward(MessageUtil.LoginFailed);
}

private void errorMessageShow(HttpServletRequest request,String errorMessage,String property)
{
   ActionMessages errors = new ActionMessages();
   ActionMessage error = new ActionMessage(errorMessage);
   errors.add(property,error);
   this.saveErrors(request, errors);
}

public TestUserService getTestUserService()
{
   return testUserService;
}

public void setTestUserService(TestUserService testUserService)
{
   this.testUserService = testUserService;
}

}

6、customerLogin.jsp.

<%@ page language="java" pageEncoding="utf-8"%>
<%@ taglib uri="http://jakarta.apache.org/struts/tags-bean" prefix="bean"%>
<%@ taglib uri="http://jakarta.apache.org/struts/tags-html" prefix="html"%>
<%@ page import="java.util.Locale" %>
<%@ page import="org.apache.struts.Globals" %>
<html:html locale="true">
<html>
<head>
   <title><bean:message key="customerLoginForm.title"/></title>
</head>
<body>
   <TABLE border="0" cellpadding="0" cellspacing="0" width="100%">
  <html:form action="/customerLogin?method=loginOn" >
   <tr>
    <table border="0" cellpadding="0" cellspacing="0">
    <tr>
     <FONT color="red"><html:errors property="accessIllegal"/></FONT>
    </tr>
    <tr>
     <td><bean:message key="customerLoginForm.email"/></td>
     <td><html:text property="email"/></td>
     <td><html:errors property="email"/></td>
    </tr>
    <tr>
     <td><bean:message key="customerLoginForm.customerPassword"/></td>
     <td><html:password property="password"/></td>
     <td><html:errors property="password"/></td>
    </tr>
    <tr>
      <td><html:submit><bean:message key="customerLoginForm.button.submit"/></html:submit></td>
     <td><html:cancel><bean:message key="customerLoginForm.button.cancel"/></html:cancel></td>
    </tr>
    <tr>
     <td><html:link action="/customerLogin.do?method=getSQuestionList"><bean:message key="newCustomerRegister.register"/></html:link></td>
    </tr>
   </TABLE>
</tr>
</html:form>
</TABLE>
</body>
</html>
</html:html>

8、其它的配置文档信息比如application-context.xml,资源文件ApplicationResources.properties都不细说了。



[本日志由 blurxx 于 2009-01-21 09:55 PM 编辑]
文章来自: 本站原创
引用通告: 查看所有引用 | 我要引用此文章
Tags: Validator
相关日志:
评论: 0 | 引用: 0 | 查看次数: 432
发表评论
昵 称:
密 码: 游客发言不需要密码.
内 容:
验证码: 验证码
选 项:
虽然发表评论不用注册,但是为了保护您的发言权,建议您注册帐号.
字数限制 1000 字 | UBB代码 开启 | [img]标签 关闭