1、导对包包
这里是核心包commons-fileupload-1.3.2.jarcommons-io-2.4.jarcommons-lang3-3.4.jarfreemarker-2.3.23.jarjavassist-3.20.0-GA.jarlog4j-api-2.7.jarognl-3.1.12.jarstruts2-core-2.5.8.jar这里是JSON依赖包,(ToT这里可坑哭我了,没导对一直报错...)commons-beanutils-1.9.2.jarcommons-collections-3.2.1.jarcommons-lang-2.4.jarezmorph-1.0.6.jarjson-lib-2.3-jdk15.jarstruts2-json-plugin-2.5.10.jar2、struts2实现Ajax、json重点在于struts.xml
1、<package>标签的写法:<package name="随意" namespace="/" extends="json-default"> //extends必须继承"json-default"</package>2、<result>标签的写法:<result type="json">//type必须写json //不写<param>标签即该action下所有返回的变量 <param name="root">要改成json格式的变量</param></result>3、其它就和常规一样…举个小栗子
JsonAction.javapublic class JsonAction extends ActionSupport{ PRivate User user;//User类就name、age; private JSONArray jsonArray; @Override public String execute() throws Exception { System.out.println("测试数据"); List<User> list=new ArrayList<User>(); list.add(new User("小福",17)); list.add(new User("王优",52)); list.add(new User("布赫优",34)); jsonArray=JSONArray.fromObject(list); return SUCCESS; } public JSONArray getJsonArray() { return jsonArray; } public void setJsonArray(JSONArray jsonArray) { this.jsonArray = jsonArray; } public User getUser() { return user; } public void setUser(User user) { this.user = user; }}struts.xml<struts> <package name="ajax" namespace="/" extends="json-default"> <!-- <action name="ajax" class="com.action.AjaxAction"> </action> --> <action name="json" class="com.action.JsonAction" > <result type="json"> <param name="root">jsonArray</param> </result> </action> </package></struts>JSON.jsp(用js写的显得很多,jq的话很方便,但是不会)<html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>Insert title here</title><script type="text/Javascript">window.onload=function(){ var bt=document.getElementById("bt"); bt.onclick=function(){ var xmlhttp=new XMLHttpRequest; xmlhttp.open("POST","json"); xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); xmlhttp.send(); xmlhttp.onreadystatechange=function(){ if (xmlhttp.readyState==4) { if (xmlhttp.status==200) { var msg=document.getElementById("msg"); var redata=xmlhttp.responseText.toString(); var myjson=JSON.parse(redata); var text=""; for(var i=0;i<myjson.length;i++){ text+=myjson[i].name+":"; text+=myjson[i].age+", "; } msg.innerHTML=text; } } } }}</script></head><body><button id="bt">点我获取JSON</button><h1 id="msg"></h1></body></html>效果图
新闻热点
疑难解答