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.yxj.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>

 

 

 

 

 

希望對你們有所幫助,勤加練習喲微笑微笑微笑微笑

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章