转载:http://www.apk-doc.net/spring-mvc/spring-mvc-json-2.html
前面第一篇讲述了,搭建spring mvc环境,这里我们主要使用spring mvc的注解方式快速构建web
注解:
@Controller 表示控制器
@RequestMapping("/hello") 表示控制器访问路径为/hello
@ResponseBody 表示返回的是json串
/** * * @author 喧嚣求静 * * blog:www.apk-doc.net * * * * * */ @Controller public class HelloWorldController { @RequestMapping("/hello") public String hello( @RequestParam(value = "name", required = false, defaultValue = "World") String name, Model model) { model.addAttribute("name", name); return "helloworld"; } @RequestMapping("/hello2") @ResponseBody public Map<String, Object> hello2(HttpServletRequest request, HttpServletResponse response, HttpSession session) { String name = request.getParameter("name"); Map<String, Object> map = new HashMap<String, Object>(); map.put("name", name); return map; } }
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <context:component-scan base-package="com.smsc"/> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix"> <value>/WEB-INF/views/</value> </property> <property name="suffix"> <value>.jsp</value> </property> </bean> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <list> <ref bean="stringHttpMessageConverter" /> <ref bean="mappingJacksonHttpMessageConverter" /> </list> </property> </bean> <bean id="stringHttpMessageConverter" class="org.springframework.http.converter.StringHttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/plain;charset=UTF-8</value> <value>text/html;charset=UTF-8</value> </list> </property> </bean> <bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>application/json;charset=UTF-8</value> <value>text/html;charset=UTF-8</value> </list> </property> </bean> <mvc:annotation-driven content-negotiation-manager="contentNegotiationManager" /> <bean id="contentNegotiationManager" class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean"> <property name="favorPathExtension" value="false" /> <property name="favorParameter" value="false" /> <property name="ignoreAcceptHeader" value="false" /> <property name="mediaTypes"> <value> atom=application/atom+xml html=text/html json=application/json *=*/* </value> </property> </bean> </beans>