JSON뷰를 이용하여 AJAX를 사용할 수 있게 설정하는 방법입니다.
예제는 전자정부 프레임웤으로 했습니다.
사실 pom.xml과 dispatcher에는 기본적으로 등록되어있었습니다.
다른 스프링기반 프레임웤들은 직접 추가해주시면 됩니다.
<dependency> <groupId>net.sf.json-lib</groupId> <artifactId>json-lib</artifactId> <version>2.4</version> <classifier>jdk15</classifier> </dependency> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> <version>1.6.4</version> </dependency>
<bean class="org.springframework.web.servlet.view.BeanNameViewResolver" id="viewResolver" p:order="0"/> <bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView" id="jsonView"> <property name="contentType" value="application/json;charset=UTF-8"/> </bean>
<servlet-mapping> <servlet-name>action</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>action</servlet-name> <url-pattern>*.ajax</url-pattern> </servlet-mapping>
@RequestMapping("/test.do") public String test(@ModelAttribute("searchVO") CommentVO commentVO, ModelMap model) throws Exception { return "test/test"; } @RequestMapping("/test.ajax") public ModelAndView testAjax(@ModelAttribute("searchVO") CommentVO commentVO, ModelMap model) throws Exception { Map resultMap = new HashMap(); resultMap.put("result1", "test1"); resultMap.put("result2", "test222"); ModelAndView modelAndView = new ModelAndView("jsonView",resultMap); return modelAndView; }
<script type="text/javascript"> <!-- $.post("${pageContext.request.contextPath}/test.ajax", { test1: "1111", test2: "2222" }, function(data) { alert("result: " + data); } ); --> </script>
END