使用Json进行前后台传值

一、传值方式

          Json通过字符串形式进行前后台传值

二、Jsp_Servlet_前后台传值

  • 从前台向后台传值:使用x-www-form-urlencoded:request.getParameter()方法获取json字段

                                     使用application/json编码格式,json字符串以流的形式传输。使用BufferedReader读取流数据并存入字符串中,最后使用JSONObject.toBean()方法将json字符串填充到Pojo类对象中。

      

 BufferedReader br = request.getReader();
        String str, wholeStr = "";
        while((str = br.readLine()) != null){
            wholeStr += str;
        }
        System.out.println(wholeStr);
        User user= (User) JSONObject.toBean(JSONObject.fromObject(wholeStr),User.class);
        System.out.println(user.getUsername());
 
  • 从后台向前台传值:通过response对象获得PrintWriter对象直接向客户端输出json字符串  

           示例:Prinwriter out=response.getPrintWriter();

                     out.print(JSONObject.toString());

三、Springmvc_前后台传值

  • 从前台向后台传值:使用Springmvc默认转换机制,在controller方法头通过@requestParam、@requestBody或无注解方式填充

           @requestParam:常处理content-Type为x-www-form-urlencoded类型的编码格式,x-www-form-urlencode编码格式本质将                                            请求参数转换成键值对形式,等价于request.getParameter()方法,可进行数                                                                                     据类型转化(如字符串类型填充到pojo类对象中),常用来绑定单个参数

           @requestBody:常用来处理content-Type不是x-www-form-urlencoded类型的编码格式,如:application/json,只能接受json字符串,所以前台Ajax需要进行Json.stringfy()序列化转化或加单引号变为json字符串,同@requestParam,可进行数据类型填充转化。

           无注解:常用来pojo对象的填充

  • 从后台向前台传值:  1.使用Springmvc数据转换机制,返回List、Map等集合类,springmvc自动将其转成json字符串

                                        2.直接返回json字符串,创建JSONObject对象,返回JSONObject.toString();

          

猜你喜欢

转载自blog.csdn.net/weixin_38753309/article/details/84453841