AJAX和JSON Web开发前后台交互
?
工具: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+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html> <head> <base href="<%=basePath%>"> <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" type="text/css" href="styles.css">--> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>ajax样例</title> <style type="text/css"> td {width: 100px;} </style> <script type="text/javascript" src="/ajax/pages/json2.js"></script> <script type="text/javascript"> function getXHR() { try { return new XMLHttpRequest(); } catch(e) { try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) { return new ActiveXObject("Msxml2.XMLHTTP"); } } } function getInfo() { var xhr = getXHR(); xhr.open("POST", "/ajax/emp.do?method=getInfo", true); xhr.onreadystatechange = function() { if (xhr.readyState == 4) { var empInfo = JSON.parse(xhr.responseText); document.getElementById("id").value = empInfo.id; document.getElementById("name").value = empInfo.name; document.getElementById("age").value = empInfo.age; document.getElementById("sal").value = empInfo.sal; document.getElementById("desc").value = empInfo.desc; var sexRadios = document.getElementsByName("sex"); for(var i=0;i<sexRadios.length;i++) { if(sexRadios[i].value == empInfo.sex) sexRadios[i].checked = true; } } } xhr.send(); } </script> </head> <body> <fieldset style="width: 300px"> <legend>人员信息</legend> <table width="100%"> <tr><td>ID</td><td><input type="text" id="id" /></td></tr> <tr><td>姓名</td><td><input type="text" id="name" /></td></tr> <tr><td>年龄</td><td><input type="text" id="age" /></td></tr> <tr><td>性别</td><td><input type="radio" value="0" name="sex" />男<input type="radio" value="1" name="sex" />女</td></tr> <tr><td>薪资</td><td><input type="text" id="sal" /></td></tr> <tr><td colspan="2">备注</td></tr> <tr><td colspan="2"><textarea rows="5" id="desc" style="width: 100%"></textarea></td></tr> </table> </fieldset> <input type="button" value="获取数据" onclick="getInfo()"/> </body></html>
?
配置Struts1.2支持--/ajax/WebRoot/WEB-INF/struts-config.xml:
?
?
<?xml version="1.0" encoding="ISO-8859-1" ?><!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.3//EN" "http://struts.apache.org/dtds/struts-config_1_3.dtd"><struts-config> <action-mappings> <action type="com.neusoft.ajax.EmpAction" scope="request" parameter="method" path="/emp" /> </action-mappings></struts-config>
?
后台数据包装后发送到前台处理--/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+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html> <head> <base href="<%=basePath%>"> <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" type="text/css" href="styles.css">--><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>ajax样例</title><style type="text/css"></style><script type="text/javascript"> function getXHR() { try { return new XMLHttpRequest(); } catch(e) { try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) { return new ActiveXObject("Msxml2.XMLHTTP"); } } } function getMsg() { var xhr = getXHR(); xhr.open("POST", "/ajax/emp.do?method=getMsg", true); xhr.onreadystatechange = function() { if (xhr.readyState == 4) { document.getElementById("msg").value = xhr.responseText; } } xhr.send(); }</script> </head> <body> <textarea rows="5" cols="100" id="msg"></textarea> <input type="button" value="获取数据" onclick="getMsg()"/> </body></html>?
最后配置工程启动xml,--/ajax/WebRoot/WEB-INF/web.xml
?
?
<?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE web-app PUBLIC"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN""http://java.sun.com/dtd/web-app_2_3.dtd"><web-app> <display-name>ajax</display-name> <!-- Standard Action Servlet Configuration --> <servlet> <servlet-name>action</servlet-name> <servlet-class>org.apache.struts.action.ActionServlet</servlet-class> <init-param> <param-name>config</param-name> <param-value>/WEB-INF/struts-config.xml</param-value> </init-param> <load-on-startup>2</load-on-startup> </servlet> <!-- Standard Action Servlet Mapping --> <servlet-mapping> <servlet-name>action</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <!-- The Usual Welcome File List --> <welcome-file-list> <welcome-file>pages/ajax.jsp</welcome-file> </welcome-file-list></web-app>