<!-- 输出对象转String支持 -->
<bean id="stringConverter"
class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/plain;charset=UTF-8</value>
</list>
</property>
</bean>
<!-- 输出对象转JSON支持 -->
<bean id="jsonConverter"
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="stringConverter" />
<ref bean="jsonConverter" />
</list>
</property>
</bean>
package com.web.controller.rest.api;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
@Controller
public class RESTController {
// URI: http://localhost:8080/SpringMVC-RESTful-Json/hi
@RequestMapping(value = "/hi", produces = "text/plain;charset=UTF-8")
public @ResponseBody String hello() {
//logger.info("测试hi");
return "Hello World !!!";
}
// URI: http://localhost:8080/SpringMVC-RESTful-Json/say/hello world
@RequestMapping(value = "/say/{msg}", produces = "application/json;charset=UTF-8")
public @ResponseBody String say(@PathVariable("msg") String msg) {
return "{\"msg\":\"you say:'" + msg + "'\"}";
}
//POST
@RequestMapping(value = "/info", method = RequestMethod.POST)
public @ResponseBody Object addBook( ) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("msg", "添加信息成功!");
return jsonObject;
}
}