zoukankan      html  css  js  c++  java
  • SpringMVC中响应json数据(异步传送)

    1、首先导入3个jar包:

    • jackson-annotations-2.1.5.jar
    • jackson-core-2.1.5.jar
    • jackson-databind-2.1.5.jar

    JSON所需jar包下载(百度云) 密码:bfav

    2、在controller中,@RequestMapping注解下添加@ResponseBody注解,自动将数据封装成json

    Department有两个属性iddepartmentName;

     1 @Controller
     2 public class JsonController {
     3     @RequestMapping(value="/helloJson")
     4 @ResponseBody
     5     public List<Department> helloJson() throws IOException{
     6         List<Department> departList=new ArrayList<Department>();
     7         departList.add(new Department(2, "财务部"));
     8         departList.add(new Department(3, "人事部"));
     9         departList.add(new Department(5, "技术部"));
    10         return departList;
    11     }
    12 }

    3、在jsp页面访问后台方法,并接受json数据

     1 <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
     2 <!-- 动态获取路径,详情查看web应用路径问题(相对路径,绝对路径,动态获取路径) -->
     3 <%
     4     String path = request.getContextPath();
     5     String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
     6 %>
     7 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
     8 <html>
     9 <head>
    10 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    11 <title>Insert title here</title>
    12 <script type="text/javascript" src="<%=basePath %>public/js/jquery-3.2.1.min.js"></script>
    13 <script type="text/javascript">
    14     $(function(){
    15         $("#testJson").click(function(){
    16             alert();
    17             var url="${pageContext.request.contextPath}/helloJson";
    18             function callback(data){
    19                 for(var i=0;i<data.length;i++){
    20                     alert(data[i].id+"-----"+data[i].departmentName);
    21                     //2-----财务部
    22                     //3-----人事部
    23                     //5-----技术部
    24                 }
    25             }
    26             $.post(url,{},callback);
    27         });
    28     });
    29 </script>
    30 </head>
    31 <body>
    32     <button id="testJson">json</button>
    33 </body>
    34 </html>
  • 相关阅读:
    一枚渣硕的2019校招记录
    PLT hook笔记
    从排序数组中删除重复项
    golang刷Leetcode系列 --- 实现strStr()
    Docker镜像浅谈
    golang刷Leetcode系列 --- 加1
    ubuntu包管理机制
    LeetCode 234——回文链表
    LeetCode 19——删除链表的倒数第N个节点(JAVA)
    LeetCode 160——相交链表(JAVA)
  • 原文地址:https://www.cnblogs.com/lixiang1993/p/7420215.html
Copyright © 2011-2022 走看看