SpringBoot study notes (five, Restful and json)

A, Restful

What Restful Shi?
REST Representational State Transfer abbreviation that is, can be translated as "presentation layer state transformation." REST some of the biggest features are: resources, unified interface, URI, and stateless. Restful Resource Locator and is a style resource operations. Not standard protocol is not just a style. Based on this style of software can be more concise, more structured and easier to implement caching mechanisms.
RESTful architecture predetermined style, metadata operations, i.e. CRUD (create, read, update and delete, i.e. deletions change check data) operation, respectively, corresponding to the HTTP method: GET to obtain resources, POST for new resources (which may used to update the resource), PUT for updating resources, dELETE to delete the resource, so that a unified interface to data manipulation, only through the HTTP method, you can complete investigation of all additions and deletions to change the working of the data.
Namely:
GET (the SELECT): Remove the resource from the server (one or more).
POST (CREATE): a new resource on the server.
PUT (UPDATE): updated resources on the server (client provides full resource data).
PATCH (UPDATE): In the server updates the resource (client provides the resources you need to modify data).
DELETE (DELETE): Delete the resource from the server.
And traditional to do some comparison:
Here Insert Picture Descriptionto transform the project into a Restful style

1、listCategory.jsp

1, an increase in the beginning of the introduction of jquery.min.js (must have jquery.min.js, and placed in this directory js)

<script type="text/javascript" src="js/jquery.min.js"></script>

2, increased
action to modify "the Categories"
3, delete
url modify the categories / id;
click hyperlinks, will use the submission form and submit _method value delete, in order to achieve a similar effect and increase

<script type="text/javascript">
        /*将post方法改为delete*/
       $(function(){
    	   $(".delete").click(function(){
    		   var href=$(this).attr("href");
               $("#formdelete").attr("action",href).submit();
               return false;
    	   })
       })
</script>
<a class="delete" href="categories/${c.id}">删除</a>

4, obtaining
url to modify / the Categories / ID
listCategory.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
 <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>   
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript">
        /*将post方法改为delete*/
       $(function(){
    	   $(".delete").click(function(){
    		   var href=$(this).attr("href");
               $("#formdelete").attr("action",href).submit();
               return false;
    	   })
       })
</script>
<title>查看分类</title>
</head>
<body>
	<div style="width: 500px; margin: 20px auto; text-align: center">
		<table align='center' border='1' cellspacing='0'>
			<tr>
				<td>id</td>
				<td>name</td>
				<td>编辑</td>
				<td>删除</td>
			</tr>
			<c:forEach items="${page.content}" var="c" varStatus="st">
				<tr>
					<td>${c.id}</td>
					<td>${c.name}</td>
					<td><a href="categories/${c.id}">编辑</a></td>
					<td><a class="delete" href="categories/${c.id}">删除</a></td>
				</tr>
			</c:forEach>

		</table>
		<br>
		<div>
			<a href="?start=0">[首 页]</a> <a href="?start=${page.number-1}">[上一页]</a>
			<a href="?start=${page.number+1}">[下一页]</a> <a
				href="?start=${page.totalPages-1}">[末 页]</a>
		</div>
		<br>
		<form action="categories" method="post">

			name: <input name="name"> <br>
			<button type="submit">提交</button>

		</form>
		
		 <form id="formdelete" action="" method="POST" >
           <input type="hidden" name="_method" value="DELETE">
         </form>
</body>
</html>

2、editCategory.jsp

In order to modify the action categories / id
Note: form filed under increase, although this form of method is post, but springmvc _method see the value of this is that after put, will change it to put.

<input type="hidden" name="_method" value="PUT">
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>修改</title>
</head>
<body>
	<div style="margin: 0px auto; width: 500px">

		<form action="../categories/${c.id}" method="post">
             <input type="hidden" name="_method" value="PUT">
			name: <input name="name" value="${c.name}"> <br> <input
				name="id" type="hidden" value="${c.id}">
			<button type="submit">提交</button>

		</form>
	</div>
</body>
</html>

3、CategoryController

To modify the CRUD are RequestMapping / categories, called the annotation previously used @RequestMapper, now are called GetMapper, PutMapper, PostMapper DeleteMapper and Method for acceptance of the corresponding

package edu.hpu.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.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import edu.hpu.springboot.dao.CategoryDao;
import edu.hpu.springboot.pojo.Category;

@Controller
public class CategoryController {
   @Autowired
   CategoryDao categoryDao;
   
   @PostMapping("/categories")
   public String addCategory(Category c) throws Exception{
	   categoryDao.save(c);
	   return "redirect:/categories";
   }
   
   @DeleteMapping("/categories/{id}")
   public String deleteCategory(Category c) throws Exception{
	   categoryDao.delete(c);
	   return "redirect:/categories";
   }
   
   @GetMapping("/categories/{id}")
   public String getCategory(@PathVariable("id") int id,Model m) throws Exception {
       Category c= categoryDao.getOne(id);
       m.addAttribute("c", c);
       return "editCategory";
   }
   
   @PutMapping("/categories/{id}")
   public String updateCategory(Category c) throws Exception{
	   categoryDao.save(c);
	   return "redirect:/categories";
   }
   @GetMapping("/categories")
    public String listCategory(Model m,@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);
	   System.out.println(page.getNumber());
       System.out.println(page.getNumberOfElements());
       System.out.println(page.getSize());
       System.out.println(page.getTotalElements());
       System.out.println(page.getTotalPages());
       m.addAttribute("page", page);
	   return "listCategory";
   }
}

Run it, the result was about the same as before.

Two, json

1、Category

Increasing a comment: @JsonIgnoreProperties ({ "handler", "hibernateLazyInitializer"}), because the internal audit mechanism jsonplugin with the java, hibernate will join a managed pojo hibernateLazyInitializer property, jsonplugin hibernateLazyInitializer will also operate out, which can not be read and a property of the reflection operation exception is generated, so ignore this property.

package edu.hpu.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;

//对应category_的实体类
@Entity                            //表示这是个实体类
@Table(name="category_")       //表示对应的表
@JsonIgnoreProperties({ "handler","hibernateLazyInitializer" }) 
public class Category {
   @Id                               //表示主键
   @GeneratedValue(strategy = GenerationType.IDENTITY)   //表明自增长方式
   @Column(name="id")                           //表示对应的字段
   private int id;
   
   @Column
   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 + "]";
	}
}

2、JsonCategoryController

@ RestController = @ RequestBody + @ Controller
If @RestController annotation Controller, the Controller of the method can not return jsp pages, or html, InternalResourceViewResolver configuration view resolver will not work directly back content.

package edu.hpu.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 edu.hpu.springboot.dao.CategoryDao;
import edu.hpu.springboot.pojo.Category;

@RestController
public class JsonCategoryController {
        @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) {
        	Category c= categoryDao.getOne(id);
            System.out.println(c);
            return c;
        }
        
        @PutMapping("/category")
        public void addCategory(@RequestBody Category category) {
        	System.out.println("springboot接受到浏览器以JSON格式提交的数据:"+category);
        	categoryDao.save(category);
        }
}

Three new html file in webapp
Here Insert Picture Description

3、submit.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>用AJAX以JSON方式提交数据</title>
<script type="text/javascript" src="js/jquery.min.js"></script>
</head>
<body>
    <div align="center">
      <form >
        id:<input type="text" id="id" value="123"><br>
        名称:<input type="text" id="name" name="category xxx"><br>
        <input type="button" value="提交" id="sender">
      </form>
    </div>
    <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: "category",
               data:jsonData,
               dataType:"json",
               contentType : "application/json;charset=UTF-8",
               success: function(result){
               }
            });
           alert("提交成功,请在springboot控制台查看服务端接收到的数据");
  
    });
    </script>
</body>
</html>

4、getOne.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>通过Ajax查找一个数据</title>
 <script type="text/javascript" src="js/jquery.min.js"></script>
</head>
<body>
    <form >
      <input type="button"  id="sender"  value="通过Ajax获得一个对象"> 
    </form>
    <div id="messageDiv"></div>
    <script >
    $('#sender').click(function(){
        var url="category/50";
        $.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>
</html>

5、getMany.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>通过Ajax获得多个分类对象</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>
</html>

Run about
Here Insert Picture DescriptionHere Insert Picture DescriptionHere Insert Picture DescriptionHere Insert Picture DescriptionHere Insert Picture DescriptionHere Insert Picture DescriptionHere Insert Picture Description

参考
【1】、https://www.cnblogs.com/chinajava/p/5871305.html
【2】、http://how2j.cn/k/springboot/springboot-restful/1653.html
【3】、https://blog.csdn.net/a57565587/article/details/43151239
【4】、http://how2j.cn/k/springboot/springboot-json/1654.html#nowhere
【5】、https://www.cnblogs.com/jingmoxukong/p/10200916.html

Guess you like

Origin blog.csdn.net/sinat_40770656/article/details/89504521