Springboot-json做前后端分离

步骤 1 : 可运行项目

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

首先下载一个简单的可运行项目作为演示:网盘链接https://newryan.lanzous.com/ic3zeuj
下载后解压,比如解压到 E:\project\springboot 目录下

步骤 2 : Category

  1. 增加个 toString() 方便,便于显示
  2. 增加个注解:@JsonIgnoreProperties({ "handler","hibernateLazyInitializer" }) ,否则会出错
package com.ryan.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 + "]";
	}
}

步骤 3 : CategoryController

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

package com.ryan.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.ryan.springboot.dao.CategoryDAO;
import com.ryan.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 = "6") 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);
    }
}

步骤 4 : submit.html

在 webapp 下新增 submit.html,用于提交数据

<!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="1" /><br/>
       名称:<input type="text" id="name" value="梦却了无影踪"/><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>

访问测试地址:

http://localhost:8080/submit.html

测试效果:

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

步骤 5 : getOne.html

在 webapp 下新增 getOne.html,用于获取单个数据

<!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/8";
        $.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>

访问测试地址:

http://localhost:8080/getOne.html

注意:要确保 id=8 的分类对象存在
测试效果:

控制台:

步骤 6 : getMany.html

在 webapp 下新增 getMany.html,用于获取多个数据

<!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>

访问测试地址:

http://localhost:8080/getMany.html

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

更多关于 Springboot-json 详细内容,点击学习: https://how2j.cn/k/springboot/springboot-json/1654.html?p=139689

猜你喜欢

转载自www.cnblogs.com/newRyan/p/12809332.html