Completely just a note I use it when fetching data without screen transition
Struts2.0.11.2 (too old ...) Java 8 (old ...)
JSP
sample.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<input type="button" value="Send" onClick="getSampleData();" />
jsonArray.jsp
<!--Do I have to receive the response like this ...?-->
<%@ page language="java" contentType="text/javascript; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<s:property value="jsonArray" escape="false"/>
JavaScript(Ajax)
sample.js
function getSampleData() {
new Ajax.Request("GetSampleData.action", {
method : 'GET',
onSuccess : function(res) {
var arr = JSON.Parse(res.responseText);
arr.forEach(function(data){
console.log(data.id + ":" + data.name);
}
},
onError : function() {
console.log("Error");
},
onComplete : function() {
console.log("Complete");
}
})
}
struts.xml
struts.xml
<action name="GetSampleData" class="PATH.BuildSampleData">
<result>PATH/jsonArray.jsp</result>
</action>
Action Class
BuildSampleData.java
package hogehoge.fugafuga
import java.util.ArrayList;
import net.sf.json.JSONObject;
public class BuildLoginData {
private ArrayList<JSONObject> jsonArray = new ArrayList<JSONObject>();
//Execute if Action method is not specified()Is called
public String execute() throws Exception {
JSONObject tarou = new JSONObject();
tarou.put("id", 1);
tarou.put("name", "tarou");
jsonArray.add(tarou);
JSONObject hanako = new JSONObject();
hanako.put("id", 2);
hanako.put("name", "hanako");
jsonArray.add(hanako);
return "success";
}
public ArrayList<JSONObject> getJsonArray() {
return jsonArray;
}
public void setJsonArray(ArrayList<JSONObject> jsonArray) {
this.jsonArray = jsonArray;
}
}
It's annoying to have to prepare jsp when receiving the response from the server. Is there any other way ...?
Recommended Posts