개인코딩공부방

[Spring framework] 자주쓰는 view Resolver 셋팅하기 ( ModelAndView-Ajax 편) 본문

웹/Spring Framework

[Spring framework] 자주쓰는 view Resolver 셋팅하기 ( ModelAndView-Ajax 편)

atlasia 2018. 12. 5. 15:34
[pom.xml]


<!-- jackson -->

		<dependency>

			<groupid>com.fasterxml.jackson.core</groupid>

			<artifactid>jackson-core</artifactid>

			<version>2.7.0</version>

		</dependency>

		<dependency>

			<groupid>com.fasterxml.jackson.core</groupid>

			<artifactid>jackson-databind</artifactid>

			<version>2.7.0</version>

		</dependency>

		<dependency>

			<groupid>com.fasterxml.jackson.core</groupid>

			<artifactid>jackson-annotations</artifactid>

			<version>2.7.0</version>

		</dependency>

[서블릿 설정 xml ] spring 3.x 이상, jackson 2.x이상 은 MappingJackson2JsonView, 그외에는 MappingJacksonJsonView 클래스 명을 사용한다.


<!-- ajax를 처리할 resolver의 load 순서를 0으로 하여 먼저 인식하도록 함  -->

<bean class="org.springframework.web.servlet.view.BeanNameViewResolver" p:order="0">

	

	<bean id="jsonView" class="org.springframework.web.servlet.view.json.MappingJackson2JsonView">

		<property name="contentType" value="application/json;charset=UTF-8">

	</property></bean>



<!-- order 프로퍼티를 수정하여  인식 순서를 변경 -->

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

		<property name="order" value="1">

	</property></bean>

	

<!-- 여러가지를 먼저 처리할 resolver가 있는 경우 스프링 기본제공 resolver는 최하위 순서가 되는 경우가 많다. 그냥 맨 뒤로 빼자 -->

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

        <!-- Example: a logical view name of 'showMessage' is mapped to '/WEB-INF/jsp/showMessage.jsp' -->

        <property name="order" value="2">

        <property name="prefix" value="/WEB-INF/views/**/">

        <property name="suffix" value=".jsp">

	</property></property></property></bean>  
</bean>
[controller 예시]


/**

	 * ajax컨트롤러 예시

	 */

	@RequestMapping(path = "init", method = RequestMethod.GET, produces="application/json;charset=UTF-8")

	@ResponseBody

	public ModelAndView ajaxController(HttpServletRequest request, HttpServletResponse response, HashMap<string, string=""> param, Model model) throws Exception {
               //xml의 (MappingJsckson2JsonView  or MappingJscksonJsonView )의 bean id와 동일하게 생성
		ModelAndView mav = new ModelAndView("jsonView");

		mav.addObject("data", "addedData");

		return mav;

	}


Comments