icai项目开发日记(三)

来源:互联网 发布:德国 知乎 编辑:程序博客网 时间:2024/06/05 05:37

四.struts中Ajax 的简单应用

  Ajax 现在已经热火朝天了,正好做这个小项目时有个功能最理想的方法就是用Ajax时,因为没学过javascript,费了好大的劲,也请教了不少人才弄明天下面这段代码是怎么回事.功能是实现了,不过对Ajax的实在了解不多,有空了以后好好再琢磨.不懂javascript.不会Ajax.struts中Ajax的简单应用.可以完全不用理会javascript.现在就来看看它的入门级用法.看看我是怎么实现的.

用到的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 retrieveURL(url,nameOfFormToPost) {
    
    
//get the (form based) params to push up as part of the get request
    url=url+getFormAsString(nameOfFormToPost);
    
    
//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 "+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
      if (req.status == 200// OK response
        
        
//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(
"Ajax response:"+req.responseText);
        
//alert("Problem with server response:  " + req.statusText);
      }

    }

  }

 
 
/**
  * 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
         returnString=returnString+"&"+escape(formElements[i].name)+"="+escape(formElements[i].value);
     }

     
     
//return the values
     return returnString; 
 }

 
 
/**
 * 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页面如下:(仅贴出使用相关的代码)

 

<%@page contentType="text/html;charset=gb2312" language="java" isELIgnored="false"%>
<html:form action="/lr0Analyze" method="POST"  >
<align="left">
选择文法:
  
<html:select property="select_grammar" onchange="retrieveURL('grammarAjax.do?tableName=GRAMMAR','lr0AnalyzeForm');">
     
<html:options collection="grammarCollection" property="label" labelProperty="label"/>
  
</html:select>
</P>
  
<align="left">
  输入文法:                                                                      
  
<!-- 1.Default Return Blank -->  
  
<logic:notPresent name="SELECTED_GRAMMAR" scope="request">
  
<span id="thegrammar">                                       
    
<html:textarea property="selected_grammar" rows="7" cols="40">
    
</html:textarea>*
  
</span>
  
</logic:notPresent>
  
<!-- 2.Return content if requested-->    
  
<logic:present name="SELECTED_GRAMMAR" scope="request">
    
<span id="thegrammar">         
      
<html:textarea property="selected_grammar" rows="7" cols="40" value="${SELECTED_GRAMMAR}">
      
</html:textarea>*     
    
</span>      
  
</logic:present>                                           
  
</P>
  
<align="left">
  输 入 串  :
  
<html:text maxlength="40" property="input_lr0" size="40"/>必须以<FONT color="#ff0000"></FONT>号结尾
</P>
  
<align="left">
  
<html:submit/><html:reset/>
</P>
</html:form>

  如代码所示:代码中有两个<span id="thegrammar"> (thegrammar是保存在request域内的一个参数)两个代码表示的意思分别是:1.当request域内不存在thegrammar时使用期1。2.当request域内存在thegrammar时使用期2。form提交的目标是grammarAjax.do.(struts-config.xml中定义的名字)

<html:textarea property="selected_grammar" rows="7" cols="40" value="${SELECTED_GRAMMAR}">

将<html:textarea>的值设为${SELECTED_GRAMMAR};

Ajax可以接收任一后台处理的结果。jsp,servlet,action等。要做的只要将处理结果保存到相应的区域(request,reponse,application)使用action处理如下(此即为grammarAjax.do 对应的代码):

package ysu.cs.icai.action;
import javax.servlet.ServletContext;
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 java.sql.*;
import ysu.cs.icai.common.*;
import ysu.cs.icai.database.ConDatabase;

/** 
 * MyEclipse Struts
 * Creation date: 08-30-2006
 * 
 * XDoclet definition:
 * @struts.action validate="true"
 
*/

public class GrammarAjaxAction extends Action {
    
/** 
     * Method execute
     * 
@param mapping
     * 
@param form
     * 
@param request
     * 
@param response
     * 
@return ActionForward
     
*/

    
public ActionForward execute(
        ActionMapping mapping,
        ActionForm form,
        HttpServletRequest request,
        HttpServletResponse response) 
{
        
        ConDatabase dataSource;
        java.sql.Connection myConnection;
        Statement st;
        ResultSet set;
        String sel
=request.getParameter("select_grammar");
        String labeltable
=request.getParameter("tableName");
        String sql
="select * from "+labeltable+" where label='"+sel+"'";//the value of "tableName" is GRAMMAR OR FORMULA 
        
        
try{
            ServletContext application
=request.getSession().getServletContext();
            
            dataSource
=(ConDatabase)application.getAttribute("DATASOURCE");
            myConnection
=dataSource.getConnection();

            st
=myConnection.createStatement();
            st.execute(
"use icaidb;");
            set
=st.executeQuery(sql);
            
while(set.next()){
                String re
=set.getString(2);
                re
=Common.removeTransferredMeaning(re);
                //System.out.print(re);
                request.setAttribute(
"SELECTED_GRAMMAR",re);        
                
//System.out.print(re);
            }

        }
catch(SQLException er){
            er.printStackTrace();
        }

        
return mapping.findForward("SUCCESS_PATH");
    }

}


这段代码相信大家都看能看明白:根据select_grammar和tablename这两个属性在一个数据库中检索相应的数据后,并将结果返回.(注意相保存在到request,reponse,application...任一作用域中).

 可以参考如下文章(以下列表摘自www.ibm.com):

  • Adaptive Path 是一家领先的用户界面设计公司,仔细阅读他们的网站可以更多地了解 Ajax。 
     
  • 可以先了解下一期文章的主题 XMLHttpRequest 对象,请阅读 关于 XMLHttpRequest 对象的这篇文章
  • 如果使用 Internet Explorer,可以访问 Microsoft Developer Network 的 XML Developer Center
  • 面向 Java 开发人员的 Ajax: 构建动态的 Java 应用程序(developerWorks,2005 年 9 月)介绍了这种革新方法,它解决了页面重新加载难题,可以创建动态的 Web 应用程序体验。
  • 面向 Java 开发人员的 Ajax: Ajax 的 Java 对象序列化(developerWorks,2005 年 10 月)介绍了在 Ajax 应用程序中对数据进行序列化的五种方法。
  • Using Ajax with PHP and Sajax(developerWorks,2005 年 10 月),这篇教程针对那些对开发丰富 Web 应用程序感兴趣的人,介绍了使用 Ajax 和 PHP 动态更新内容。
  • Call SOAP Web services with AJAX, Part 1: Build the Web services client(developerWorks,2005 年 10 月)介绍了如何使用 Ajax 设计模式实现基于 Web 浏览器的 SOAP Web 服务客户机。
  • XML 问题: 超越 DOM(developerWorks,2005 年 5 月)详细阐述了如何使用文档对象模型来构建动态 Web 应用程序。
  • Build apps with Asynchronous JavaScript with XML, or AJAX(developerWorks,2005 年 11 月)演示了如何使用 Ajax 构造支持实时检验的 Web 应用程序。