SpringMVC后端返回数据到前端代码示例

 更新时间:2020年04月23日 16:37:13   作者:筱菜鸟  
这篇文章主要介绍了SpringMVC后端返回数据到前端代码示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

1.返回ModelAndView对象(.jsp)

controller代码:

package controller;

import java.util.List;

import javax.annotation.Resource;

import model.Comment;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import service.CommentService;

@Controller
//@RequestMapping("comment")
public class CommentController {
  @Resource private CommentService commentService;
  @RequestMapping(value="showComments")
  public ModelAndView test(){
    ModelAndView mav = new ModelAndView();
    List<Comment> comments = commentService.selectAllComment();
    for(Comment com:comments){
      System.out.println(com.getC_text());
    }
    mav.addObject("msg",comments);
    mav.setViewName("textIndex.jsp");
    return mav;
  }
}

jsp页面代码

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

  <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
 <head>
  <base href="<%=basePath%>" rel="external nofollow" >
  
  <title>My JSP 'index.jsp' starting page</title>
  <meta http-equiv="pragma" content="no-cache">
  <meta http-equiv="cache-control" content="no-cache">
  <meta http-equiv="expires" content="0">  
  <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
  <meta http-equiv="description" content="This is my page">
  <!--
  <link rel="stylesheet" type="text/css" href="styles.css" rel="external nofollow" >
  -->
 </head>
 
 <body>
 <c:forEach items="${msg}" var="com">
  ${com.getUid()}:${com.getC_text()}:${com.getC_date()}<br>
  </c:forEach>
 </body>
</html>

2.返回JSON数据到html页面

利用ajax接收数据

ajax({
    method:'post',
    url:'http://localhost:8080/graduate/showComments.do',
    data:'null',
    success:function(response){
      console.log(response);
    }
})

controller

@Controller
//@RequestMapping("comment")
public class CommentController {
  @Resource private CommentService commentService;
  
  @RequestMapping(value="showComments")
  @ResponseBody
  public List<Comment> test(){
    List<Comment> comments = commentService.selectAllComment();
    for(Comment com:comments){
      System.out.println(com.getC_text());
    }
    return comments;
  }
}

3.顺便记录一下原生ajax,方便以后使用

function ajax(opt) {
    opt = opt || {};
    opt.method = opt.method.toUpperCase() || 'POST';
    opt.url = opt.url || '';
    opt.async = opt.async || true;
    opt.data = opt.data || null;
    opt.success = opt.success || function () {};
    var xmlHttp = null;
    if (XMLHttpRequest) {
      xmlHttp = new XMLHttpRequest();
    }
    else {
      xmlHttp = new ActiveXObject('Microsoft.XMLHTTP');
    }var params = [];
    for (var key in opt.data){
      params.push(key + '=' + opt.data[key]);
    }
    var postData = params.join('&');
    if (opt.method.toUpperCase() === 'POST') {
      xmlHttp.open(opt.method, opt.url, opt.async);
      xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;charset=utf-8');
      xmlHttp.send(postData);
    }
    else if (opt.method.toUpperCase() === 'GET') {
      xmlHttp.open(opt.method, opt.url + '?' + postData, opt.async);
      xmlHttp.send(null);
    } 
    xmlHttp.onreadystatechange = function () {
      if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
        opt.success(JSON.parse(xmlHttp.responseText));
      }
    };
  }

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

相关文章

  • Java编写中容易搞错的一些东西

    Java编写中容易搞错的一些东西

    Java编写中容易搞错的一些东西...
    2006-12-12
  • Java使用Knife4j优化Swagger接口文档的操作步骤

    Java使用Knife4j优化Swagger接口文档的操作步骤

    在现代微服务开发中,接口文档的质量直接影响了前后端协作效率,Swagger 作为一个主流的接口文档工具,虽然功能强大,但其默认界面和部分功能在实际使用中略显不足,而 Knife4j 的出现为我们提供了一种增强的选择,本篇文章将详细介绍如何在项目中集成和使用 Knife4j
    2024-12-12
  • 解决SpringBoot2.1.0+RocketMQ版本冲突问题

    解决SpringBoot2.1.0+RocketMQ版本冲突问题

    这篇文章主要介绍了解决SpringBoot2.1.0+RocketMQ版本冲突问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2024-06-06
  • Spring Cloud Gateway + Nacos 实现动态路由

    Spring Cloud Gateway + Nacos 实现动态路由

    这篇文章主要介绍了Spring Cloud Gateway + Nacos 实现动态路由的方法,帮助大家实现路由信息的自动更新,感兴趣的朋友可以了解下
    2020-10-10
  • SpringCloud Stream 整合RabbitMQ的基本步骤

    SpringCloud Stream 整合RabbitMQ的基本步骤

    这篇文章主要介绍了SpringCloud Stream 整合RabbitMQ的基本步骤,从项目介绍到生产者结合示例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2022-03-03
  • SpringCache的基本使用方法

    SpringCache的基本使用方法

    Spring Cache利用了AOP,实现了基于注解的缓存功能,并且进行了合理的抽象,业务代码不用关心底层是使用了什么缓存框架,只需要简单地加一个注解,就能实现缓存功能了,本文介绍SpringCache的基本使用方法,感兴趣的朋友一起看看吧
    2024-01-01
  • 在Eclipse中部署Spring Boot/Spring Cloud应用到阿里云

    在Eclipse中部署Spring Boot/Spring Cloud应用到阿里云

    这篇文章主要介绍了在Eclipse中部署Spring Boot/Spring Cloud应用到阿里云,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-12-12
  • java代码实现MD5加密及验证过程详解

    java代码实现MD5加密及验证过程详解

    这篇文章主要介绍了java代码实现MD5加密及验证过程详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2019-10-10
  • java如何实时动态获取properties文件的内容

    java如何实时动态获取properties文件的内容

    这篇文章主要介绍了java如何实时动态获取properties文件的内容,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-09-09
  • 详解MySQL的简易封装以及使用

    详解MySQL的简易封装以及使用

    本文主要介绍了MySQL的简易封装以及使用。具有一定的参考价值,下面跟着小编一起来看下吧
    2017-01-01

最新评论