ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

Http请求类型(Method)实现查询增删改

2022-04-25 23:04:34  阅读:217  来源: 互联网

标签:function Http name id Method products 增删 Products public


第一步:定义一个实体类

package com.example.products.entity;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

//实现Serializable接口
public class Products implements Serializable {

    private int id;
    private String name;
    private double price;


    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;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    public Products(int id, String name, double price) {
        this.id = id;
        this.name = name;
        this.price = price;
    }

    public Products() {
    }
}
View Code

第二步:定义一个服务类接口

package com.example.products.service;


import com.example.products.entity.Products;

import java.util.List;

public interface ProductsService {
    //查询商品
    public Products findProductById(int id);
    //查询所有商品
    public List<Products> findAllPorducts();

    //添加商品
    public int addPorducts(Products products);

    //修改商品
    public int editProducts(Products products);

    //删除商品
    public int delete(int id);
}
View Code

第三步:定义一个实现接口的方法

package com.example.products.service.impl;
import com.example.products.entity.Products;
import com.example.products.service.ProductsService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserServiceImpl implements ProductsService {

    //定义集合
    static List<Products> list=new ArrayList<>();

    static {
        list.add(new Products(1,"果冻",2));
        list.add(new Products(2,"旺旺碎冰冰",2.5));
        list.add(new Products(3,"甜筒",5));
    }

    //查询id的数据
    @Override
    public Products findProductById(int id) {
        Products products=null;
       for(Products u:list){
           if(u.getId()==id){
               products=u;
               break;
           }
       }
       return  products;
    }
    //查询全部数据
    @Override
    public List<Products> findAllPorducts() {
        return list;
    }

    //添加数据
    @Override
    public int addPorducts(Products products) {
     list.add(products);
       return 1;
    }

    //修改数据
    @Override
    public int editProducts(Products products) {
        int i=0;
        Products u=findProductById(products.getId());
        if(u!=null) {
            u.setName(products.getName());
            u.setPrice(products.getPrice());
            i++;
        }
        return i;
    }

    //删除数据
    @Override
    public int delete(int id) {
        int i=0;
        Products p=findProductById(id);
        if(p!=null){
            list.remove(p);
            i++;
        }
        return i;
    }
}
View Code

第四步:定义一个控制类,实现请求的接口

package com.example.products.contorller;

import com.example.products.entity.Products;
import com.example.products.service.ProductsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController()
@RequestMapping("/api")
public class UserContorller {
    @Autowired
    ProductsService productsService;

    //查询id的数据
    @GetMapping(path = "/products/{id}")
    public Products getProductById(@PathVariable int id){
        return productsService.findProductById(id);
    }

    //查询全部数据
    @GetMapping("/products")
    public List<Products> getAll(){
        return productsService.findAllPorducts();
    }

    //添加数据
    @PostMapping(path = "/products")
    public int addPorducts(@RequestBody Products product){
        return productsService.addPorducts(product);
    }

    //修改数据
    @PutMapping(path = "/products")
    public int editUser(@RequestBody Products products){
        return productsService.editProducts(products);
    }

    //删除数据s
    @DeleteMapping(path = "/products/{id}")
    public int deletUser(@PathVariable int id){
        return productsService.delete(id);
    }

}
View Code

第五步:页面代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="./js/jquery-3.5.1.min.js"></script>
    <script src="./js/axios.min.js"></script>
    <script src="./js/vue.min.js"></script>
    <style>
        tr{
            text-align: center;
        }
        input{
            outline-style: none;
        }
        .div1{
            position: relative;
        }
        .prompt{
            width: 150px;
            height: 100px;
            text-align: center;
            line-height: 100px;
            color: aliceblue;
            font-size: 25px;
            background-color: #5CB85C;
            position: absolute;
            top: 50%;
            left: 50%;
            transform:translate(-75px,-50px);
            display: none;
        }
    </style>
</head>
<body>
<div id="app">
    <h2>商品管理</h2>

    <label for="coid">商品查询:</label><input type="text" id="coid" placeholder="请输入商品编号"><button style="background-color: #5CB85C;color: azure;border: none" @click="getProductById()">搜索</button><br><br>
    <table id="tab" width="100%" border="1">
        <tr style="background-color: #1FC0EF">
            <th>编号</th>
            <th>商品名称</th>
            <th>价格</th>
            <th>操作</th>
        </tr>
        <tr v-for="(product,index) in products">
            <td>{{product.id}}</td>
            <td>{{product.name}}</td>
            <td>{{product.price}}</td>
            <td style="text-align: center">
                <button  onclick="up(this)" style="background-color:  #1FC0EF;border: none;color: black">修改</button>
                <button @click="del(product.id)" style="background-color: #FF0000;border: none;color: azure"  >删除</button>
            </td>
        </tr>
    </table>

    <br>
    <br>

    <div class="div1">
        <div class="prompt">
            添加成功!
        </div>
    </div>
    <form action="#">
        <fieldset style="width: 300px">
        <legend>商品管理</legend>
        <label for="pid" >编号:</label> <input id="pid"  type="text"><br><br>
        <label for="name">名称:</label> <input id="name" type="text"><br><br>
        <label for="price">价格:</label> <input id="price" type="text"><br><br>
        <button style="background-color: #5CB85C;color: azure;border: none" @click="addProduct()">添加</button>  <button style="background-color: #F0AD4E;color: azure;border: none" @click="update">修改</button>
        </fieldset>
    </form>

</div>
<script type="text/javascript">
    var app = new Vue({
        el: "#app",
        data: {
            products: []
        },
        //初始化数据
        created() {
            axios.get('/api/products', {}).then(function (response) {
                app.products = response.data;
            })
                .catch(function (error) {
                    console.log(error);
                })
                .then(function () {
                });
        },
        methods:{
            //查询为id的数据
            getProductById:function (){
                let coid=document.getElementById("coid").value;
                axios.get("/api/products/"+coid+"", {}).then(function (response) {
                    let arr=[response.data]
                    app.products=arr;

                })
                    .catch(function (error) {
                        console.log(error);
                    })
                    .then(function () {
                    });
            },
            //添加数据
            addProduct:function () {
                let pid = document.getElementById("pid").value;
                let name = document.getElementById("name").value;
                let price = document.getElementById("price").value;
                if (pid != "" && name != "" && price != "") {

                    let product = {
                        "id": pid,
                        "name": name,
                        "price": price
                    }
                    axios.post("/api/products", product)
                        .then(function (response) {
                            let i = response.data;
                            if (i>=1){

                                document.getElementsByClassName("prompt")[0].innerHTML="添加成功!"
                                document.getElementsByClassName("prompt")[0].style.display="block"
                                setTimeout(function (){
                                    document.getElementsByClassName("prompt")[0].style.display="none"
                                    location.reload();
                                },500);
                            }
                        })
                        .catch(function (error) {
                            console.log(error);
                        })
                        .then(function () {
                        });
                }else{
                    alert("添加数据不能为空");
                    return;
                }
            },
            //修改数据
            update:function (){
                let pid=document.getElementById("pid").value;
                let name=document.getElementById("name").value;
                let price=document.getElementById("price").value;
                if (pid != "" && name != "" && price != "") {
                    let product = {
                        "id": pid,
                        "name": name,
                        "price": price
                    }
                    axios.put("/api/products", product)
                        .then(function (response) {
                            let i = response.data;
                            if (i>=1){
                                document.getElementsByClassName("prompt")[0].innerHTML="修改成功!"
                                document.getElementsByClassName("prompt")[0].style.display="block";
                                setTimeout(function (){
                                    document.getElementsByClassName("prompt")[0].style.display="none"
                                    location.reload();
                                },500);
                            }

                        })
                        .catch(function (error) {
                            console.log(error);
                        })
                        .then(function () {
                        });
                }
                else{
                    alert("添加数据不能为空");
                }
            },
            //删除数据
            del:function (i){
                axios.delete("/api/products/"+i+"", {}).then(function (response) {
                   let i=response.data;
                   if(i>=1){
                       document.getElementsByClassName("prompt")[0].innerHTML="删除成功!"
                       document.getElementsByClassName("prompt")[0].style.backgroundColor="#FF0000";
                       document.getElementsByClassName("prompt")[0].style.display="block";
                       setTimeout(function (){
                           document.getElementsByClassName("prompt")[0].style.display="none"
                           location.reload();
                       },500);
                   }

                })
                    .catch(function (error) {
                        console.log(error);
                    })
                    .then(function () {
                    });
            }


        }

    });
    //点击修改把数据填写到对应的表单中
    function up(val){
        var value = $(val).parent().parent().find("td");
        let id=value.eq(0).text();
        let name=value.eq(1).text();
        let price=value.eq(2).text();

        let pid=document.getElementById("pid");
        let name1=document.getElementById("name");
        let price1=document.getElementById("price");
        pid.value=id;
        name1.value=name;
        price1.value=price;

        pid.disabled="disabled"
    }
</script>

</body>
</html>
View Code

 

标签:function,Http,name,id,Method,products,增删,Products,public
来源: https://www.cnblogs.com/Ryan-DHQ/p/16192445.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有