385、Java中级40 -【Spring Boot - JSON】 2020.09.27

56 篇文章 1 订阅
17 篇文章 0 订阅

1、 本知识点效果

本知识点效果有三个,分别是以json方式:提交,获取单个和获取多个
提交

http://localhost:8080/submit.html

获取单个

http://localhost:8080/getOne.html

获取多个

http://localhost:8080/getMany.html

2、基于前面的知识点

基于Restful 风格的springboot进行修改。 毕竟Restful 风格的springboot直接转换为json,很方便的啦

3、Category

  1. 增加个toString() 方便,便于显示
  2. 增加个注解:@JsonIgnoreProperties({ “handler”,“hibernateLazyInitializer” }) ,否则会出错
package com.how2java.springboot.pojo;
 
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
 
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
 
@Entity
@Table(name = "category_")
@JsonIgnoreProperties({ "handler","hibernateLazyInitializer" }) 
public class Category {
 
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private int id;
     
    @Column(name = "name")
    private String name;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    @Override
    public String toString() {
        return "Category [id=" + id + ", name=" + name + "]";
    }
     
}

4、CategoryController

控制器里提供3个方法,分别用来处理json 提交,json获取单个对象,json获取多个对象

package com.how2java.springboot.web;
import java.util.List;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
 
import com.how2java.springboot.dao.CategoryDAO;
import com.how2java.springboot.pojo.Category;
  
@RestController
public class CategoryController {
    @Autowired CategoryDAO categoryDAO;
     
    @GetMapping("/category")
    public List<Category> listCategory(@RequestParam(value = "start", defaultValue = "0") int start,@RequestParam(value = "size", defaultValue = "5") int size) throws Exception {
        start = start<0?0:start;
        Sort sort = new Sort(Sort.Direction.DESC, "id");
        Pageable pageable = new PageRequest(start, size, sort);
        Page<Category> page =categoryDAO.findAll(pageable);
        return page.getContent();
    }
     
    @GetMapping("/category/{id}")
    public Category getCategory(@PathVariable("id") int id) throws Exception {
        Category c= categoryDAO.getOne(id);
        System.out.println(c);
        return c;
    }
    @PutMapping("/category")
    public void addCategory(@RequestBody Category category) throws Exception {
        System.out.println("springboot接受到浏览器以JSON格式提交的数据:"+category);
    }
}

5、submit.html

访问测试地址:

http://localhost:8080/submit.html

提交成功后,在springboot控制台查看使用json方式提交的数据
注: 不要在eclipse自带的浏览器里面点击,自带的浏览器有bug,有时候不能识别jquery, 会导致点击没有反应。 使用独立的浏览器,比如chrome,firefox点击测试

在这里插入图片描述

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>用AJAX以JSON方式提交数据</title>
<script type="text/javascript" src="js/jquery.min.js"></script>
</head>
<body>
    <form >
       id:<input type="text" id="id" value="123" /><br/>
       名称:<input type="text" id="name" value="category xxx"/><br/>
        <input type="button" value="提交" id="sender"> 
    </form>
    <div id="messageDiv"></div>
         
    <script>
    $('#sender').click(function(){
        var id=document.getElementById('id').value;
        var name=document.getElementById('name').value;
        var category={"name":name,"id":id};
        var jsonData = JSON.stringify(category);
        var page="category";
          
        $.ajax({
               type:"put",
               url: page,
               data:jsonData,
               dataType:"json",
               contentType : "application/json;charset=UTF-8",
               success: function(result){
               }
            });
           alert("提交成功,请在springboot控制台查看服务端接收到的数据");
  
    });
    </script>
</body>
     
</html>

6、getOne.html

访问测试地址:

http://localhost:8080/getOne.html

注意:要确保id=10的分类对象存在
在这里插入图片描述

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>用AJAX以JSON方式获取数据</title>
<script type="text/javascript" src="js/jquery.min.js"></script>
</head>
<body>
    <input type="button" value="通过AJAX获取一个Hero对象---" id="sender"> 
     
    <div id="messageDiv"></div>
         
    <script>
    $('#sender').click(function(){
        var url="category/10";
        $.get(
                url,
                function(data) {
                    console.log(data);
                     var json=data;
                     var name =json.name;
                     var id = json.id;
                     $("#messageDiv").html("分类id:"+ id + "<br>分类名称:" +name );
                        
         }); 
    });
    </script>
</body>
     
</body>
</html>

7、getMany.html

访问测试地址:

http://localhost:8080/getMany.html

点击按钮,获取多个json数据

在这里插入图片描述

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>用AJAX以JSON方式获取数据</title>
<script type="text/javascript" src="js/jquery.min.js"></script>
</head>
<body>
    <input type="button" value="通过AJAX获取多个分类对象" id="sender"> 
     
    <div id="messageDiv"></div>
         
    <script>
    $('#sender').click(function(){
        var url="category?start=0&size=100";
        $.get(
                url,
                function(data) {
                    var categorys = data;
                     for(i in categorys){
                         var old = $("#messageDiv").html();
                         var category = categorys[i];
                         $("#messageDiv").html(old + "<br>"+category.id+"   -----   "+category.name);
                     }
         }); 
    });
    </script>
</body>
     
</body>
</html>

8、参考链接

[01] How2j - Spring Boot - JSON

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值