SpringMVC响应Ajax请求(@Responsebody注解返回页面)

项目需求描述:page1中的ajax请求Controller,Controller负责将service返回的数据填充到page2中,并将page2整个页面返回到page1中ajax的回调函数。
一句话表述:利用SpringMVC,以一个页面作为响应返回给ajax。

接下来,我们将介绍怎样将这样的需求实现到SpringMVC中,废话不多说,分步上代码。

1. Jquery ajax请求

对这部分不太熟悉的同学可以移步我的另一篇博客详解jQuery中ajax函数:$.get(),$.post(),$.ajax()。首先我们需要向Controller发送ajax请求。

function res(){

    $.post('mine',{

        qt:$('#mtext').attr('value')

    },function(data) {

        $('#queryresult').html(data);

    });

}

page1页面

<div id="queryresult"></div>

页面中具体实现的内容不进行赘述,各位客官根据自身项目情况进行脑补即可。

2. SpringMVC处理ajax请求

先介绍一个SpringMVC中的注释@Responsebody。使用@Responsebody标识的方法表示该方法的返回结果直接写入HTTP response body中,一般在异步获取数据时使用,在使用@RequestMapping后,返回值通常解析为跳转路径,加上@Responsebody后返回结果不会被解析为跳转路径,而是直接写入HTTP response body中。比如异步获取json数据,加上@Responsebody后,会直接返回json数据。

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;

import org.springframework.web.bind.annotation.ResponseBody;

import org.springframework.web.servlet.ModelAndView;
import javax.annotation.Resource;

import java.io.IOException;

import java.util.List;


@Controller

public class DMController {

    @Resource

    private IDMService dmService;

    @RequestMapping(value = "/mine",method = RequestMethod.POST)

    public @ResponseBody ModelAndView textMine(String qt,ModelAndView m) throws IOException {

        List<QueryResult> qrresults=dmService.getQueryResults(qt);//QueryResult是自定义的pojo

        m.addObject("queryresults",qrresults);

        m.setViewName("page2");

        return m;

    }

}

利用ModelAndView将Service中的结果值传到page2页面,并将ModelAndView对象返回到ajax。

page2页面

<c:forEach items="${queryresults}" var="queryresults">

    <div>

        <p>${queryresults.resultTitle}</p>

        <p>${queryresults.resultContent}</p>

    </div>

</c:forEach>

至此,SpringMVC以页面响应Ajax请求的整个过程也结束,整个过程还需要各位客官仔细理解,然后结合自己的实际需求进行改进。项目中运用到的场景如下图。
springmvc响应ajax请求

参考:
http://www.aichengxu.com/view/38943

posted @   星朝  阅读(7178)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示