8.SpringMVC-处理JSON数据

本文最后更新于2024.04.28-07:32,某些文章具有时效性,若有错误或已失效,请在下方留言或联系涛哥

什么是JSON?

JSON(JavaScript Object Notation, JS对象简谱)是一种轻量级的数据交换格式。它基于 ECMAScript(European Computer Manufacturers Association, 欧洲计算机协会制定的js规范)的一个子集,采用完全独立于编程语言的文本格式来存储和表示数据。简洁和清晰的层次结构使得 JSON 成为理想的数据交换语言。 易于人阅读和编写,同时也易于机器解析和生成,并有效地提升网络传输效率

JSON

1,基本格式

{"key":"value","key":"value"} 一个对象

[{“key”:"value"},{"key":"value"}] 一个数组 value的类型可以是 数组 字符串 数字 或者对象

2.准备工作

a. 导入 相关的jar包

jackson-databind

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.10.3</version>
</dependency>

b.mvc.xml中配置

 <mvc:annotation-driven/>

c.在页面中添加 jquery

3.发送数据

jquery中常用的 异步请求的方法:

方法1:

$.post(url,data,callback); ---->这种方式发送post请求,后台controller不可使用 @RequestBody注解

方法2:

    $.ajax({
            url:"地址",
            method:"请求方式",
            data:发送的数据(可以是json对象,也可以是json字符串)
            contentType:(如果后台试用了requestBody,这里必须设置成application/json;charset=utf-8,同时data的类型应该是字符串),
            dataType:预估的返回的数据类型,
            success:function(data,state){
                请求成功的回调函数 data表示返回的数据,state Http状态码
            }
    })

ps:JSON.stringify 可以把对象或者数组 转换成json字符串

4.响应给前端

a.控制器的方法上 加上注解 @ResponseBody

b.直接修改方法返回值类型,在方法中返回对应的结果即可。

c.前端的回调函数中 对数据进行处理。

5.完整流程

1,前端发起异步请求

<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2021/4/20
  Time: 11:43
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>$Title$</title>
    <style>
      #msgbox,#userForm,navigate{
        width: 1020px;
        margin: 0 auto;
        border-collapse: collapse;
        overflow: hidden;
      }
      #msgbox td{
        text-align-all: center;
      }
        li{
        list-style: none;
        float: left;
        margin-left: 10px;
​
      }
      .pageSize{
        margin-left: 123px;
      }
      .navigate{
        margin-left: -40px;
      }
      .pg{
        position: relative;
        margin-left: 280px;
      }
    </style>
    <script src="${pageContext.request.contextPath}/js/jquery.min.js"></script>
  </head>
  <body>
  <form id="userForm">
    <input type="text" name="username" id="username" placeholder=用户名>
    <select name="sex" id="sex">
      <option value="">不限</option>
      <option value="男">男</option>
      <option value="女">女</option>
    </select>
      <input type="text" name="phone" id="phone" placeholder="联系方式">
      <select name="phonetype" id="phonetype">
        <option value="">不限</option>
        <option value="安卓">安卓</option>
        <option value="苹果">苹果</option>
      </select>
      <input type="text" id="age" name="age">
     年龄: <input type="date" name="startDate" id="startDate">
      ~<input type="date" name="endDate" id="endDate">
    </form>
​
    <table id="msgbox" border="1">
      <thead>
          <th>用户名</th>
          <th>性别</th>
          <th>联系方式</th>
          <th>手机系统</th>
          <th>年龄</th>
          <th>生日</th>
          <th>操作</th>
      </thead>
      <tbody id="userBox">
      </tbody>
   </table>
  <ul class="pg">
    <li class="pageSize">每页显示<select name="pageSize" id="pageSize">
      <option value="1">1</option>
      <option value="2">2</option>
      <option value="3">3</option>
    </select>条</li>
    <li >
      <ul  class="navigate">
​
      </ul>
    </li>
​
  </ul>
​
  <br>
  </body>
  <script>
    $(function(){
      getUsers(1);
    });
    $("#userForm").change(function () {
      getUsers(1);
    });
    $("#pageSize").change(function () {
      getUsers(1);
    });
    function getUsers(pageNum){
      $("#userBox").empty();
      $(".navigate").empty();
      var url="${pageContext.request.contextPath}/getUser";
      var data={
        "username":$("#username").val(),
        "sex":$("#sex").val(),
        "phone":$("#phone").val(),
        "phonetype":$("#phonetype").val(),
        "age":$("#age").val(),
        "birthday":$("#birthday").val(),
        "startDate":$("#startDate").val(),
        "endDate":$("#endDate").val(),
        "pageNum":pageNum,
        "pageSize":$("#pageSize").val(),
      }
        $.ajax({
          url:url,
          method:"post",
          data:data,
          success:function(data) {
            makePage(data);
              console.log(data);
              var users=data.list;
              var pageNums=data.navigatepageNums;
              for (var i=0;i<users.length;i++){
                var $tr=$("<tr>");
                var $username=$("<td>");
                var $sex=$("<td>");
                var $phone=$("<td>");
                var $phonetype=$("<td>");
                var $age=$("<td>");
                var $birthday=$("<td>");
                var $del=$("<td>");
                console.log(users[i].userid);
                $tr.append($username.html(users[i].username)).
                    append($sex.html(users[i].sex)).
                    append($phone.html(users[i].phone)).
                    append($phonetype.html(users[i].phonetype)).
                    append($age.html(users[i].age)).
                    append($birthday.html(users[i].birthday)).append($del.html('<button onclick="del('+users[i].userid+')">删除</button>'));
                $("#userBox").append($tr);
              }
          }
        });
    }
​
    function del(userId) {
      alert(userId)
      $.ajax({
        url:"${pageContext.request.contextPath}/delUser/"+userId,
        method:"post",
        success:function(data) {
          console.log(data);
          if (data==1){
              alert("删除成功!");
              getUsers();
          }
        }
      });
    }
​
​
    function makePage(data){
      var pageNums=data.navigatepageNums;
      if(data.pages==1){
        return;
      }
​
      if(data.isFirstPage!=true){
        var pageNum=1;
        $li=$("<li></li>");
        $btn=$("<button></button>");
        $li.append($btn);
        $btn.attr("onclick","getUsers("+pageNum+")").text("首页");
        $(".navigate").append($li);
      }
      if(data.hasPreviousPage==true){
        var pageNum=data.pageNum-1;
        $li=$("<li></li>");
        $btn=$("<button></button>");
        $li.append($btn);
        $btn.attr("onclick","getUsers("+pageNum+")").text("上一页");
        $(".navigate").append($li);
      }
      for(var i=0;i<pageNums.length;i++){
        var pageNum=pageNums[i];
        $li=$("<li></li>");
        $btn=$("<button></button>");
        $li.append($btn);
        $btn.attr("onclick","getUsers("+pageNum+")").text(pageNum);
        $(".navigate").append($li);
      }
      if(data.hasNextPage==true){
        var pageNum=data.pageNum+1;
        $li=$("<li></li>");
        $btn=$("<button></button>");
        $li.append($btn);
        $btn.attr("onclick","getUsers("+pageNum+")").text("下一页");
        $(".navigate").append($li);
      }
​
      if(data.isLastPage!=true){
        var pageNum=data.pages;
        $li=$("<li></li>");
        $btn=$("<button></button>");
        $li.append($btn);
        $btn.attr("onclick","getUsers("+pageNum+")").text("尾页");
        $(".navigate").append($li);
      }
    }
  </script>
</html>

2,请求到后台对应的controller

package com.edu.controller;
​
import com.edu.bean.User;
import com.edu.service.UserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
​
import java.util.Date;
​
@Controller
public class UserController {
​
    @Autowired
    private UserService userService;
​
    @RequestMapping("/getUser")
    @ResponseBody
    public Object selectUser(User user,Date startDate, Date endDate,@RequestParam(value = "pageNum",required = false) int pageNum,@RequestParam(value = "pageSize",defaultValue = "1",required = false)int pageSize){
        System.out.println(user);
        System.out.println(startDate);
        System.out.println(endDate);
        PageHelper.startPage(pageNum, pageSize);
        return userService.queryUsers(user,startDate,endDate).toPageInfo();
    }
​
    @RequestMapping("/delUser/{userId}")
    @ResponseBody
    public int delUser(@PathVariable("userId") int userId){
        System.out.println("zsdfsfsdf");
        System.out.println(userId);
        return userService.delUser(userId);
    }
}

3,业务逻辑层

package com.edu.service;
​
import com.edu.bean.User;
import com.github.pagehelper.Page;
​
import java.util.Date;
​
public interface UserService {
    Page<User> queryUsers(User user, Date startDate, Date endDate);
    int delUser(int userId);
}
​
package com.edu.service.impl;
​
import com.edu.bean.User;
import com.edu.mapper.UserMapper;
import com.edu.service.UserService;
import com.github.pagehelper.Page;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
​
import java.util.Date;
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
​
    public Page<User> queryUsers(User user, Date startDate, Date endDate) {
        return userMapper.selectUser(user,startDate,endDate);
    }
​
    public int delUser(int userId) {
        return userMapper.deleteByPrimaryKey(userId);
    }
}

4,数据酷查询返回结果

package com.edu.mapper;
​
import com.edu.bean.User;
import com.edu.bean.UserExample;
​
import java.util.Date;
import java.util.List;
​
import com.github.pagehelper.Page;
import org.apache.ibatis.annotations.Param;
​
public interface UserMapper {
    int deleteByPrimaryKey(Integer userid);
    Page<User> selectUser(@Param("user") User user, @Param("start") Date startDate, @Param("end") Date endDate);
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.edu.mapper.UserMapper">
  <resultMap id="BaseResultMap" type="com.edu.bean.User">
    <id column="userid" jdbcType="INTEGER" property="userid" />
    <result column="username" jdbcType="VARCHAR" property="username" />
    <result column="sex" jdbcType="VARCHAR" property="sex" />
    <result column="phone" jdbcType="VARCHAR" property="phone" />
    <result column="phonetype" jdbcType="VARCHAR" property="phonetype" />
    <result column="age" jdbcType="INTEGER" property="age" />
    <result column="birthday" jdbcType="DATE" property="birthday" />
  </resultMap>
  
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
    delete from user
    where userid = #{userid,jdbcType=INTEGER}
  </delete>
 
  <select id="selectUser" parameterType="com.edu.bean.User" resultMap="BaseResultMap">
    select * from user
    <where>
      <if test="user.username != null and user.username !=''">
        username = #{user.username,jdbcType=VARCHAR}
      </if>
      <if test="user.sex != null and user.sex !=''">
        and sex = #{user.sex,jdbcType=VARCHAR}
      </if>
      <if test="user.phone != null and user.phone !=''">
        and phone = #{user.phone,jdbcType=VARCHAR}
      </if>
      <if test="user.phonetype != null and user.phonetype !=''">
        and phonetype = #{user.phonetype,jdbcType=VARCHAR}
      </if>
      <if test="user.age != null and user.age !=''">
        and age = #{user.age,jdbcType=INTEGER}
      </if>
      <if test="start != null">
        and birthday >= #{start}
      </if>
      <if test="end != null">
        and birthday &lt;= #{end}
      </if>
    </where>
  </select>
</mapper>

 

阅读剩余
THE END