Springmvc返回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();
  }


原文地址:http://www.itmmd.com/201412/355.html 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值