JavaWeb+Vue separation project realizes adding, deleting, modifying and checking


foreword

提示:这里可以添加本文要记录的大概内容:

req:request
resp:response

In Java, req means request (request), usually refers to the request message sent by the client to the server. The request can include information such as request method, URL, HTTP version, request header, and request body. The server will receive this request, process it and then return a corresponding response message.

And resp means response (response), usually refers to the response message returned by the server to the client. The response may include information such as HTTP status code, response header, and response body. The client will receive this response and process it, such as rendering a web page, downloading a file, and so on.

In Java, developers can use some frameworks or libraries to handle requests and responses, such as Servlet API or Spring MVC, etc. These frameworks and libraries provide rich APIs and tools to handle network communication, request routing, data transformation and exception handling, etc.


insert image description here

提示:以下是本篇文章正文内容,下面案例可供参考

database

Database code:

drop TABLE IF EXISTS food;
-- IF EXISTS 表名; 作用:如果表存在就删掉(这段代码怎么执行都不会报错)
CREATE TABLE food
(
	foodId int auto_increment PRIMARY KEY,
	foodName VARCHAR(20) NOT NULL,
	foodPrice DOUBLE(8,2) NOT NULL,
	details VARCHAR(255),  -- 菜品描述
	think VARCHAR(255)   -- 菜品评价
);

INSERT INTO food(foodName,foodPrice,details,think)
VALUES('年糕',30.00,'多吃一块,幸福满满','还行,好吃不贵');

backend code

Create a new Javaweb dynamic project

Project package directory:
insert image description here

util code

util: a tool class that encapsulates JDBC code

Note the database name and password inside

package com.project.mvc.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.ParseException;
import java.text.SimpleDateFormat;

public class JdbcUtil {
    
    
	public static Connection createConnection() {
    
    
		
		Connection connection = null;
		try {
    
    
			connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/food?characterEncoding=utf8&serverTimezone=Asia/Shanghai", "root", "123456");
		} catch (SQLException e) {
    
    
			e.printStackTrace();
		}
		
		return connection;
	}
	
	//释放资源 封装到静态方法中 
	public static void close(Statement statement,Connection connection) {
    
    
		try {
    
    
			statement.close();
			connection.close();
		} catch (SQLException e) {
    
    
			e.printStackTrace();
		}
	}
	
	public static void close(ResultSet resultSet,Statement statement,Connection connection) {
    
    
		try {
    
    
			resultSet.close();
			statement.close();
			connection.close();
		} catch (SQLException e) {
    
    
			e.printStackTrace();
		}
	}
	
	//String类型转换为java.sql.Date类型 封装到方法中
	public static java.sql.Date toSqlDate(String string){
    
    
		java.util.Date d1=null;
		java.sql.Date  d2=null;
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		
		try {
    
    
			d1 = sdf.parse(string);
			d2 = new java.sql.Date( d1.getTime() );
		} catch (ParseException e) {
    
    
			e.printStackTrace();
		}
		
		return d2;	
	}
}

listener code

listener: put the listener

package com.project.mvc.listener;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

@WebListener
public class WebServerListener implements ServletContextListener{
    
    
	@Override
	public void contextInitialized(ServletContextEvent sce) {
    
    
		try {
    
    
			Class.forName("com.mysql.cj.jdbc.Driver");
		} catch (ClassNotFoundException e) {
    
    
			e.printStackTrace();
		}
	
	}
}

filter code

filter: put filter

package com.project.mvc.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebFilter("/*")
public class CommonFilter implements Filter{
    
    
	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
    
    
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse resp = (HttpServletResponse) response;
		// 设置请求的编码方式            post方式请求需要
		req.setCharacterEncoding("utf8");
		// 设置响应内容类型及编码方式
		resp.setContentType("application/json;charset=utf8");
		// 设置响应头允许ajax跨域请求
		resp.setHeader("Access-Control-Allow-Origin", "*");
		// 放行 
		chain.doFilter(request, response);
	}
}

po code

po: put simple objects

public class Food {
    
    
	private Integer foodId;
	private String foodName;
	private double foodPrice;
	private String details;
	private String think;
	// Getter/Setter/to String/有参无参构造方法自动生成
}

Dao layer add, delete, modify and check code

dao: data access JDBC

The return result of addition, deletion and modification is an integer

package com.project.mvc.dao;

import java.sql.Connection; 
import java.sql.PreparedStatement; 
import java.sql.ResultSet; 
import java.sql.SQLException; 
import java.util.ArrayList; 
import com.project.mvc.po.Food; 
import com.project.mvc.util.JdbcUtil; 

public class FoodDao {
    
     

    // 插入菜品信息         做封装
    public int insertFood(Food food) {
    
     
    	// 定义返回值,默认值0
        int result = 0;
        // 只有插入需要结果集ResultSet
        Connection connection = null; 
        PreparedStatement statement = null;
        // 创建数据库连接
        connection = JdbcUtil.createConnection(); 
        try {
    
    
            // 创建预编译的 SQL 语句并设置参数,id在数据库中是自增这里不需要写
            statement = connection.prepareStatement("insert into food(foodName,foodPrice,details,think) values(?,?,?,?)"); 
            // 给? 赋值,用setXXX方法
            statement.setString(1, food.getFoodName()); 
            statement.setDouble(2, food.getFoodPrice()); 
            statement.setString(3, food.getDetails()); 
            statement.setString(4, food.getThink()); 

            // 执行 SQL语句,返回结果,增删改用executeUpdate()方法,都属于更新
            result = statement.executeUpdate(); 
        } catch (SQLException e) {
    
    
            // TODO try/catch 包围
            e.printStackTrace();
        } finally {
    
    
            // 关闭数据库连接和预编译的语句
            JdbcUtil.close(statement, connection); 
        }
        // 返回结果
        return result; 
    }

    // 删除指定菜品信息       按照主键删除
    public int deleteFoodId(int foodId) {
    
    
    	// 定义结果,默认值0
        int result = 0; 
        Connection connection = null; 
        PreparedStatement statement = null; 
        // 创建数据库连接
        connection = JdbcUtil.createConnection(); 
        try {
    
    
            // 创建预编译的 SQL 语句并设置参数
            statement = connection.prepareStatement("delete from food where foodId=?"); 
            // 这个方法里面没有封装数据
            statement.setInt(1, foodId); 
            // 执行 SQL语句,返回成功操作的结果,增删改都属于更新
            result = statement.executeUpdate(); 
        } catch (SQLException e) {
    
    
            // TODO try/catch 块
            e.printStackTrace();
        } finally {
    
    
            // 关闭数据库连接和预编译的语句
            JdbcUtil.close(statement, connection); 
        }
        // 返回结果
        return result; 
    }

    // 修改菜品信息
    public int UpdateFood(Food food) {
    
     
    	// 定义返回值
        int result = 0; 
        Connection connection = null; 
        PreparedStatement statement = null; 
        // 创建数据库连接
        connection = JdbcUtil.createConnection(); 
        try {
    
    
            // 创建预编译的 SQL 语句(根据主键改其他列)并设置参数                                    
            statement = connection.prepareStatement("update food set foodName=?,foodPrice=?,details=?,think=? where foodId=?"); 
            // 给? 赋值,用setXXX方法
            statement.setString(1,food.getFoodName()); 
            statement.setDouble(2,food.getFoodPrice()); 
            statement.setString(3,food.getDetails()); 
            statement.setString(4,food.getThink()); 
            statement.setInt(5,food.getFoodId());
            // 执行 SQL语句,返回结果
            result = statement.executeUpdate(); 
        } catch (SQLException e) {
    
    
            // TODO 自动生成的 catch 块
            e.printStackTrace();
        } finally {
    
    
            // 关闭数据库连接和预编译的语句
            JdbcUtil.close(statement, connection); 
        }
        // 返回的结果
        return result; 
    }

    // 模糊查询菜品  返回一个集合
    public ArrayList<Food> query(String foodName){
    
     
    	// 定义返回值
        ArrayList<Food> list = new ArrayList<>(); 
        // 查询需要结果集
        Connection connection = null; 
        PreparedStatement statement = null; 
        ResultSet resultSet = null; 
        // 创建数据库连接
        connection = JdbcUtil.createConnection(); 
        try {
    
    
            // 创建预编译的 SQL 语句并设置参数
            statement = connection.prepareStatement("select foodId,foodName,foodPrice,details,think from food where foodName like ?"); 
            // 设置名字模糊查询      给?赋值
            statement.setString(1,"%"+foodName+"%"); 
            // 执行 SQL 语句,结果是个结果集resultSet
            resultSet = statement.executeQuery(); 
            // 带条件的while循环,有下一个取出来
            while (resultSet.next()) {
    
    
                // 创建出一个Food对象
                Food food = new Food(); 
                // 把结果集的数据取出来,进行Set
                food.setFoodId(resultSet.getInt("foodId")); 
                food.setFoodName(resultSet.getString("foodName")); 
                food.setFoodPrice(resultSet.getDouble("foodPrice")); 
                food.setDetails(resultSet.getString("details"));
                food.setThink(resultSet.getString("think")); 
                // 将 Food 对象添加至查询结果列表
                list.add(food); 
            }
        } catch (SQLException e) {
    
    
            // TODO 自动生成的 catch 块
            e.printStackTrace();
        } finally {
    
    
            // 关闭数据库连接、查询结果和预编译的语句
            JdbcUtil.close(resultSet, statement, connection); 
        }
        // 返回查询结果列表
        return list; 
    }
}

Service layer additions, deletions, changes, and code checks

The caller of dao is service, and service is called by controller

service: business logic class code

The following code uses a ternary operator, which can be interpreted as the following code:

if (dao.insertFood(food) > 0) {
    
    
    return "食品增加成功";
} else {
    
    
    return "食品增加失败";
}

The format of the ternary operator is: 条件表达式 ? 表达式 1 : 表达式 2.
Where the value of the conditional expression is true, return the value of expression 1, otherwise return the value of expression 2.
Therefore, when insertFoodthe method is called to insert food records successfully, and the conditional expression value of the ternary operator is true, it returns "food addition successful", otherwise it returns "food addition failed"

package com.project.mvc.service; 

import java.util.ArrayList; 
import com.google.gson.Gson; 
import com.project.mvc.dao.FoodDao; 
import com.project.mvc.po.Food; 

// 业务类调用 dao 类方法
public class FoodService {
    
     
	//	调用dao,提前创建dao对象
    private FoodDao dao = new FoodDao(); 

    // 定义 add 方法,返回字符串,参数是po类
    public String add(Food food) {
    
     
    	// dao层返回值 是 整数 > 0 ?(是否)成功 : (否则)失败
        return dao.insertFood(food) > 0 ? "食品增加成功" : "食品增加失败";
    }

    // 定义 remove 方法,返回整数
    public String remove(int foodId) {
    
     
        // 调用 FoodDao 类的 deleteFoodId 方法,并返回操作结果
        return dao.deleteFoodId(foodId) > 0 ? "食品删除成功" : "食品删除失败";
    }

    // 定义 update 方法,返回字符串,参数是po类
    public String update(Food food) {
    
     
        // 调用 FoodDao 类的 UpdateFood 方法,并返回操作结果
        return dao.UpdateFood(food) > 0 ? "食品修改成功" : "食品修改失败";
    }

    // 定义 query 方法,返回 Gson格式字符串(按照名字模糊查询,传一个名字进来)
    public String query(String foodName) {
    
     
        // 调用 FoodDao 类的 query 方法,拿到返回的集合
        ArrayList<Food> list = dao.query(foodName); 
        // 创建 Gson 对象
        Gson gson = new Gson(); 
        // 将查询结果转化为 JSON 格式并返回
        return gson.toJson(list); 
    }
}

Controller layer add, delete, modify and check code

controller: put servlet code, business logic class

Test the backend first :

package com.project.mvc.controller;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

// 加WebServlet注解,设置servlet的访问路径
@WebServlet("/food")
// 继承HttpServlet
public class FoodController extends HttpServlet {
    
    

    // 重写servlet的  service方法
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
        
        // 获取 请求 发来的数据
        String action = req.getParameter("action");
        
        // 获取 响应 
        PrintWriter writer = resp.getWriter();
        
        // 根据请求参数中的action值进行不同的处理
        if (action.equals("add")) {
    
     
            // 生成响应  输出
            writer.print("添加请求处理完毕");
        } else if (action.equals("delete")) {
    
    
            // 生成响应  输出
            writer.print("删除请求处理完毕");
        } else if (action.equals("update")) {
    
    
            // 生成响应  输出
            writer.print("更新请求处理完毕");
        } else if (action.equals("query")) {
    
     
            // 生成响应  输出
            writer.print("查找请求处理完毕");
        }
    }
}

Postman test: run the Tomcat server before the test After testing,
insert image description here
all requests are processed

In a real project, the response is not directly generated, but the actual processing code should be written in it

Test each function written here

package com.project.mvc.controller;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.project.mvc.po.Food;
import com.project.mvc.service.FoodService;

@WebServlet("/food")
public class FoodController extends HttpServlet {
    
    
    
    // 创建一个FoodService的实例,用于调用其中的方法
    private FoodService service = new FoodService();
    
    // 重写HttpServlet中的service方法
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) 
        throws ServletException, IOException {
    
    
        
    	// 获取 前端请求 发来的数据
        String action = req.getParameter("action");
        // 获取 响应 
        PrintWriter writer = resp.getWriter();
        
        // 判断请求的类型添加
        if (action.equals("add")) {
    
       
            // 获取请求参数,传过来的数据都是字符串
            String foodName = req.getParameter("foodName");
            String foodPrice = req.getParameter("foodPrice");
            String details = req.getParameter("details");
            String think = req.getParameter("think");
            
            // 创建一个Food对象,用 po对象封装
            Food food = new Food();
            // 调用setXXX方法封装
            food.setFoodName(foodName);
            // 取出来的数据是字符串,这里的数据是double,所以这里需要转型
            food.setFoodPrice(Double.parseDouble(foodPrice)); 
            food.setDetails(details);
            food.setThink(think);
            // 调用service处理,在上面创建,方面后面调用
            
            // 调用FoodService中的add()方法,将数据添加到数据库中
            String result = service.add(food);
            // 将结果输出到前端页面
            writer.print(result);
            
        // 删除数据
        } else if (action.equals("delete")) {
    
      
            // 获取请求参数,类型是String
            String foodId = req.getParameter("foodId");
            // 调用FoodService中的remove()方法,将数据从数据库中删除
            String result = service.remove(Integer.parseInt(foodId));
            // 将结果输出到前端页面
            writer.print(result);
            
        // 更新数据    
        } else if (action.equals("update")) {
    
      
            // 获取请求参数
            String foodId = req.getParameter("foodId");
            String foodName = req.getParameter("foodName");
            String foodPrice = req.getParameter("foodPrice");
            String details = req.getParameter("details");
            String think = req.getParameter("think");
            
            // 创建一个Food对象,用于存储数据(封装)
            Food food = new Food();
            
            // 将获取到的参数存储到Food对象中
            food.setFoodId(Integer.parseInt(foodId));
            food.setFoodName(foodName);
            food.setFoodPrice(Double.parseDouble(foodPrice));
            food.setDetails(details);
            food.setThink(think);
            
            // 调用FoodService中的update()方法,更新数据到数据库中
            String result = service.update(food);
            // 将结果输出到前端页面
            writer.print(result);
        
        // 是查询数据
        } else if (action.equals("query")) {
    
       
            // 获取请求参数,查name数据即可
            String foodName = req.getParameter("foodName");
            // 返回值   调用FoodService中的query()方法,从数据库中查询数据
            String result = service.query(foodName);
            
            // 将结果输出到前端页面
            writer.print(result);
        }
    }
}

Various functional tests:

Add test:
insert image description here

Remove test:
insert image description here

Modify the test:
insert image description here

Query test:
insert image description here

front-end code

Create a new front-end project, check the Router option when creating it, because there is a jump
insert image description here

After creating the project, install axiosand qsframe
Please add a picture description
, and finally generate the content box, left box and upper box

<template>
  <div class="wrapper">
    <header class="header">外卖系统</header>
    <div class="main">
      <aside class="menu">
        <router-link to="/query">外卖管理</router-link>
      </aside>
      <section class="work">
        <router-view></router-view>
      </section>
    </div>
  </div>
</template>

Then randomly generate point style distinction

Then generate three views FoodAdd, FoodQuery,FoodUpdate

Next, index.jsimport these three routes in the file and configure the route object

import FoodAdd from '@/views/FoodAdd'
import FoodQuery from '@/views/FoodQuery'
import FoodUpdate from '@/views/FoodUpdate'
const routes = [
{
    
    
  path: '/query',
  name: 'query',
  component: FoodQuery
},
{
    
    
  path: '/add',
  name: 'add',
  component: FoodAdd
},
{
    
    
  path: '/update',
  name: 'update',
  component: FoodUpdate
}
]

query operation

<template>
  <div>
    菜品名:<input type="text" v-model="foodName">
    <button @click="query">查询</button>
    <button @click="gotoAdd">新增</button>
    <table>
        <tr>
            <th>菜品编号</th>
            <th>菜品名</th>
            <th>菜品价格</th>
            <th>菜品描述</th>
            <th>菜品评价</th>
            <th>修改</th>
            <th>删除</th>
        </tr>
        <tr v-for="(food, index) in items" :key="index">
            <!-- 与po类中属性名一致 -->
            <th>{
    
    {
    
     food.foodId }}</th>
            <th>{
    
    {
    
     food.foodName }}</th>
            <th>{
    
    {
    
     food.foodPrice }}</th>
            <th>{
    
    {
    
     food.details }}</th>
            <th>{
    
    {
    
     food.think }}</th>
            <th><button @click="gotoUpdate(index)">修改</button></th>
            <th><button @click="del(index)">删除</button></th>
        </tr>
    </table>
  </div>
</template>

<script>
import axios from 'axios'
import qs from 'qs'
export default {
    
    
  data () {
    
    
    return {
    
    
        
    }
  },
  methods: {
    
    
   
  },
  components: {
    
    },
  computed: {
    
    },
  watch: {
    
    },
  mounted () {
    
    }
}
</script>

<style scoped>
/* 加点样式 */
</style>

insert image description here
Next, dataconfigure query related data in (two-way bound data: foodName, traversed data: items)

  data () {
    
    
    return {
    
    
        foodName: '',
        items: []
    }
  },

Next in methodsthe request:

  methods: {
    
    
    query(){
    
    
    
    }
  }

Then the framework that needs to be introduced axiossends a request to the backend ( scriptunder the label)

import axios from 'axios'

Then you can querysend the request in the method

    query(){
    
    
        axios.get(`http://localhost:8888/MVCProject/food?action=query&foodName=${
      
      this.foodName}`)
        .then((response)=>{
    
    
         // response:返回来的响应,也可以写成resp
            this.items = response.data
        })
    },

Find the path in postman:
the value of the dish name should become dynamic
insert image description here
after clicking query:
Please add a picture description

delete function

Deletion is to send a post request, and the normal sending of data needs to import qsthe framework ( scriptunder the label)

import qs from 'qs'

Next, send the dish number to the server

// i:下标
 del(i){
    
    
        alert(this.items[i].foodId)
 }      

At this time, click the delete button and there will be a corresponding prompt below.
insert image description here
To delete, two parameters must be passed. The first is the address, and the second is the data sent by post.

    del(i){
    
    
        // alert(this.items[i].foodId)
        axios.post('http://localhost:8888/MVCProject/food',qs.stringify({
    
    
            action: 'delete',
            foodId: this.items[i].foodId
        })).then((response)=>{
    
    
            alert(response.data)
            // 查询删完后的结果
            this.query()
        })
    }

insert image description here

add feature

Method name:gotoAdd

    gotoAdd(){
    
    
    	// 不需要传参,直接加地址
        this.$router.push('/add')
    }

Next, go back to the Add view and add some input boxes

The data here is controllerconsistent with the name of the data in the class

v-model is bound to several properties in an object

<template>
  <div>
    菜品名称:<input type="text" v-model="food.foodName"> <br>
    菜品价格:<input type="text" v-model="food.foodPrice"> <br>
    菜品描述:<input type="text" v-model="food.details"> <br>
    菜品评价:<input type="text" v-model="food.think"> <br>
    <button @click="addFood">新增</button>
  </div>
</template>

write nextdata

  data () {
    
    
    return {
    
    
    	// 对象用{}
        food: {
    
    
            foodName: '',
            foodPrice: '',
            details: '',
            think: '',
        }
    }
  },

methodsNext write addFoodthe method inside

First import the ajax request to import axiosthe framework, because you want to send data, so also import qsthe framework

import axios from 'axios'
import qs from 'qs'

methodsInside:

  methods: {
    
    
    addFood(){
    
    
    							   		// v-model是绑定到food对象里的几个属性  简化
        axios.post('http://localhost:8888/MVCProject/food',qs.stringify(this.food))
	
    }
  },

But there are still few action, so add an action data to the food object

  data () {
    
    
    return {
    
    
        // 对象用{}
        food: {
    
    
            foodName: '',
            foodPrice: '',
            details: '',
            think: '',
            action: 'add'
        }
    }
  },

Then refine addFoodthe method

  methods: {
    
    
    addFood(){
    
    
                                        // v-model是绑定到food对象里的几个属性  简化
        axios.post('http://localhost:8888/MVCProject/food',qs.stringify(this.food))
        .then( (response)=>{
    
    
            // 增加弹窗
            alert(response.data)
        } )
    }
  },

Please add a picture description

Modification method

Route parameter modification

The method has been defined in the FoodQuery page gotoUpdate, so add the gotoUpdate method below

    gotoUpdate(i){
    
    
        this.$router.push({
    
    
            path: '/update',
            // query方式传参
            query: this.items[i]
        })
    }

In the modification page, write the template first:

There must be an ID in the modification page, but it can only be viewed, not modified (read-only):readonly

<template>
  <div>
    菜品编号:<input type="text" readonly v-model="food.foodId"> <br>
    菜品名称:<input type="text" v-model="food.foodName"> <br>
    菜品价格:<input type="text" v-model="food.foodPrice"> <br>
    菜品描述:<input type="text" v-model="food.details"> <br>
    菜品评价:<input type="text" v-model="food.think"> <br>
    <button @click="updateStudent">修改</button>
  </div>
</template>

Next, write the script part:
1. Define the bound object food
2. Complete the updateFood method

  data () {
    
    
    return {
    
    
      food: {
    
    
        foodId: this.$route.query.foodId,
        foodName: this.$route.query.foodName,
        foodPrice: this.$route.query.foodPrice,
        details: this.$route.query.details,
        think: this.$route.query.think,
        action: 'update'
      }
    }
  },

Click the Modify button to see if the data has been passed
insert image description here

The next submission to be modified is imported first under the
labelscript

import axios from 'axios';
import qs from 'qs';

Then send the request, process the response ( .then)

  methods: {
    
    
    updateFood(){
    
    
      axios.post('http://localhost:8888/MVCProject/food',qs.stringify(this.food))
      .then((response)=>{
    
    
        alert(response.data)
      })
    }
  },

insert image description here

session storage modification

Copy the FoodUpdate page and name it FoodUpdateSessionto distinguish it
, then import the route in index.js and configure the route object

import FoodUpdateSession from '@/views/FoodUpdateSession'
//...
{
    
    
  path: '/session',
  name: 'session',
  component: FoodUpdateSession
}

Next, add a modification button to the modification button on the FoodQuery page:

<th><button @click="gotoUpdate(index)">路由传参</button><button @click="gotoSession(index)">会话存储</button></th>

Add the gotoSession method below

    gotoSession(i){
    
    
        this.$router.push('/session')
    }

Let’s see if you can skip it.
insert image description here
There is no data yet. Next, save the data.

    gotoSession(i){
    
    
        sessionStorage.setItem('food',JSON.stringify(this.items[i]))
        this.$router.push('/session')
    }

Then run it again, open the developer tool to view the application→session storage,
insert image description here
then take out the data recovery object form, delete the data in data
in the view, and become:FoodUpdateSession

  data () {
    
    
    return {
    
    
      food: {
    
    

      }
    }
  },

The attribute needs to be fetched in the session, using the hook functionmounted

In the previous view, the data stored in the session needs to be retrieved

  mounted () {
    
    
    let s = sessionStorage.getItem('food')
    s = JSON.parse(s)
    this.food = s
  }

At this time, the data is passed over ,
insert image description here
and now actionit can be modified, but it needs to be sent before sending action, and new attributes are added before sendingaction

  methods: {
    
    
    updateFood(){
    
    
      this.food['action'] = 'update'
      axios.post('http://localhost:8888/MVCProject/food',qs.stringify(this.food))
      .then((response)=>{
    
    
        alert(response.data)
      })
    }
  },

insert image description here


Guess you like

Origin blog.csdn.net/rej177/article/details/131775551