トッカンソフトウェア

Spring MVC JSON

今回はJSONをやります。Jacksonを使います。Jacksonの使い方はこちらを参照下さい。


設定ファイル

web.xml、applicationContext.xmlはJspと同じです。

pom.xml

jackson-databindを追加します。これを追加しないと、「415 Unsupported Media Type」エラーが発生します。
				
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>springMVC</groupId>
	<artifactId>springMVC</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>
	<build>
		<plugins>
			<plugin>
				<artifactId>maven-war-plugin</artifactId>
				<version>3.2.3</version>
			</plugin>
			<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.8.1</version>
				<configuration>
					<release>16</release>
				</configuration>
			</plugin>
		</plugins>
	</build>
	<dependencies>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>5.3.22</version>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>4.0.1</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-databind</artifactId>
			<version>2.13.4</version>
		</dependency>
	</dependencies>
</project>

			

コントローラ

アノテーションに@Controllerを指定した場合、メソッドに@ResponseBodyを指定して下さい。
@RestControllerを指定する場合は、@ResponseBodyを指定しなくて良いです。

戻り値のオブジェクトがJSONに変換されてクライアントに戻されます。

JsonControler.java
				
package spring.test.controller;

import java.util.HashMap;
import java.util.Map;

import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import spring.test.UserModel;

//@RestController
@Controller
public class JsonControler {

	@ResponseBody
	@RequestMapping(value = "/testjson", method = RequestMethod.GET)
	public UserModel jsonGet() {
		UserModel um = new UserModel();
		um.setId("0001");
		um.setName("名前");
		return um;
	}

	@RequestMapping(value = "/loginj", method = RequestMethod.GET)
	public String loginGet() {
		return "loginj";
	}

	@ResponseBody
	@RequestMapping(value = "/loginj", method = RequestMethod.POST, 
				consumes = MediaType.APPLICATION_JSON_VALUE)
	public Map<String, Object> jsonPost(@RequestBody UserModel um) {
		Map<String, Object> ret = new HashMap<>();
		if (um.getId().equals("abc")) {
			um.setName("ABCさん");
			ret.put("ret", true);
			ret.put("user", um);
		} else {
			ret.put("ret", false);
		}
		return ret;
	}
}

			
consumes = MediaType.APPLICATION_JSON_VALUE を指定した場合、呼び出し側で contentType : "application/json" を指定する必要があります。

Model

モデルはJspで作成したUserModelを使用します。

Jsp

loginj.jsp という名前で作成します。
Jsonの送受信はJqueryの$.ajaxを使用します。

loginj.jsp
				
<%@page import="spring.test.controller.JsonControler"%>
<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<html>
<head>
<title>ログイン</title>
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script type="text/javascript">
	$(function() {

		$("#btn").click(function() {
			$("#msg").empty();
			var param = {
				"id" : $("#txt").val()
			};
			$.ajax({
				type : "POST",
				contentType : "application/json",
				url : "/springMVC/loginj",
				data : JSON.stringify(param)
			}).done(function(data, status, xhr) {
				// 正常
				$("#msg").append(JSON.stringify(data));
			}).fail(function(xhr, status, error) {
				// 異常
				$("#msg").append(xhr);
				$("#msg").append(":" + status);
				$("#msg").append(":" + error);
			}).always(function(data, status, xhr) {
				// 常に
				$("#msg").append("END");
			});
		});
	});
</script>
</head>
<body>
	ID:
	<input id="txt" type="text" />
	<BR />
	<input type="button" id="btn" value="ボタン" />
	<BR />
	<div id="msg"></div>
</body>
</html>

			
JavaScriptでは処理の最初にbtnボタンを押したときに、msgをクリアし、AjaxでJson情報をサーバに送り、戻ってきた値をmsgに書き込む、ということをやっています。

$(function() { が初期化処理(最初に呼ばれる処理)で $("#btn").click(function() { がbtnボタン押したときの処理を定義しています。

ボタンを押した時の処理の$.ajaxでJsonをサーバ送り、正常に処理された場合、.doneが処理され、異常が発生した場合、.failが処理されます。
正常、異常のどちらの場合でも最後に.alwaysが処理されます。

contentType : "application/json" を指定していますが、これはコントローラ側で consumes = MediaType.APPLICATION_JSON_VALUE を指定しているためで、 指定していなければ省略しても動作します。

data : の指定でJSON.stringifyを呼び出していますが、これがJavaScriptオブジェクトからJSON文字列に変換してくれます。
正常処理時もJavaScriptに戻り値オブジェクトがセットされるので、JSON文字列に変換してmsgに出力しています。


実行イメージ
http://localhost:8080/springMVC/loginj


ページのトップへ戻る