SpringMVC常用注解實例詳解3:@ResponseBody

我的開發環境
框架:        springmvc+spring+freemarker
開發工具: springsource-tool-suite-2.9.0
JDK版本: 1.6.0_29
tomcat版本:apache-tomcat-7.0.26

前置文章-SpirngMVC配置入門 http://www.cnblogs.com/sunang/p/3419544.html

      Spring整合Freemarker http://www.cnblogs.com/sunang/p/3419676.html

@ResponseBody用于在controller方法中直接返回一個數據對象,常用于Ajax交互中,本文用Ajax交互的例子來演示下該註釋的用法。

step1.由於Ajax傳輸數據用到JSON,所以要先添加JSON依賴如下:

Maven代碼如下:

<!-- JSON -->
<dependency>
    <groupId>org.codehaus.jackson</groupId>
    <artifactId>jackson-core-asl</artifactId>
    <version>1.8.4</version>
</dependency>
<dependency>
    <groupId>org.codehaus.jackson</groupId>
    <artifactId>jackson-mapper-asl</artifactId>
    <version>1.8.4</version>
</dependency>

在spring配置文件中加入JSON所需配置,此處以spring-servlet.xml為例,代碼如下:

<!-- JSON所需配置 -->
<bean        class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
    <property name="messageConverters">
        <list>
            <ref bean="mappingJacksonHttpMessageConverter" />
        </list>
    </property>
</bean>
<bean id="mappingJacksonHttpMessageConverter"        class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
    <property name="supportedMediaTypes">
        <list>
        <value>application/json;charset=UTF-8</value>
        </list>
    </property>
</bean>

 step2.編寫頁面ajaxGetMsg.ftl,代碼如下:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<!-- 引入jquery文件-->
<script type="text/javascript" src="../js/jquery.js"></script>
<title>Insert title here</title>
</head>
<body>
<span id="content">
<!-- 點擊按鈕后調用getMsg()方法-->
<button type="button" onclick="javascript:getMsg();">@ResponseBody結合Ajax例子演示</button>
</span>
</body>
</html>
<script type="text/javascript">
function getMsg(){
    var content = "";
    //ajax訪問controller方法,利用@ResponseBody返回數據對象
    $.ajax({
        async:false,
        cache : false,
        type : 'POST',
        dataType : "json",
        url:"ajaxGetMsg.htm",
        success:function(data){
            $.each(data, function(i,obj){
                content=content+obj;
            });
            $("#content").html(content);
        },
        error:function(){
            alert("加载失败");
                return;
            }
    });
}
</script>

step3.編寫controller方法,代碼如下:

package www.asuan.com.controller;

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/learnMVC")
public class LearnMVCController {
    //前往初始頁面
    @RequestMapping("/indexPage")
    public String indexPage(){
        return "ajaxGetMsg.ftl";
    }
    //Ajax交互方法
    @RequestMapping("/ajaxGetMsg")
    @ResponseBody
    public List<String> ajaxGetMsg() {
        List<String> strList = new ArrayList<String>();
        strList.add("學");
        strList.add("習");
        strList.add("Spring");
        strList.add("M");
        strList.add("V");
        strList.add("C");
        return strList;
    }
}

indexPage()方法用於訪問初始頁面,ajaxGetMsg()方法上加了@ResponseBody註釋,所以該方法可以直接向頁面返回數據對象,該方法的返回數據類型為List<String>.

step4.運行調試

部署運行項目,瀏覽器訪問:http://localhost:8080/你的工程名/learnMVC/indexPage.htm

運行結果如下:

點擊按鈕,ajax加載數據得到如下結果:

complete!

系列文章鏈接:

SpringMVC常用注解實例詳解:@Controller,@RequestMapping,@RequestParam,@PathVariable   http://www.cnblogs.com/sunang/p/3421707.html 

SpringMVC常用注解實例詳解:@ModelAttribute                                                                    http://www.cnblogs.com/sunang/p/3423227.html 

原文地址:https://www.cnblogs.com/sunang/p/3429895.html