SpringMvc对JSON的处理与AJAX示例

/**

   * 测试自定义AJAX JSON

   */

  @RequestMapping("/testJson")

  public void testJson(HttpServletResponse response) throws Exception{

  User user = new User();

  user.setName("zhanghw");

  user.setRealName("zhanghongwei");

  JSONObject json = JSONObject.fromObject(user);

  PrintWriter out = response.getWriter();

  out.print(json.toString());

  }

<script type="text/javascript"  src="${pageContext.request.contextPath}/js/jquery.js"></script>

<script type="text/javascript">

  $(function() {//测试ajax json

  $.ajax({

  type : "post",

  url : "${pageContext.request.contextPath}/testJson.action",

  success : function(data) {

  alert(data);

  console.log(data);

  },

  dataType : "json"

  });

  });

</script> 

SpringMVC中,可以使用@ResponseBody注解快速生成json数据但需要jackson类库支持。

配置要求:

<context:annotation-config />

<mvc:annotation-driven />  //加载转换器,并支持对象与JSON间的数据转换

生成JSON字符串

@RequestMapping("/getJson")

public @ResponseBody User getJson(){

User user = new User("zhanghw", "123456");

return user;

}

  1. /**
  2.    * 测试AJAX JSON
  3.    */
  4.   @RequestMapping("/testJson2")
  5.   public @ResponseBody List<User> testJson2(){
  6.   List<User> list = new ArrayList<User>();
  7.   User user = new User();
  8.   user.setName("Hello");
  9.   user.setRealName("Hello World!");
  10.   list.add(user);
  11.   return list;
  12.   }

猜你喜欢

转载自blog.csdn.net/W_Y_L_/article/details/82793310
今日推荐