日期:2014-05-16  浏览次数:20717 次

整合struts2 jQuery validate 插件的远程Ajax验证
整合struts2 jQuery validate 插件的远程Ajax验证
法:-----对用户名进行验证

<tr>

      <td>
        <label for="user.username">
         用户名(<font color=red>*</font>)
        </label>
       </td>
       <td>
        <input name="user.username" id="input1" />
       </td>

</tr>

js:

$("#info").validate(
      {
        rules: {
     "user.username":{
      required: true,
      minlength: 5 ,
      maxlength:15 ,
      remote:"/ssh2/test/remotetestAction.action"
     },
      ........       
    }});

struts.xml:

<action name="remotetestAction"
    class="com.small.action.RegAction" method="remoteTest">
    <result type="stream">
     <param name="user.username">inputStream</param><!--   默认就为inputStream   -->
    </result>
   </action>

action做处理:

public String remoteTest() {
   boolean b = false;

   if (null == user)
    b = true;
   else {
    logger.info("AJAX验证用户:" + user.getUsername());
    User userinfo = this.userDaoImpl.getUser(user);
    if (null != userinfo) {
     logger.info("AJAX验证用户:" + user.getUsername() + "---->已经存在....");
     b = true;
    } else
     logger.info("AJAX验证用户:" + user.getUsername() + "---->验证通过....");
   }
   return renderText(b ? "false" : "true");
}

protected String render(String text, String contentType) {
   try {
    HttpServletResponse response = ServletActionContext.getResponse();
    response.setContentType(contentType);
    response.getWriter().write(text);
   } catch (IOException e) {
   }
   return null;
}

/**
* 直接输出字符串.
*/
protected String renderText(String text) {
   return render(text, "text/plain;charset=UTF-8");
}