Spring MVC でjQueryのAjax関数を使用する1 〜 JSON作成にGSONを使用する
引き続きベースは「Spring MVCのサンプルプロジェクトでViewの描画をthymeleafテンプレートエンジンによるものに変更する」から続いているもの。
これまでは同期通信で画面遷移を伴うものだったが、今は画面遷移を伴わずに非同期通信を行ってデータだけを取得するものが主流(のはず)。
今回は、jQueryのAjax関数を使用して、ページ遷移を行わずにサーバからデータを取得する方法をメモする。
まずは、クライアントサイドのHTML。個人的なポイントは次の2つ。
・javascriptはwebapp/resources/jsに配置しており、src="resources/js/jquery-1.11.0.js"として読み込む。
・formサブミット時のactionの指定は、action="/sample/getJSON"のように指定する。/getJSONがコントローラの@RequestMappingに指定する値である。
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Ajaxテストデータ表示画面</title> <script src="resources/js/jquery-1.11.0.js" type="text/javascript"></script> <script type="text/javascript"> $(function() { $("#test").click(function() { $.ajax({ type : "GET", url : "/sample/getJSON", // リクエストURL dataType : "json", cache : false, success : function(data, status, xhr) { alert("success"); alert(data); }, error : function(XMLHttpRequest, status, errorThrown) { alert("fail:" + XMLHttpRequest); alert("status:" + status); } }); }); }); </script> </head> <body> <div id="map"></div> <p> <input type="button" id="test" value="ajax" /> <br /> </p> <form action="/sample/getJSON" method="GET"> <input type="submit" id="test" value="notAjax" /> <br /> </form> </body> </html>
◎次にコントローラ。
@Controller @RequestMapping("/") public class HomeController { private static final Logger logger = LoggerFactory .getLogger(HomeController.class); @RequestMapping(value = "/getJSON", method = RequestMethod.GET) @ResponseBody public String getJSON(){ logger.info("called getJSON"); Gson gson = new Gson(); List<String> strList = new ArrayList<String>(); strList.add("test1"); strList.add("test2"); return gson.toJson(strList); } }