Spring MVC – 21 – JSON View | @ResponseBody

Merhaba Arkadaslar,
Bu JSON entegrasyonunu gerceklestirecegiz.

  • JSON , JavaScript Object Notation anlamina gelmektedir.
  • JSON , veri degisimi (exchange data) ve veri saklanmasi (data store) icin kullanilan bir veri degisim formatidir.
  • JSON , XML’e alternatif olarak gelistirilmistir.
  • JSON , dil bagimsizdir , anlasilmasi kolaydir.

Daha fazla bilgi icin ;

http://www.w3schools.com/json/
http://json.org/json-tr.html
https://tr.wikipedia.org/wiki/JSON

Ornek bir JSON tanimlamasi;

{"employees":[
    {"firstName":"John", "lastName":"Doe"},
    {"firstName":"Anna", "lastName":"Smith"},
    {"firstName":"Peter", "lastName":"Jones"}
]}

XML tanimlamasini inceleyecek olursak ;

<employees>
    <employee>
        <firstName>John</firstName> <lastName>Doe</lastName>
    </employee>
    <employee>
        <firstName>Anna</firstName> <lastName>Smith</lastName>
    </employee>
    <employee>
        <firstName>Peter</firstName> <lastName>Jones</lastName>
    </employee>
</employees>

XML ve JSON formatlari ornegin web servislerde kullanilmaktadir. Burada basit bir uygulama yapalim ve Spring MVC icin entegrasyonu gerceklestirelim.

Oncelikle projemize gerekli dependency tanimlarini ekleyelim.

pom.xml

<properties>
 	<!-- updated 10.02.2016 -->
 	....
	<jackson.version>2.8.6</jackson.version>
</properties>


<!-- Jackson Mapper -->
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>${jackson.version}</version>
</dependency>

Domain model sinifimizi ekleyelim ;

Person.java

package _22.json.model;

public class Person {

	private String id;
	private String name;
	private String surname;
	private String birthYear;

	public Person(String id, String name, String surname, String birthYear) {
		super();
		this.id = id;
		this.name = name;
		this.surname = surname;
		this.birthYear = birthYear;
	}

	//getters and setters

}

JSONController.java
@ResponseBody annotation ‘ini kullanildiginda  uygun formata donusturme islemi yapilir. Uygun formatlar , JSON , XML vs.
Spring bunun icin uygun HttpMessageConverter implementation’ini kullanir.

package _22.json.controller;

import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import _22.json.model.Person;

@Controller
public class JSONController {

	@RequestMapping("/getPerson")
	@ResponseBody
	// http://localhost:8080/injavawetrust.springmvc/getPerson
	public Person getPerson() {
		return new Person("1", "Levent", "Erguder", "1989");
	}

	@RequestMapping("/getPersonList")
	@ResponseBody
	// http://localhost:8080/injavawetrust.springmvc/getPersonList
	public List<Person> getPersonList() {
		// prepare data
		Person person1 = new Person("1", "Levent", "Erguder", "1989");
		Person person2 = new Person("2", "James", "Gosling", "1955");
		Person person3 = new Person("3", "Joshua", "Bloch", "1961");

		List<Person> personList = new ArrayList<Person>();
		personList.add(person1);
		personList.add(person2);
		personList.add(person3);

		return personList;
	}

}

22.json.xml
@ResponseBody annotation inin calismasi icin <mvc:annotation-driven> tagini eklememiz gereklidir.
Aksi durumda HTTP Status 406 hatasi aliriz;
The resource identified by this request is only capable of generating responses with characteristics not acceptable according to the request “accept” headers.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc 
        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
        ">
	
	<context:component-scan base-package="_22.json.controller" />
	<mvc:annotation-driven />
    
</beans>

web.xml

...
<init-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>                                   
    <!--            
     /WEB-INF/01.appContext.xml
     /WEB-INF/02.00.appContext.xml
     /WEB-INF/03.multiActionController.xml
     ....
     -->
     /WEB-INF/22.json.xml
    </param-value>                  
</init-param>  
...

Ornegimizi calistirdigimizda;

http://localhost:8080/injavawetrust.springmvc/getPerson

json example

http://localhost:8080/injavawetrust.springmvc/getPersonList

Github kaynak kodlar / source folder
Injavawetrust-springmvc-tutorial

Yazimi burada sonlandiriyorum.
Herkese Bol Javali Gunler dilerim.
Be an oracle man , import java.*;
Levent Erguder
OCP, Java SE 6 Programmer
OCE, Java EE 6 Web Component Developer

Print Friendly, PDF & Email

Leave a Reply

Your email address will not be published. Required fields are marked *