@ResponseBody注解的使用

一、前端

    @responseBody注解的做用是就是将controller层返回的对象经过适当的转换器转换为指定格式(JSON)后写入到HTTP response body中。json

    在使用注解后不会再走视图处理器,而是直接将数据写入到输入流中,他的效果等同于经过response对象输出指定格式的数据。app

    缺点:返回时,若是与前端编码格式不一致,很容易致使乱码。编码

二、  对象

返回对象:get

  @RequestMapping("/login",method=RequestMethod.POST,produces= {"application/json;charset=UTF-8"})
  @ResponseBody
  public User login(User user){//User字段:userName pwdit

      User user = new User();
  user.setUserName("xxx");
  user.setPwd("xxx");
  return user;
  }
  
  前台接收数据:'{"userName":"xxx","pwd":"xxx"}'

  效果等同于以下代码:
  @RequestMapping("/login")
  public void login(User user, HttpServletResponse response){
    response.getWriter.write(JSONObject.fromObject(user).toString());
  }io

相关文章
相关标签/搜索