struts2中使用JSON插件实现AJAX

1.下载JSON插件jsonplugin-0.32.jar,并导入到工程中

  http://code.google.com/p/jsonplugin/downloads/list

2.下载prototype.js(可选),并放到WebContent/js中

  http://www.prototypejs.org/assets/2007/11/6/prototype.js

  这个脚本里有调用ajax的方法,并封装了一些实用的方法(如提取Form中要提交的参数), 如果不用到这些方法可以不用,本文没有用到

3.问题说明

  (1)Form.serialize中文乱码

  其中Form.serialize($('converge')),是把converge表单中所有的字段,拼成method=xxx&type=sss的形式。

  在prototype的函数中,会把key和value分别用encodeURIComponent 来把一个字符串转成utf-8的URL编码形式。比如,“中文”会被编码成:%E4%B8%AD%E6%96%87

但该字符串传到后台时,会被识别成乱码. 用request.getParameter取到的字符串也是乱码,而不是本身的字符。

  主要原因是%号,如果该串改成%22E4%22B8%22AD%22E6%2296%2287 也是可以识别的.

  解决方法: 在prototype文件中找到 encodeURIComponent  这段, 在encodeURIComponent 后,再将该字符串用escape方法再编码一次。 这时候传到后台,用request.getParameter,可以得到编码后的正确的字符串。即 %E4%B8%AD%E6%96%87 .

这时,可以用java.net.URLDecoder.decode(keyword, "UTF-8");  对这个字符串进行解码,从而得到正确的中文。

  (2)页面中的request.readyState 是 HTTP 的就绪状态。

  request.readyState == 0 :请求没有发出(在调用 open() 之前)。
  request.readyState == 1 :请求已经建立但还没有发出(调用 send() 之前)。
  request.readyState == 2 :请求已经发出正在处理之中(这里通常可以从响应得到内容头部)。
    request.readyState ==3 :请求已经处理,响应中通常有部分数据可用,但是服务器还没有完成响应。
  request.readyState == 4 :响应已完成,可以访问服务器响应并使用它。



4.源码

配置struts

web.xml
<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">  <display-name>SampleSS</display-name>    <filter>    <filter-name>struts2</filter-name>    <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>  </filter>    <filter-mapping>    <filter-name>struts2</filter-name>    <url-pattern>/*</url-pattern>  </filter-mapping>    <welcome-file-list>      <welcome-file>/jsp/SampleJsp.jsp</welcome-file>    <welcome-file>index.html</welcome-file>    <welcome-file>index.htm</welcome-file>    <welcome-file>index.jsp</welcome-file>    <welcome-file>default.html</welcome-file>    <welcome-file>default.htm</welcome-file>    <welcome-file>default.jsp</welcome-file>  </welcome-file-list></web-app>


SampleJsp.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8"%><%@ taglib prefix="s" uri="/struts-tags" %><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>Insert title here</title><script src="<%=request.getContextPath()%>/js/Prototype.js" type="text/javascript"></script><script type="text/javascript">    var xmlHttpSupport = (typeof XMLHttpRequest != "undefined" || window.ActiveXObject);    if (typeof XMLHttpRequest == "undefined" && window.ActiveXObject) {        function XMLHttpRequest() {            var arrSignatures = ["MSXML2.XMLHTTP.5.0", "MSXML2.XMLHTTP.4.0",                                 "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP",                                 "Microsoft.XMLHTTP"];            for (var i=0; i < arrSignatures.length; i++) {                try {                    var oRequest = new ActiveXObject(arrSignatures[i]);                    return oRequest;                } catch (oError) { /*ignore*/ }            }            throw new Error("MSXML is not installed on your system.");        }    }    function appendXmlValue(key, value) {        var str = "\n<" + key + ">" + value + "</" + key + ">";        return str;    }    function ajaxSubmit() {        if(xmlHttpSupport) {            var sUrl = "SampleAction.action";            var request = new XMLHttpRequest();            request.onreadystatechange = function() {                if(request.readyState == 4) {                    var result = eval("(" + request.responseText + ")");                    document.getElementById("result").innerHTML = "<span>" + result.sum + "</span>";                }            };            request.open('POST', sUrl);            var xmlStr = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><RequestInfo>";            var params = Form.serialize("sampleForm");//通过prototype.js脚本获取Form表单中提交的数据(也可以手动完成如下面注释掉的部分)//          xmlStr += appendXmlValue("id", document.getElementById("id").value);//          xmlStr += appendXmlValue("name", document.getElementById("name").value);            var paraList = params.split("&");            for(var i=0; i<paraList.length; i++) {                var temp = paraList[i].split("=");                xmlStr +=  appendXmlValue(temp[0], temp[1]);            }            xmlStr += "</RequestInfo>";            request.send(xmlStr);        }    }</script></head><body>    <label>输入字符判断界面是否刷新</label><input>    <form action="SampleAction_add.action" method="post" id="sampleForm">        <label>id</label><input id="id" type="text" name="id">        <label>name</label><input id="name" type="text" name="name">        <input type="button" value="ajaxSubmit" onclick="ajaxSubmit()" />    </form>    <label>IdAndName:</label>    <label id="result"></label></body></html>


struts配置文件,package的extends改为"json-default"

struts.xml
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE struts PUBLIC    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"    "http://struts.apache.org/dtds/struts-2.0.dtd"><struts>    <package name="struts" extends="json-default">        <action name="SampleAction" class="com.zz.action.SampleAction">            <result type="json"></result>        </action>    </package></struts>


SampleAction.java
package com.zz.action;import com.opensymphony.xwork2.ActionSupport;import com.zz.vo.SampleVo;import com.zz.util.DocObject;@SuppressWarnings({"serial", "unchecked"})public class SampleAction extends ActionSupport {        private SampleVo svo;    String sum;    @Override    public String execute() {        DocObject doc = null;        try {            javax.servlet.ServletInputStream inputStream = org.apache.struts2.ServletActionContext.getRequest().getInputStream();            doc = new DocObject(inputStream);            svo = new SampleVo();            svo.setId(doc.getNodeValue("id"));            svo.setName(doc.getNodeValue("name"));                    } catch (Exception e) {            e.printStackTrace();        } finally {            if (doc != null)                doc.close();        }                if(svo!=null) {            sum = svo.getId() + svo.getName();        }        return com.opensymphony.xwork2.Action.SUCCESS;    }        public SampleVo getSvo() {        return svo;    }    public void setSvo(SampleVo nvo) {        this.svo = nvo;    }    public String getSum() {        return sum;    }    public void setSum(String sum) {        this.sum = sum;    }    }


DocObject.java
package com.zz.util;import java.io.IOException;import java.io.InputStream;import javax.xml.parsers.DocumentBuilder;import javax.xml.parsers.DocumentBuilderFactory;import javax.xml.parsers.ParserConfigurationException;import org.w3c.dom.Document;import org.w3c.dom.Element;import org.w3c.dom.Node;import org.w3c.dom.NodeList;import org.xml.sax.SAXException;/** * 使用ajax时解析xml文件 * @author zz *  */public class DocObject {    private Node rootNode;    private InputStream stream;    public DocObject(InputStream stream) throws ParserConfigurationException,            SAXException, IOException {        this.stream = stream;        DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory                .newInstance();        DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();        Document doc = docBuilder.parse(stream);        NodeList parameters = doc.getElementsByTagName("RequestInfo");        if (parameters != null)            rootNode = parameters.item(0);    }    public String getNodeValue(String nodeName) {        String s = "";        if (rootNode.getNodeType() == Node.ELEMENT_NODE) {            Element rootElement = (Element) rootNode;            NodeList childList = rootElement.getElementsByTagName(nodeName);            Element childElement = (Element) childList.item(0);            if (childElement != null) {                NodeList textFNList = childElement.getChildNodes();                if (textFNList != null){                    Node temp = (Node) textFNList.item(0);                    if(temp != null){                        s = temp.getNodeValue();                        if (s != null)                            s = s.trim();                    }                }            }        }        return s;    }    public void close() {        if (stream != null) {            try {                stream.close();            } catch (Exception e) {            }        }    }}


SampleVo.java
package com.zz.vo;public class SampleVo {        private String id;    private String name;        public String getId() {        return id;    }    public void setId(String id) {        this.id = id;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    }

你可能感兴趣的:(jsp,Ajax,json,struts,prototype)