LoginSignup
4
3

More than 5 years have passed since last update.

Struts2 + AjaxでGETするメモ

Last updated at Posted at 2018-07-31

はじめに

完全にただのメモ
画面遷移させずにデータ取ってきたりとかするときに使ってます

環境

Struts2.0.11.2(古すぎ・・・)
Java 8(古・・・)

コーディング

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="送信" onClick="getSampleData();" />
jsonArray.jsp
<!-- レスポンスはこうやって受け取らなきゃいけないのか・・・? -->
<%@ 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>();

  // Actionメソッド指定なしだとexecute()が呼ばれる
  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;
  }
}

感想

サーバーからのレスポンス受け取った時、jspを用意しておかないといけないのがめんどくさい。
他にやり方があるのかな・・・?

4
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
3