月光代碼園

記錄、分享、交流

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

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 

 

posted on   bangdikka  阅读(4583)  评论(0编辑  收藏  举报

编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
点击右上角即可分享
微信分享提示