您的位置:程序门 -> java -> eclipse



ajax與mvc的配合使用(高手請進)


[收藏此页] [打印本页]选择字色:背景色:字体:[][][]


ajax與mvc的配合使用(高手請進)
发表于:2007-03-04 21:31:26 楼主
我用mvc方式寫了一個登錄驗證的action,如果是執行submit數,已能正常運行.
現在我套用上ajax技術,進行異步提交數據,然後要解決的問題有以下的:
1.在actionform中,我檢驗用戶輸入的user和pass,如果為null,則actionerrors會把該錯誤對象會被actionform.add(...)保存起來,接著我要在用戶輸入的頁面上發同該錯誤並且提示,怎麽完成這些動作?由於ajax技術是不用整個頁面刷新,請各大蝦指點。。。
发表于:2007-03-04 23:44:531楼 得分:0
iframe
发表于:2007-03-05 09:30:382楼 得分:0
当用戶輸入了username和password后,可以用ajax将这两个值作为参数而发出请求,在服务器端处理后返回(如用out.print()),可以在返回串中设标志位来检查用户是否合法;更加灵活的是返回xml,这些在网上都有很多资料的,可以搜一下;用框架会挺简单,只是如果项目只会在这个地方用到ajax,那单纯的ajax已经可以满足要求^_^
发表于:2007-03-05 09:56:313楼 得分:0
這裏先謝過上樓上的回複,這裏有我的源文件源碼:
jsp文件
----------------
<%@   include   file= "taglib.jsp "%>
<!doctype   html   public   "-//w3c//dtd   html   4.01   transitional//en ">
<html:html   locale= "true "> <html:base/>
    <head>        
        <title> <bean:message   key= "webname "/> </title>        
        <meta   http-equiv= "pragma "   content= "no-cache ">
        <meta   http-equiv= "cache-control "   content= "no-cache ">
        <meta   http-equiv= "expires "   content= "0 ">
        <meta   http-equiv= "keywords "   content= "keyword1,keyword2,keyword3 ">
        <meta   http-equiv= "description "   content= "this   is   my   page ">
        <link   rel= "stylesheet "   href= "_/styles.css "   type= "text/css "> </link>
    </head>
    <script   type= "text/javascript "   src= "_/ajax.js "> </script>
    <body>
<center> <div   id= "outside "   class= "outside ">
<div   id= "partnerlink "   class= "partnerlink "   align= "right ">
<html:link   page= "/ "> partner   links </html:link>
<html:link   page= "/ "> computer   technic </html:link>
<html:link   page= "/ "> my   blog </html:link>
<html:link   page= "/ "> online   help? </html:link>
</div>
<div   id= "login_search "   class= "login_search ">
<div   id= "logindiv "   style= "text-align:left; "> <html:errors/> <html:errors/>
<html:form   action= "/loginaction "   method= "post "   style= "width:auto;float:left; ">
userid   : <html:text   property= "username "   styleid= "username "   styleclass= "inputtxt "/>
pass: <html:password   property= "password "   redisplay= "true "   styleid= "password "   styleclass= "inputtxt "/>
<html:button   property= "submit "   value= "log-in "   styleclass= "btncss "   onclick= "ajax( 'project/loginaction.do ', 'loginform '); "/>
</html:form>
<html:link   page= "/ "> register </html:link>
<html:link   page= "/ "> help? </html:link>
</div>
<div   style= "text-align:right; "> </div>
</div>
</div> </center>
    </body>
</html:html>

----------------
actionform
----------------
//created   by   myeclipse   struts
//   xsl   source   (default):   platform:/plugin/com.genuitec.eclipse.cross.easystruts.eclipse_4.1.1/xslt/javaclass.xsl

package   project.form;

import   javax.servlet.http.httpservletrequest;

import   org.apache.struts.action.actionerrors;
import   org.apache.struts.action.actionmessage;
import   org.apache.struts.action.actionform;
import   org.apache.struts.action.actionmapping;

/**  
  *   myeclipse   struts
  *   creation   date:   02-28-2007
  *  
  *   xdoclet   definition:
  *   @struts.form   name= "loginform "
  */
public   class   loginform   extends   actionform   {

//   ---------------------------------------------------------   instance   variables

/**   password   property   */
private   string   password;

/**   username   property   */
private   string   username;

//   ---------------------------------------------------------   methods

/**  
  *   method   validate
  *   @param   mapping
  *   @param   request
  *   @return   actionerrors
  */
public   actionerrors   validate(
actionmapping   mapping,
httpservletrequest   request)   {
actionerrors   errors   =   new   actionerrors();
if(username.trim().length()==0){
errors.add( "username ",new   actionmessage( "error.userid "));
}
if(password.trim().length()==0){
errors.add( "password ",new   actionmessage( "error.passtx "));
}
//   todo   auto-generated   method   stub
return   errors;
}

/**  
  *   method   reset
  *   @param   mapping
  *   @param   request
  */
public   void   reset(actionmapping   mapping,   httpservletrequest   request)   {

//   todo   auto-generated   method   stub
}

/**  
  *   returns   the   password.
  *   @return   string
  */
public   string   getpassword()   {
return   password;
}

/**  
  *   set   the   password.
  *   @param   password   the   password   to   set
  */
public   void   setpassword(string   password)   {
this.password   =   password;
}

/**  
  *   returns   the   username.
  *   @return   string
  */
public   string   getusername()   {
return   username;
}

/**  
  *   set   the   username.
  *   @param   username   the   username   to   set
  */
public   void   setusername(string   username)   {
this.username   =   username;
}

}


----------------
action
----------------
//created   by   myeclipse   struts
//   xsl   source   (default):   platform:/plugin/com.genuitec.eclipse.cross.easystruts.eclipse_4.1.1/xslt/javaclass.xsl

package   project.action;

import   javax.servlet.http.httpservletrequest;
import   javax.servlet.http.httpservletresponse;

import   org.apache.struts.action.action;
import   org.apache.struts.action.actionform;
import   org.apache.struts.action.actionforward;
import   org.apache.struts.action.actionmapping;

import   project.form.loginform;

/**  
  *   myeclipse   struts
  *   creation   date:   02-28-2007
  *  
  *   xdoclet   definition:
  *   @struts.action   path= "/loginaction "   name= "loginform "   input= "/index.jsp "   scope= "request "   validate= "true "
  */
public   class   loginaction   extends   action   {

//   ---------------------------------------------------------   instance   variables

//   ---------------------------------------------------------   methods

/**  
  *   method   EXECute
  *   @param   mapping
  *   @param   form
  *   @param   request
  *   @param   response
  *   @return   actionforward
  */
public   actionforward   EXECute(
actionmapping   mapping,
actionform   form,
httpservletrequest   request,
httpservletresponse   response)   {
loginform   loginform   =   (loginform)   form;
//   todo   auto-generated   method   stub
return   null;
}

}


发表于:2007-03-05 09:56:514楼 得分:0
----------------
ajax
----------------
/**
  *   ajax.js
  *
  *   collection   of   scripts   to   allow   in   page   communication   from   browser   to   (struts)   server
  *   ie   can   reload   part   instead   of   full   page
  *
  *   how   to   use
  *   ==========
  *   1)   call   retrieveurl   from   the   relevant   event   on   the   html   page   (e.g.   onclick)
  *   2)   pass   the   url   to   contact   (e.g.   struts   action)   and   the   name   of   the   html   form   to   post
  *   3)   when   the   server   responds   ...
  *   -   the   script   loops   through   the   response   ,   looking   for   <span   id= "name "> newcontent </span>
  *     -   each   <span>   tag   in   the   *existing*   document   will   be   replaced   with   newcontent
  *
  *   note:   <span   id= "name ">   is   case   sensitive.   name   *must*   follow   the   first   quote   mark   and   end   in   a   quote
  *   everything   after   the   first   '> '   mark   until   </span>   is   considered   content.
  *   empty   sections   should   be   in   the   format   <span   id= "name "> </span>
  */

//global   variables
    var   req;
    var   which;


    /**
      *   get   the   contents   of   the   url   via   an   ajax   call
      *   url   -   to   get   content   from   (e.g.   /struts-ajax/sampleajax.do?ask=command_name_1)  
      *   nodetooverwrite   -   when   callback   is   made
      *   nameofformtopost   -   which   form   values   will   be   posted   up   to   the   server   as   part  
      * of   the   request   (can   be   null)
      */
    function   ajax(url,nameofformtopost)   {
       
        //get   the   (form   based)   params   to   push   up   as   part   of   the   get   request
        //url= "/ "+url+ ".do? "+getformasstring(nameofformtopost);
        url= "/ "+url+ "? "+getformasstring(nameofformtopost);
        alert(url);
        //do   the   ajax   call
        if   (window.xmlhttprequest)   {   //   non-ie   browsers
            req   =   new   xmlhttprequest();
            req.onreadystatechange   =   processstatechange;
            try   {
            req.open( "get ",   url,   true);   //was   get
            }   catch   (e)   {
                alert( "problem   communicating   with   server\n "+e);
            }
            req.send(null);
        }   else   if   (window.activexobject)   {   //   ie
           
            req   =   new   activexobject( "microsoft.xmlhttp ");
            if   (req)   {
                req.onreadystatechange   =   processstatechange;
                req.open( "get ",   url,   true);
                req.send();
            }
        }
}

/*
      *   set   as   the   callback   method   for   when   xmlhttprequest   state   changes  
      *   used   by   retrieveurl
    */
    function   processstatechange()   {
   
        if   (req.readystate   ==   4)   {   //   complete
        alert(req.statustext);
            if   (req.status   ==   200)   {   //   ok   response
                alert(req.statustext);
                ///alert( "ajax   response: "+req.responsetext);
               
                //split   the   text   response   into   span   elements
                spanelements   =   splittextintospan(req.responsetext);
               
                //use   these   span   elements   to   update   the   page
                replaceexistingwithnewhtml(spanelements);
               
            }   else   {
                alert( "problem   with   server   response:\n   "   +   req.statustext+ "\n--------------------\nreq.status= "+req.status);
            }
        }
    }
 
  /**
    *   gets   the   contents   of   the   form   as   a   url   encoded   string
    *   suitable   for   appending   to   a   url
    *   @param   formname   to   encode
    *   @return   string   with   encoded   form   values   ,   beings   with   &
    */  
  function   getformasstring(formname){
 
  //setup   the   return   string
  returnstring   = " ";
 
    //get   the   form   values
  formelements=document.forms[formname].elements;
 
  //loop   through   the   array   ,   building   up   the   url
  //in   the   form   /strutsaction.do&name=value
 
  for   (   var   i=formelements.length-1;   i> =0;   --i   ){
  //we   escape   (encode)   each   value
  if(formelements[i].name   !=   "submit "   &&   formelements[i].name   !=   "cancel ")
  returnstring=returnstring+escape(formelements[i].name)+ "= "+escape(formelements[i].value)+ "& ";
  }
 
  //return   the   values
  return   returnstring.substr(0,returnstring.length-1);  
  }
 
  /**
  *   splits   the   text   into   <span>   elements
  *   @param   the   text   to   be   parsed
  *   @return   array   of   <span>   elements   -   this   array   can   contain   nulls
  */
  function   splittextintospan(texttosplit){
 
    //split   the   document
  returnelements=texttosplit.split( " </span> ")
 
  //process   each   of   the   elements  
  for   (   var   i=returnelements.length-1;   i> =0;   --i   ){
 
  //remove   everything   before   the   1st   span
  spanpos   =   returnelements[i].indexof( " <span ");
 
  //if   we   find   a   match   ,   take   out   everything   before   the   span
  if(spanpos> 0){
  substring=returnelements[i].substring(spanpos);
  returnelements[i]=substring;
 
  }  
  }
 
  return   returnelements;
  }
 
  /*
    *   replace   html   elements   in   the   existing   (ie   viewable   document)
    *   with   new   elements   (from   the   ajax   requested   document)
    *   where   they   have   the   same   name   and   are   <span>   elements
    *   @param   newtextelements   (output   of   splittextintospan)
    * in   the   format   <span   id=name> texttoupdate
    */
  function   replaceexistingwithnewhtml(newtextelements){
 
  //loop   through   newtextelements
  for   (   var   i=newtextelements.length-1;   i> =0;   --i   ){
   
  //check   that   this   begins   with   <span
  if(newtextelements[i].indexof( " <span ")> -1){
 
  //get   the   name   -   between   the   1st   and   2nd   quote   mark
  startnamepos=newtextelements[i].indexof( ' " ')+1;
  endnamepos=newtextelements[i].indexof( ' " ',startnamepos);
  name=newtextelements[i].substring(startnamepos,endnamepos);
 
  //get   the   content   -   everything   after   the   first   >   mark
  startcontentpos=newtextelements[i].indexof( '> ')+1;
  content=newtextelements[i].substring(startcontentpos);
 
  //now   update   the   existing   document   with   this   element
 
  //check   that   this   element   exists   in   the   document
  if(document.getelementbyid(name)){
 
  //alert( "replacing   element: "+name);
  document.getelementbyid(name).innerhtml   =   content;
  }   else   {
  //alert( "element: "+name+ "not   found   in   existing   document ");
  }
  }
  }
  }


---------------------------------------------------------------------------
請問我要如何在jsp的頁面上顯示actionformj裏actionerrors信息?(這裏是用了ajax提交的)
发表于:2007-03-05 10:00:405楼 得分:0
可以的話加我qq:117999300,icq:237529869,大家互相交流。。。
我每天都會在線的~~


快速检索

最新资讯
热门点击