首先寫頁面,主要代碼爲:
- <script type="text/javascript" src="js/jquery-1.6.1.js"></script>
- <script type="text/javascript">
- $(document).ready(function(){
- $("input").click(function(){
- $.ajax({
- url:'<%=basePath%>strutsJ.do',
- error:function(){
- alert("this has errors!!");
- },
- success:function(data){
- alert(data);
- }
- });
- });
- });
- </script>
- </head>
- <body>
- <input type="submit" value="submit"/>
- </body>
然後是action,代碼爲import java.io.IOException;
- import org.apache.struts2.ServletActionContext;
- public class TestAction {
- private String result;
- // ajax返回結果
- public String getResult() {
- return result;
- }
- public String execute() {
- this.result = "Hello! ";
- System.out.println("this is action here!!");
- try {
- ServletActionContext.getResponse().getWriter().print(result);
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- return null;
- }
- }
其次是struts.xml,代碼爲:
- <?xml version="1.0" encoding="UTF-8"?>
- <!DOCTYPE struts PUBLIC
- "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN"
- "http://struts.apache.org/dtds/struts-2.1.dtd">
- <struts>
- <!--指定web應用的默認編碼集,相當於調用HttpServletRequest.setCharacterEncoding方法 -->
- <constant name="struts.i18n.encoding" value="UTF-8" />
- <!-- 指定需要struts2處理的請求後綴,默認值爲action. 如果用戶需要指定多個請求後綴,則多個後綴之間以英語逗號(,)隔開 -->
- <constant name="struts.action.extension" value="do" />
- <package name="struts-platform" extends="struts-default" namespace="/">
- <!--自定議返回類型 -->
- <action name="strutsJ" class="lqx.TestAction">
- </action>
- </package>
- </struts>
最後是web.xml,代碼爲:
- <?xml version="1.0" encoding="UTF-8"?>
- <web-app version="2.5"
- xmlns="http://java.sun.com/xml/ns/javaee"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
- http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
- <welcome-file-list>
- <welcome-file>index.jsp</welcome-file>
- </welcome-file-list>
- <filter>
- <filter-name>struts2</filter-name>
- <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
- </filter>
- <filter-mapping>
- <filter-name>struts2</filter-name>
- <url-pattern>*.do</url-pattern>
- </filter-mapping>
- </web-app>
結束語:這是一個關於jquery ajax和struts2結合的一個小例子,只是一個最簡單的流程,但卻是最基本,最關鍵的一步。