DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> JavaScript入門知識 >> AJAX入門 >> AJAX詳解
讓AJAX與Spring無縫整合
編輯:AJAX詳解     

整合出乎意料地簡單

把AJAX與Spring整合,過程異常簡單,幾乎只需要改動設定檔即可,頁面端的程式碼完全不必更動。

頁面端的呼叫

以Buffalo為例,頁面只需組出服務端點,建立Buffalo物件,再呼叫remoteCall指定要觸發的物件與方法,並在回呼中處理結果:

<script language="Javascript">
var springEndPoint = "<%=request.getContextPath()%>/remoting/Spring-buffalo";
function pageMethod() {
    var buffalo = new Buffalo(springEndPoint);
    buffalo.remoteCall("yourObject.yourMethod", [], function(reply) {
        var obj = reply.getResult();
    });
}
</script>

Web部署描述檔

過去用來設定Buffalo的properties檔,此處改由applicationContext.xml取代。web.xml中主要掛上Spring的ContextLoaderServlet與DispatcherServlet,並把/remoting/*路徑交給後者處理:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
  "https://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
  <display-name>Buffalo Web Remoting Demo</display-name>
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/applicationContext.xml</param-value>
  </context-param>
  <servlet>
    <servlet-name>context</servlet-name>
    <servlet-class>org.springframework.web.context.ContextLoaderServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet>
    <servlet-name>remoting</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>4</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>remoting</servlet-name>
    <url-pattern>/remoting/*</url-pattern>
  </servlet-mapping>
</web-app>

Spring組態檔

applicationContext.xml負責宣告被Spring托管的Bean,這些Bean可以是任何受Spring管理的物件:

<beans>
  <bean name="simpleService" class="net.buffalo.demo.simple.SimpleService"></bean>
  <bean name="numberService" class="net.buffalo.demo.numberguess.NumberGuessService"></bean>
</beans>

remoting-servlet.xml則透過BuffaloServiceExporter,把這些Bean對外暴露為可被AJAX呼叫的服務,用map把服務名稱與實際Bean關聯起來:

<beans>
  <bean name="/Spring-buffalo" class="net.buffalo.spring.BuffaloServiceExporter">
    <property name="services">
      <map>
        <entry key="simpleService"><ref bean="simpleService"/></entry>
        <entry key="numberService"><ref bean="numberService"/></entry>
      </map>
    </property>
  </bean>
</beans>

小結

整串的整合重點在於:页面邏輯零改動,僅透過web.xml掛上Spring的Dispatcher,再用applicationContext.xml宣告Bean、以BuffaloServiceExporter將Bean導出為遠端服務。被導出的Controller可透過任意方式的Servlet Dispatcher呼叫,讓AJAX與Spring的結合既乾淨又靈活。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved