import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
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 test.Service.impl.UserServiceImpl;
import test.domain.User;
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
private UserServiceImpl userService;
@ResponseBody
@RequestMapping(value = "showUser",method = RequestMethod.GET)
public Object showUser(){
//return net.sf.json.JSONObject.fromObject("");
User user = userService.getUserById(1);
String str = JSON.toJSONString(user);
return str;
}
@ResponseBody
@RequestMapping(value = "test",method = RequestMethod.GET)
public Object test(){
//return net.sf.json.JSONObject.fromObject("");
User user = userService.getUserById(2);
String str = JSON.toJSONString(user);
return str;
}
}
@ResponseBody
作用:
该注解用于将Controller的方法返回的对象,通过适当的HttpMessageConverter转换为指定格式后,写入到Response对象的body数据区。
使用时机:
返回的数据不是html标签的页面,而是其他某种格式的数据时(如json、xml等)使用;
@ResponseBody 将内容或对象作为 HTTP 响应正文返回,并调用适合HttpMessageConverter的Adapter转换对象,写入输出流