RadarURL

조회 수 1687 추천 수 0 댓글 0
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄 첨부
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄 첨부

Spring MVC 에서 하나의 Request 요청이 올때 보통 비지니스 로직을 거쳐, 가공된 데이터는 jsp 나 freemarker 같은 view단으로 보내지게 됩니다.

하지만 기존웹 & 모바일웹과 네이티브 모바일앱에 모두 대처하기 위해서는 단일 Request에서 해당 데이터를 jsp와 같은 view단을 위한 request mapping 뿐만 아니라, 모바일 Client을 위한 json , 크로스 도메인에 대처하기 위한 jsonp 까지 제공할려면 어떻게 해야 할까요.


예를 들어,

http://localhost/member/profile - 전통적인 view를 보여줍니다.
http://localhost/member/profile.json - json형태를 반화
http://localhost/member/profile.jsonp - jsonp 형태를 변환


ContentNegotiatingViewResolver


ContentNegotiatingViewResolver 를 이용하면, 위와 같이 하나의 URI에 *.json 등과같이 mediaType 에 변화를 줌으로써 해당 형태의 페이지를 각각 제공 해 줄 수 있습니다.


ContentNegotiatingViewResolver 의 사용 방법은 아래와 같습니다.

<bean class=" org.springframework.web.servlet.view.contentnegotiatingviewresolver">

<!-- ViewResolver 우선순위 설정 -->
<property name="order" value="1" />
<property name="mediaTypes">
<!-- 맵핑될 확장자 정의 -->
<map>
<entry key="json" value="application/json" />
<entry key="jsonp" value="javascript/jsonp" />
</map>
</property>
<property name="defaultViews">
<list>
<!-- JSON 요청을 처리할 뷰 -->
<bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView"/>
<!-- JSONP 요청을 처리할 뷰 -->
<bean class="com.jce.commons.controller.JSONPView">
<property name="contentType" value="javascript/jsonp"/>
</bean>
</list>
</property>
<property name="ignoreAcceptHeader" value="true" />
< /bean>



  • 기존의 FreeMarkerViewResolver 위에 위와 같이 ContentNegotiatingViewResolver를 정의합니다.
    mediaTypes의 entry의 key에 json, jsonp 등과 같이 원하는 형식의 mediaType 을 설정하고,
    entry에 view에는 json이라면 application/json과 같이 contentType을 설정합니다
    .
  • 설정된 mediaType 정보를 바탕으로 아래쪽 defaultViews 목록에 정의된 view들 중에서 랜더링 가능한 view를 찾게 됩니다. 그 기준은 defaultView의 list에 정의된 view class의 contentType 입니다.
  • list 의 JSONPView 같은 경우는 jsonp를 위해 정의한 클래스인데, 이와 같이 필요해 따라 개발자가 AbstractView를 상속받아 직접 구현 할 수 도 있습니다.



JSONPView

public class JSONPView extends AbstractView {

@Override
protected void renderMergedOutputModel(Map<String, Object> model,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
String callback = request.getParameter("callback")!=null?request.getParameter("callback"):"?";
ObjectMapper om = new ObjectMapper();
String json = om.writeValueAsString(model);
response.setContentType("javascript/jsonp");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(callback+"("+json+");");
}

}

Controller

@Controller
@RequestMapping("/member")
public class MemberContoller extends BaseController {
@RequestMapping(value="/profile", method=RequestMethod.GET)
public void profile(Model model) throws Exception {
List<Map<String,Object>> dataList = new ArrayList<Map<String, Object>>();
Map<String, Object> data = new HashMap<String,Object>();
data.put("name","정민혁");
data.put("lv:",10);
dataList.add(data);
data = new HashMap<String,Object>();
data.put("name","잡스");
data.put("lv",99);
dataList.add(data);
model.addAttribute("personList", dataList);
}
}


실제로 테스트 해보겠습니다.

default

normal.png

jsonp

jsonp.png

json

json.png

 

출처 : http://stunstun.tistory.com/37

?

공부 게시판

공부에 도움되는 글을 올려주세요.

  1. [공지] 공부 게시판 입니다.

    Date2003.08.18 By처누 Views928206
    read more
  2. WIndows Application의 실행 속도 측정

    Date2023.09.06 Category응용 프로그래밍 ByJaeSoo Views3185
    Read More
  3. [Apple] 엔터프라이즈 계정신청 (Enterprise Program)

    Date2023.03.27 Category응용 프로그래밍 ByJaeSoo Views267
    Read More
  4. [MSA] MSA란 무엇인가? 개념 이해하기

    Date2023.01.26 Category응용 프로그래밍 ByJaeSoo Views211
    Read More
  5. 메모리 영역 (code, data, stack, heap)

    Date2016.03.23 Category응용 프로그래밍 ByJaeSoo Views748
    Read More
  6. [SVN] Subversion 명령들

    Date2016.02.06 Category응용 프로그래밍 ByJaeSoo Views968
    Read More
  7. IBM JDK 1.6 에서 Spring 2.5.2를 사용할 때 GenericTypeResolver 에서 NullPointerException이 발생하는 문제

    Date2016.01.27 Category응용 프로그래밍 ByJaeSoo Views787
    Read More
  8. [전자정부 표준프레임워크] 톰캣(Tomcat) 설치하기

    Date2016.01.02 Category응용 프로그래밍 ByJaeSoo Views535
    Read More
  9. 프로그래밍 격언

    Date2015.03.04 Category응용 프로그래밍 ByJaeSoo Views398
    Read More
  10. 새로운 것을 배워야 좋은 프로그래머인가요?

    Date2015.02.13 Category응용 프로그래밍 ByJaeSoo Views319
    Read More
  11. 개발자&웹퍼블리셔 운영서버 배포관리는 어떻게 하시고 계신가요?

    Date2014.05.15 Category응용 프로그래밍 ByJaeSoo Views1288
    Read More
  12. 버전관리 - 형상관리, 소스세이프, CVS, Subversion(SVN), GIT, mercurial(hg), Perforce

    Date2014.05.15 Category응용 프로그래밍 ByJaeSoo Views1755
    Read More
  13. 빌드를 자동화하라 (Automate the Build)

    Date2014.05.15 Category응용 프로그래밍 ByJaeSoo Views1130
    Read More
  14. 단일화된 소스 저장소를 유지하라. (Maintain a Single Source Repository.)

    Date2014.05.15 Category응용 프로그래밍 ByJaeSoo Views1417
    Read More
  15. 지속적인 통합으로 피처요구사항 빌드하기 (Building a Feature with Continuous Integration)

    Date2014.05.15 Category응용 프로그래밍 ByJaeSoo Views1310
    Read More
  16. 지속적인 통합 (Continuous Integration)

    Date2014.05.15 Category응용 프로그래밍 ByJaeSoo Views1176
    Read More
  17. 변경관리/형상관리/빌드배포 자동화 연동 시 주요 이슈

    Date2014.05.15 Category응용 프로그래밍 ByJaeSoo Views1220
    Read More
  18. 형상관리의 기능 범주

    Date2014.05.15 Category응용 프로그래밍 ByJaeSoo Views1314
    Read More
  19. Conversion Struts to Spring MVC

    Date2014.05.09 Category응용 프로그래밍 ByJaeSoo Views1253
    Read More
  20. Spring 3.1 Overview

    Date2014.05.09 Category응용 프로그래밍 ByJaeSoo Views1147
    Read More
  21. Spring MVC 에서 ContentNegotiatingViewResolver를 이용한 단일 RequestMapping 으로 Muilti-View 처리하기

    Date2014.05.09 Category응용 프로그래밍 ByJaeSoo Views1687
    Read More
Board Pagination Prev 1 2 3 Next
/ 3


즐겨찾기 (가족)

JAESOO's HOMEPAGE


YOUNGAE's HOMEPAGE


장여은 홈페이지


장여희 홈페이지


장여원 홈페이지


즐겨찾기 (업무)

알리카페 홀릭

숭실대 컴퓨터 통신연구실 (서창진)

말레이시아 KL Sentral 한국인 GuestHouse


즐겨찾기 (취미)

어드민아이디

유에코 사랑회

아스가르드 좋은사람/나쁜사람

JServer.kr

제이서버 메타블로그

재수 티스토리


즐겨찾기 (강의, 커뮤니티)

재수 강의 홈페이지


한소리


VTMODE.COM


숭실대 인공지능학과


숭실대 통신연구실


베너