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>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM