[四]SpringMvc学习-对servlet与json的支持与实现

1.对servletAPI的支持

  request、response、session作为参数自动注入

2.对Json的支持

  2.1springmvc配置文件中添加支持对象与json的转换

    <mvc:annotation-driven>

  2.2添加命名空间

    xmlns:mvc="http://www.springframework.org/schema/mvc"

    

    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc.xsd

  2.3添加jackson jar包

 

示例代码:

  @RequestMapping("/testAjax")

  public @ResponseBody User ajax(){

    User user = new User("zhangsan","123");

    return user;

  }

  @ResponseBody设置为返回Json格式

以上这种方法实际项目中不灵活,推荐使用以下做法(传统做法)

  

package com.java1234.util;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletResponse;


public class ResponseUtil {

  public static void write(HttpServletResponse response,Object o)throws Exception{
    response.setContentType("text/html;charset=utf-8");
    PrintWriter out=response.getWriter();
    out.println(o.toString());
    out.flush();
    out.close();
  }
}

posted on 2016-01-12 22:09  Simle  阅读(237)  评论(0编辑  收藏  举报