1. 程式人生 > >spring mvc返回json字串的方式

spring mvc返回json字串的方式

 spring mvc返回json字串的方式

方案一:使用@ResponseBody 註解返回響應體 直接將返回值序列化json

           優點:不需要自己再處理

步驟一:在spring-servlet.xml檔案中配置如下程式碼

複製程式碼
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
     xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd ">
 
     <!--使用Annotation方式 完成對映  -->
     <!--讓spring掃描包下所有的類,讓標註spring註解的類生效  -->
     <context:component-scan base-package="cn.hmy.controller"/>
     <mvc:annotation-driven/>  
     <!--檢視解析器  -->
     <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
     <property name="prefix" value="/WEB-INF/jsp/"></property>
     <property name="suffix" value=".jsp"></property>
     </bean>




</beans>
複製程式碼

步驟二:在處理器方法中打上@ResponseBody  標籤

複製程式碼
@RequestMapping(value="/hello5.do")
    @ResponseBody
    public String hello(HttpServletResponse response) throws IOException{
        UserInfo u1=new UserInfo();
        u1.setAge(15);
        u1.setUname("你好");
        
        UserInfo u2=new UserInfo();
        u2.setAge(152);
        u2.setUname("你好2");
        Map<String,UserInfo> map=new HashMap<String, UserInfo>();
        map.put("001", u1);
        map.put("002", u2);
        String jsonString = JSON.toJSONString(map);
        return jsonString;
    }
    
複製程式碼

步驟三:使用ajax進行獲取資料

複製程式碼
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'index.jsp' starting page</title>
    
    <script type="text/javascript" src="js/jquery-1.8.3.js"></script>
    <script type="text/javascript">
      $(function(){
         $("#btn").click(function(){
             $.ajax({
               url:"<%=path%>/Five.do",
               success:function(data){ 
               //解析物件
               //alert(data.uname+"\n"+data.age);
               //解析map
               //alert(data.info.age+"\n"+data.info.uname);
               //解析list
               $.each(data,function(i,dom){
               alert(dom.uname+"\n"+dom.age);
               });
               }
             });
         });
      });
    </script>
  </head>
  
  <body>
    <input type="button" value="ajax" id="btn"/>
    
  </body>
</html>
複製程式碼

方案二:處理器方法的返回值---Object

由於返回Object資料,一般都是將資料轉化為JSON物件後傳遞給瀏覽器頁面的,而這個由Object轉換為Json,是由Jackson工具完成的,所以要匯入jar包,將Object資料轉化為json資料,需要Http訊息轉換器 HttpMessageConverter完成。而轉換器的開啟,需要由<mvc:annotation-driven/> 來完成,當spring容器進行初始化過程中,在<mvc:annotation-driven/> 處建立註解驅動時,預設建立了七個HttpMessageConverter物件,也就是說,我們註冊<mvc:annotation-driven/>,就是為了讓容器幫我們建立HttpMessageConverter物件


詳細程式碼看

方案二、使用返回字串的處理器方法,去掉@ResponseBody註解

步驟一、同上

步驟二

複製程式碼
@RequestMapping(value="/hello5.do")
    public String hello(HttpServletResponse response) throws IOException{
        UserInfo u1=new UserInfo();
        u1.setAge(15);
        u1.setUname("你好");
        
        UserInfo u2=new UserInfo();
        u2.setAge(152);
        u2.setUname("你好2");
        Map<String,UserInfo> map=new HashMap<String, UserInfo>();
        map.put("001", u1);
        map.put("002", u2);
        String jsonString = JSON.toJSONString(map);
        return jsonString;
    }
複製程式碼

步驟三、在前臺取值的時候需要我麼做一遍處理

複製程式碼
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'index.jsp' starting page</title>
    
    <script type="text/javascript" src="js/jquery-1.8.3.js"></script>
    <script type="text/javascript">
      $(function(){
         $("#btn").click(function(){
             $.ajax({
               url:"<%=path%>/hello5.do",
               success:function(data){ //data指的是從server列印到瀏覽器的資料
                   //jsonString jsonObject
                   //{"001":{"age":122,"name":"順利就業"}}
                  var result= eval("("+data+")");
                   $.each(result,function(i,dom){
                      alert(dom.age+"\n"+dom.uname);
                      
                   });
                //  alert(result["001"]["age"]);
               }
             });
         });
      });
    </script>
  </head>
  
  <body>
    <input type="button" value="ajax" id="btn"/>
    
  </body>
</html>
複製程式碼

方案三:使用無返回值的處理器方法

步驟一:同上

步驟二:使用響應流回送資料

複製程式碼
@RequestMapping(value="/hello5.do")
    public void hello(HttpServletResponse response) throws IOException{
        UserInfo u1=new UserInfo();
        u1.setAge(15);
        u1.setUname("你好");
        
        UserInfo u2=new UserInfo();
        u2.setAge(152);
        u2.setUname("你好2");
        Map<String,UserInfo> map=new HashMap<String, UserInfo>();
        map.put("001", u1);
        map.put("002", u2);
        String jsonString = JSON.toJSONString(map);
        response.setCharacterEncoding("utf-8");
        response.getWriter().write(jsonString);
        response.getWriter().close();
        
    }
複製程式碼

步驟三:在前臺取值也需要做處理

複製程式碼
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'index.jsp' starting page</title>
    
    <script type="text/javascript" src="js/jquery-1.8.3.js"></script>
    <script type="text/javascript">
      $(function(){
         $("#btn").click(function(){
             $.ajax({
               url:"<%=path%>/hello5.do",
               success:function(data){ //data指的是從server列印到瀏覽器的資料
                   //jsonString jsonObject
                   //{"001":{"age":122,"name":"順利就業"}}
                  var result= eval("("+data+")");
                   $.each(result,function(i,dom){
                      alert(dom.age+"\n"+dom.uname);
                      
                   });
                //  alert(result["001"]["age"]);
               }
             });
         });
      });
    </script>
  </head>
  
  <body>
    <input type="button" value="ajax" id="btn"/>
    
  </body>
</html>