본문 바로가기
프레임워크/[Java] spring

ContentNegotiatingViewResolver를 이용한 XML, JSON 뷰 만들기

by hs_seo 2013. 4. 16.

ContentNegotiatingViewResolver를 이용하면 xml, json 뷰를 편하게 만들 수 있다. 

서블릿 컨텍스트에 ContentNegotiatingViewResolver와 json뷰, xml 뷰 설정을 처리하도록 한다. 


json 뷰는 MappingJacksonJsonView를 이용하고, xml 뷰는 Jaxb2Marshaller를 이용하도록 한다. 

* 이 두가지 뷰외에도 다양한 뷰가 있다. 다른 뷰를 활용하는 방법도 찾아보면 좋을 것 같다. 


servlet-context.xml 은 다음과 같이 설정한다. 

	



	
	
	
	

	
	

	
	
		
		
	
	
	
	
	
	
		
		
			
				
				
			
		

		
		
		
			
				
					
				
				
                    
                    
                
			
		
	
	
	
	
        
            
                sdk.spring.xml.model.XmlData
            
        
    

그러면 일단 설정은 완료 되었다. 

Jaxb2Marshaller는 마샬링을 처리하려고 하는 Java 클래스를 꼭 지정해 주어야 한다. 그러지 않으면 오류가 발생 한다.


컨트롤러의 구현은 다음과 같다. 


 
package sdk.spring.xml;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import sdk.spring.xml.model.XmlChildData;
import sdk.spring.xml.model.XmlData;

/**
 * Handles requests for the application home page.
 */
@Controller
public class ViewController {
	
	/**
	 * Json 데이터는 다음과 같이 Map 에 넣으면 출력된다. 
	 * 
	 * @param model
	 */
	@RequestMapping(value = "/jsondata", method = RequestMethod.GET)
	public void jsondata(Model model) {
		
		List> list = new ArrayList>();
		Map data1 = new HashMap();
		data1.put("name", "a");
		
		Map data2 = new HashMap();
		data2.put("name", "b");
		
		list.add(data1);
		list.add(data2);
		
		model.addAttribute("data", list);
	}
	
	/**
	 * Jaxb2Marshaller 는 마샬링을 위한 클래스가 필요하므로 
	 * 다음과 클래스를 선언해주어야 한다. 
	 * 
	 * @param model
	 */
	@RequestMapping(value = "/xmldata", method = RequestMethod.GET)
	public void xmldata(Model model) {
		
		List list = new ArrayList();
		
		XmlChildData child1 = new XmlChildData();
		child1.setEmail("1");
		child1.setName("a");
		child1.setPosition("z");
		
		XmlChildData child2 = new XmlChildData();
		child2.setEmail("2");
		child2.setName("b");
		child2.setPosition("x");
		
		list.add(child1);
		list.add(child2);
		
		XmlData data = new XmlData();
		data.setItems(list);
		
		model.addAttribute("data", data);
	}
}

컨트롤러는 위와 같이 등록하면된다. 

마샬링을 위한 Java 데이터 객체는 다음과 같이 등록한다. 


package sdk.spring.xml.model;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;

@XmlAccessorType(XmlAccessType.FIELD)
public class XmlChildData {

	@XmlElement(name = "email")
	private String email;

	@XmlElement(name = "name")
	private String name;

	@XmlElement(name = "position")
	private String position;

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getPosition() {
		return position;
	}

	public void setPosition(String position) {
		this.position = position;
	}
}
package sdk.spring.xml.model;

import java.util.List;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "root")
public class XmlData {

	@XmlElement(name = "items")
	private List items;

	public List getItems() {
		return items;
	}

	public void setItems(List items) {
		this.items = items;
	}
}


결과값은 다음과 같이 볼수 있다. 

http://localhost:1180/xml/xmldata.json

{"data":{"items":[{"email":"1","name":"a","position":"z"},{"email":"2","name":"b","position":"x"}]}}


http://localhost:1180/xml/xmldata.xml


<root>
<items>
<email>1</email>
<name>a</name>
<position>z</position>
</items>
<items>
<email>2</email>
<name>b</name>
<position>x</position>
</items>
</root>

와 같은 결과를 얻을 수 있다. 

물론 jsondata.json 으로 접근해도 동일한 결과를 얻을 수 있지만 jsondata.xml 으로는 결과를 얻을 수 없다. 
Map 은 마샬링 객체로 등록이 되어 있지 않기 때문이다. 



* Java 코드 끝에 XML 데이터가 들어 가있는것은... syntaxhighlighter의 오류인 것같다... 없애도 다시 생긴다.


반응형

'프레임워크 > [Java] spring' 카테고리의 다른 글

AOP로 로그 남기기  (0) 2013.04.11