工具:myeclipse6.0
环境:支持Struts1.x的Javaweb动态工程
简介:ajax前后台的数据交互实现依赖于XMLHttpRequest对象;
json实现将后台业务逻辑处理过的数据封装送给前台。
实例1:
前台JSP页面--pages/ajax.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %>ajax样例
配置Struts1.2支持--/ajax/WebRoot/WEB-INF/struts-config.xml:
后台数据包装后发送到前台处理--/ajax/src/com/neusoft/ajax/EmpAction.java
package com.neusoft.ajax; import java.io.IOException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.actions.DispatchAction; import org.json.JSONException; import org.json.JSONObject; public class EmpAction extends DispatchAction { public ActionForward getInfo(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, JSONException { JSONObject obj = new JSONObject(); obj.put("id", 1001); obj.put("name", "Will"); obj.put("age", 28); obj.put("sex", 0); obj.put("sal", 2000); obj.put("desc", "some infomation"); response.getWriter().write(obj.toString()); return null; } public ActionForward getMsg(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, JSONException { response.getWriter().write("Hello,AlvinKing , A message from server"); return null; } }
实例2:
共用实例1的后台处理类,前台页面--/ajax/WebRoot/pages/ajax1.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %>ajax样例
最后配置工程启动xml,--/ajax/WebRoot/WEB-INF/web.xml
ajax action org.apache.struts.action.ActionServlet config /WEB-INF/struts-config.xml 2 action *.do pages/ajax.jsp