160506、Spring mvc新手入门(11)-返回json 字符串的其他方式

Spring MVC返回 json字符串的方式有很多种方法,这里介绍最简单,也是最常使用的两种方式


一、使用  PrintWriter printWriter  直接输出字符串到返回结果中 
   不需要任何xml文件配置

1
2
3
4
5
6
7
8
9
//返回给前台一个字符串
 @RequestMapping(params = "method=getJson1")
 public void getJson(@RequestParam("userid") String userid,@RequestHeader("Accept-Encoding") String encoding,HttpServletRequest request,PrintWriter printWriter) {
  System.out.println("通过注解在参数中取值 "+userid);
  System.out.println("通过@RequestHeader获得的encoding "+encoding);
        printWriter.write("{key,1}"); 
        printWriter.flush(); 
        printWriter.close(); 
 }

请求地址:http://localhost:8080/springmvc/hello.do?method=getJson1&userid=111
    返回值: {key,1}

二、通过@ResponseBody  直接返回对象,Spring MVC会自动把对象转化成Json
    需要其他配置支持 
    1、开启  <mvc:annotation-driven />
    2、Jackson library 对应的jar必须加入到工程中
             3、方法的返回值必须添加 @ResponseBody

1
2
3
4
5
6
7
8
//把返回结果解析成json串返回到前台
 @RequestMapping(params = "method=json")
 public @ResponseBody User passValue(HttpServletRequest request) {
  User user = new User();
  user.setUser("aaaa");
  user.setPass("asfd");
  return user;
 }
 

 请求地址:http://localhost:8080/springmvc/hello.do?method=json
  返回值:{"user":"aaaa","pass":"asfd"}


注意:在使用@ResponseBody 返回json的时候,方法参数中一定不能他添加   PrintWriter printWriter

  java.lang.IllegalStateException: getWriter() has already been called for this response
例如:

//这个方法会报错 因为使用了PrintWriter printWriter  错误 java.lang.IllegalStateException: getWriter() has already been called for this response 

1
2
3
4
5
6
7
 @RequestMapping(params = "method=jsonTest")
 public @ResponseBody Map<String, Object> jsonTest(@RequestParam("userid") String userid,HttpServletRequest request,PrintWriter printWriter) {
  System.out.println("通过注解在参数中取值 "+userid);
  System.out.println("通过自己写的函数从reqeust取值 "+RequestUtil.getMap(request).get("userid"));
  HelloWorld hello = new HelloWorld(RequestUtil.getMap(request));
  return   hello.hello();
 }


    提醒:注意两种方法不能混用,不然会报错如下:

原文地址:https://www.cnblogs.com/zrbfree/p/5473569.html