Based on Javaweb+Vue3, realize the front-end and back-end separation project of Taobao selling shoes

Front-end technology stack: HTML+CSS+JavaScript+Vue3
Back-end technology stack: JavaSE+MySQL+JDBC+JavaWeb


foreword

The project in this article may not be in line with real life, it doesn’t matter, it is a note made by the blogger for himself.
If you follow along carefully and find any problems, please feel free to private message or discuss in the comment area

The database and Dao layer code adopt the design and implementation of the back-end management system of Taobao selling shoes based on JavaSE

Please add a picture description

[Error-prone point]: ?actionThe value of the value must match the postman backend

1️⃣ Login function

login backend

Entity classes and databases are no longer rewritten here

One, dao package

In fact, it is a query. The login query focuses on whether it has been found , and the return value is Boolean.

public class AdminDao {
    
    
	public boolean login(Admin admin) {
    
    
		boolean result = false;
		Connection connection = null;
		PreparedStatement statement = null;
		ResultSet resultSet = null;
		
		connection = JdbcUtil.createConnection();
		try {
    
    
			statement = connection.prepareStatement("select * from admin where name=? and password=?");
			// 给? 赋值
			statement.setString(1, admin.getName());
			statement.setString(2,admin.getPassword());
			// 执行
			resultSet = statement.executeQuery();
			
			if (resultSet.next()) {
    
    
				result = true;
			}
		} catch (SQLException e) {
    
    
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		} finally {
    
    
			JdbcUtil.close(resultSet, statement, connection);
		}
		return result;
	}
}

Second, the service packageAdminService

public class AdminService {
    
    
	private AdminDao dao = new AdminDao();
	public String login(Admin admin) {
    
    
		return dao.login(admin)?"成功":"失败";
	}

Three, is the controller packageLoginServlet

1. Inheritance HttpServlet
2. Add WebServletannotation, write path
3. Re- doXXXmethod

@WebServlet("/login")
public class LoginServlet extends HttpServlet{
    
    
	// 重写AdminService代码
	private AdminService service = new AdminService();
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
		// 获取请求发来的名字和密码
		String name = req.getParameter("name");
		String password = req.getParameter("password");
		// 封装
		Admin admin = new Admin();
		admin.setName(name);
		admin.setPassword(password);
		// 调用service方法
		String result = service.login(admin);
		// 发送响应数据
		PrintWriter writer = resp.getWriter();
		writer.print(result);
	}

}

After the backend is written, use Postman to test:
insert image description here

login frontend

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 font-awesomethe framework axiosand qsframework respectively

npm i font-awesome
npm i axios
npm i qs

When installing font-awesomethe framework, you need to main.jsimport a css file in the file to add icons to the page

// 图标导入
import 'font-awesome/css/font-awesome.min.css'

At the same time, add a routing guard

The purpose of the routing guard is that except for the login view, access to other views must be logged in users. If not logged in, it will jump to the login page;
if logged in, the routing jump will be performed normally.

//路由守卫
//在路由实例上调用 beforeEach 方法,用于在导航之前进行拦截
router.beforeEach((to,from,next)=>{
    
    
    //获取当前用户是否已经登陆的状态
    let login = sessionStorage.getItem('login')
    //判断用户登录状态是否存在或者将要进入的路径为根目录
    if (login!=null || to.path=='/') {
    
    
        //如果用户已经登录或将要进入的是根目录,则正常进行导航
        next()
    } else {
    
    
        //如果用户未登录则强制跳转到根目录
        router.push('/')
    }
})

The next step is to clear the useless code and components generated in the project

Leave only one routing outlet in the root component

<template>
  <router-view></router-view>
</template>

IndexViewGenerate and LoginViewtwo views in the views folder

The next step index.jsis to import two views and routing configuration in the file

import LoginView from '@/views/LoginView'
import IndexView from '@/views/IndexView'
const routes = [
  {
    
    
    // 默认访问视图
    path: '/',
    name: 'login',
    component: LoginView
  },
  {
    
    
    path: '/index',
    name: 'index',
    component: IndexView,
   }
  //  下面配置子路由
]

index.htmlAdd style in to make it fill the entire parent tag

  html,body,#app{
    
    
    width: 100%;
    height: 100%;
    margin: 0;
  }

In the login view:

<template>
  <div class="wrapper">
    <div class="login">
      <i class="fa fa-user-o"></i><input type="text" v-model="name"> <br>
      <i class="fa fa-lock"></i><input type="password" v-model="password"> <br>
      <button @click="login">登录</button>
    </div>
  </div>
</template>

Then add some style

<style scoped>
.wrapper {
    
    
  width: 100%;
  height: 100%;
  background: linear-gradient(rgba(0, 0, 0, 0.6), rgba(0, 0, 0, 0.6)), url(../assets/bg.jpeg); /* 使用渐变遮罩来增强背景图的视觉效果 */
  background-repeat: no-repeat;
  background-size: cover;
  background-position: center center;
  padding: 50px 0; /* 增加上下内边距来让内容与背景之间有一定的间隔感 */
  display: flex;
  justify-content: center;
  align-items: center;
}

.login {
    
    
  max-width: 400px; /* 按实际情况增加登录框的最大宽度 */
  margin: 0 auto; /* 让登录框居中对齐 */
  padding: 30px; /* 调整上下左右内边距让内容与边缘之间有更多的间距 */
  box-shadow: 5px 5px 15px rgba(0, 0, 0, 0.3); /* 调整阴影效果的参数来产生更自然的视觉效果 */
}

input[type="text"], input[type="password"] {
    
    
  margin-bottom: 10px; /* 拉开间距 */
  margin-left: 10px; /* 拉开间距 */

  border-radius: 20px; /* 使用更大的圆角半径增强输入框的圆润感 */
  border: none; /* 取消边框使输入框看起来更为简洁 */
  background-color: rgba(255, 255, 255, 0.9); /* 使用透明度来让背景色渐变过渡,增强美感 */
  height: 50px; /* 增加输入框的高度让文字更加易读 */
  font-size: 18px; /* 调整字体大小 */
  padding: 0 20px; /* 调整左右内边距增加输入框内部空间 */
  box-shadow: 5px 5px 15px rgba(0, 0, 0, 0.1); /* 添加输入框的轻微阴影效果 */
}

button {
    
    
  width: 100%;
  height: 50px; /* 增加按钮的高度 */
  border: none;
  background-color: #4CAF50; /* 使用绿色来增强按钮的视觉效果 */
  color: #fff;
  font-size: 18px;
  border-radius: 20px; /* 使用更大的圆角半径来增强按钮的圆润感 */
  cursor: pointer;
  transition: all 0.2s ease-in-out; /* 添加按钮的渐变动画效果 */
}

button:hover {
    
    
  background-color: #3e8e41; /* 鼠标悬停时,按钮背景色变为深绿色 */
  box-shadow: 5px 5px 15px rgba(0, 0, 0, 0.3); /* 鼠标悬停时,添加更明显的阴影效果 */
}

</style>

insert image description here

Next, configure the two data (name and password) of v-model in data

  data () {
    
    
    return {
    
    
      // 默认为空
      naem: '',
      password: '',
    }
  },

After completing the binding, write loginthe method and add it methods, use login to send the request, and send the request to import the packageaxios

The qs package is to send a get request, and the get request data is spliced ​​into the address, so it is not needed for now

import axios from 'axios';

//.....

  methods: {
    
    
    login(){
    
    
      axios.get(`http://localhost:8888/taobao_admin/login?name=${
      
      this.name}&password=${
      
      this.password}`)
      // 生成响应
      .then((resp)=>{
    
    
      // 做个弹窗
       alert(resp.data)
      })
    }
  },

After entering the correct user name and password, click Login, and a prompt box will pop up at the top of the page to prompt success, otherwise, it will prompt failure.
insert image description here
If it shows success, you need to complete the jump to the home page.

  methods: {
    
    
    login(){
    
    
      axios.get(`http://localhost:8888/taobao_admin/login?name=${
      
      this.name}&password=${
      
      this.password}`)
      // 生成响应
      .then((resp)=>{
    
    
      // 做个弹窗
      //  alert(resp.data)
      if (resp.data=='成功') {
    
    
          sessionStorage.setItem('login',this.name)
          this.$router.push('index')
        } else {
    
    
          this.isErr = true,
          this.name = '',
          this.password = ''
        }
      })
    }
  },

[Code Explanation]:
After entering the user name and password, click the login button, and loginthe function will be triggered. This function uses axiosthe library to send a GET request to the specified URL, which contains the username and password, and waits for the server to respond. If the response returns "success", store the username in the browser's sessionStorageand redirect the user to the "index" page. If the response returns something else, it means the login failed, the username and password will be cleared, and isErrset to true, so that an error message is displayed on the UI.

Home view code:

<template>
  <div class="wrapper">
    <header>
        <img src="../assets/logo.png" alt="">
        <!-- 从会话中取出的名字 -->
        <h4>欢迎,{
   
   { name }}登录</h4>
    </header>
    <div class="main">
        <aside>
            <router-link to="">商家信息</router-link> <br>
            <router-link to="">鞋子信息</router-link> <br>
        </aside>
        <section>
            <router-view></router-view>
        </section>
    </div>
  </div>
</template>

Then add the style code

<style scoped>
.wrapper{
    
    
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
}

header{
    
    
  width: 100%;
  flex: 0 0 100px;
  background-color: #c6e2ff;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

header img{
    
    
  width: 160px;
}

.main{
    
    
  width: 100%;
  flex: 1;
  display: flex;
}

aside{
    
    
  flex: 0 0 180px;
  height: 100%;
  background-color: #d9ecff;
}

section{
    
    
  flex: 1;
  height: 100%;
  background-color: #ecf5ff;
}
</style>

The interpolation syntax is a name, which needs to databe configured in

  data () {
    
    
    return {
    
    
        name: ''
    }
  },

The name is obtained from the session storage and needs to be written into the hook function after the mount is completed. After the mount is completed, the data in the session is taken out and assigned to the name

  mounted () {
    
    
    this.name = sessionStorage.getItem('login')
  }

Then login successfully
insert image description here

2️⃣Business management

For back-end additions, deletions, modifications, and checks, only write (in order) dao, service, and controller
to view code annotations

Query business

Query Merchant Backend

The name of the query method here isqueryshop

dao package:

// 模糊查询
	public ArrayList<Shop> queryshop(String shopName){
    
    
		ArrayList<Shop> list = new ArrayList<>();
		Connection connection = null;
		PreparedStatement statement = null;
		ResultSet resultSet = null;

		connection = JdbcUtil.createConnection();
		try {
    
    
			statement = connection.prepareStatement("select * from shop where shopName like ?");
			statement.setString(1, "%"+shopName+"%");
			resultSet = statement.executeQuery();
			while (resultSet.next()) {
    
    
				Shop shop = new Shop();

				shop.setShopId(resultSet.getInt("shopId"));
				shop.setShopName(resultSet.getString("shopName"));
				shop.setShopAddress(resultSet.getString("shopAddress"));
				shop.setShopExplain(resultSet.getString("shopExplain"));
				shop.setSalePrice(resultSet.getDouble("salePrice"));
				shop.setDeliveryPrice(resultSet.getDouble("deliveryPrice"));
				list.add(shop);
			}
		} catch (SQLException e) {
    
    
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		} finally {
    
    
			JdbcUtil.close(resultSet, statement, connection);
		}
		return list;
	}

service package:

For querying, adding, and modifying multiple data, write a dao class package here

//调用dao,提前创建dao对象
	private ShopDao dao = new ShopDao();
	
	public String queryshop(String shopName) {
    
    
		ArrayList<Shop> list = dao.queryshop(shopName);
		Gson gson = new Gson();
		return gson.toJson(list);
	}

controller package:

@WebServlet("/shop")
public class ShopController extends HttpServlet{
    
    
    private ShopService service = new ShopService();

//	req请求     resp响应
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
		
		String action = req.getParameter("action");
		PrintWriter writer = resp.getWriter();

	if (action.equals("queryshop")){
    
    
			String shopName = req.getParameter("shopName");
			String result = service.queryshop(shopName);
			writer.print(result);
		} 	
	}
}

postman test:
insert image description here

Query merchant front end

Create a new folder shop under the front-end view folder, and create a new view ShopQueryView in it

First, add the configuration routing object of the query merchant under the home page configuration

  {
    
    
    path: '/index',
    name: 'index',
    component: IndexView,
    //  下面配置子路由
    children: [
      {
    
    
        path: '/queryshop',
        name: 'queryshop',
        component: () => import('@/views/shop/ShopQueryView')
      },
    ]
   },

Then

<template>
  <div>
    <input type="text" v-model="shopName" />
    <button @click="queryshop">查询</button>
    <button @click="addshop">新增</button>

    <table>
      <tr>
        <th>商家编号</th>
        <th>商家名称</th>
        <th>商家地址</th>
        <th>商家介绍</th>
        <th>所售价格</th>
        <th>快递费</th>
        <th>修改</th>
        <th>删除</th>
      </tr>
      <tr v-for="(shop, index) in items" :key="index">
        <th>{
    
    {
    
     shop.shopId }}</th>
        <th>{
    
    {
    
     shop.shopName }}</th>
        <th>{
    
    {
    
     shop.shopAddress }}</th>
        <th>{
    
    {
    
     shop.shopExplain }}</th>
        <th>{
    
    {
    
     shop.salePrice }}</th>
        <th>{
    
    {
    
     shop.deliveryPrice }}</th>
        <th><button @click="updateshop(index)">修改</button></th>
        <th><button @click="delshop(index)">删除</button></th>
      </tr>
    </table>
  </div>
</template>

<script>
import axios from 'axios'
export default {
    
    
  data() {
    
    
    return {
    
    
      shopName: '',
   
      items: []
    }
  },
  methods: {
    
    
    queryshop() {
    
    
      axios.get(`http://localhost:8888/taobao_admin/shop?action=queryshop&shopName=${
      
      this.shopName}`)
        .then((resp) => {
    
    
          this.items = resp.data
        })
    },
  },
  components: {
    
    },
  computed: {
    
    },
  watch: {
    
    },
  mounted() {
    
     }
}
</script>

insert image description here

Add business

Add Merchant Backend

The method used here isaddshop

dao package:

	// 新增商家
	public int insertShop(Shop shop) {
    
    
		int result = 0;
		Connection connection = null;
		PreparedStatement statement = null;
		connection = JdbcUtil.createConnection();
		try {
    
    
			statement = connection.prepareStatement("insert into shop(shopName,shopAddress,shopExplain,salePrice,deliveryPrice) values(?,?,?,?,?)");
			statement.setString(1, shop.getShopName());
			statement.setString(2, shop.getShopAddress());
			statement.setString(3, shop.getShopExplain());
			statement.setDouble(4, shop.getSalePrice());
			statement.setDouble(5, shop.getDeliveryPrice());

			result = statement.executeUpdate();
		} catch (SQLException e) {
    
    
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		} finally {
    
    
			JdbcUtil.close(statement, connection);
		}
		return result;
	}

service package:

	public String addshop(Shop shop) {
    
    
		return dao.insertShop(shop)>0?"商家添加成功":"商家添加失败";
	}

controller package:

@WebServlet("/shop")
public class ShopController extends HttpServlet{
    
    
    private ShopService service = new ShopService();

//	req请求     resp响应
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
		
		String action = req.getParameter("action");
		PrintWriter writer = resp.getWriter();
		
		if (action.equals("addshop")) {
    
    
			String shopName = req.getParameter("shopName");
			String shopAddress = req.getParameter("shopAddress");
			String shopExplain = req.getParameter("shopExplain");
			String salePrice = req.getParameter("salePrice");
			String deliveryPrice = req.getParameter("deliveryPrice");
			Shop shop = new Shop();
			
			shop.setShopName(shopName);
			shop.setShopAddress(shopAddress);
			shop.setShopExplain(shopExplain);
			shop.setSalePrice(Double.parseDouble(salePrice));
			shop.setDeliveryPrice(Double.parseDouble(deliveryPrice));
			
			String result = service.addshop(shop);
			writer.print(result);
		}
	}
}

Backend tests:
insert image description here

Add merchant front end

First add the configured sub-routes in index.js

      {
    
    
        path: '/addshop',
        name: 'addshop',
        component: () => import('@/views/shop/ShopAddView')
      }

Back to the insert view, push the address in the methods: addshop

    addshop() {
    
    
      this.$router.push('./addshop')
    },

Then create a new view ShopAddView and add some input boxes to the view

The data here is consistent with the name of the data fetched in the controller class

v-model is bound to several properties in an object

<template>
  <div>
    商家名称:<input type="text" v-model="shop.shopName"> <br>
    商家地址:<input type="text" v-model="shop.shopAddress"> <br>
    商家介绍:<input type="text" v-model="shop.shopExplain"> <br>
    商品价格:<input type="text" v-model="shop.salePrice"> <br>
    快递费:&emsp;<input type="text" v-model="shop.deliveryPrice"> <br>
    <button @click="addshop">新增</button>
  </div>
</template>

Add the content to be added in data

  data () {
    
    
    return {
    
    
      shop: {
    
    
        shopName:'',
        shopAddress: '',
        shopExplain: '',
        salePrice:'',
        deliveryPrice:'',
        action: 'addshop'
      },
    }
  },

Then import the qs and axios frameworks,

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

Next, write the addshop method in methods, the name here is the same as the name in the button event added earlier

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

insert image description here
Answer the query page and you will find that there are more data added just now

Next, add some styles to add merchants, perform form validation, and check whether the added input box is empty. If any input box is empty, the corresponding prompt message will be displayed, and no request will be sent.

<template>
  <div>
    <div class="form-group">
      <label for="shopName">商家名称:</label>
      <input type="text" id="shopName" v-model.trim="shop.shopName">
      <span v-if="!shop.shopName" class="error-msg">商家名称不能为空!</span>
    </div>
    <div class="form-group">
      <label for="shopAddress">商家地址:</label>
      <input type="text" id="shopAddress" v-model.trim="shop.shopAddress">
      <span v-if="!shop.shopAddress" class="error-msg">商家地址不能为空!</span>
    </div>
    <div class="form-group">
      <label for="shopExplain">商家介绍:</label>
      <input type="text" id="shopExplain" v-model.trim="shop.shopExplain">
      <span v-if="!shop.shopExplain" class="error-msg">商家介绍不能为空!</span>
    </div>
    <div class="form-group">
      <label for="salePrice">商品价格:</label>
      <input type="text" id="salePrice" v-model.number="shop.salePrice">
      <span v-if="!shop.salePrice" class="error-msg">商品价格不能为空!</span>
    </div>
    <div class="form-group">
      <label for="deliveryPrice">快递费:&emsp;</label>
      <input type="text" id="deliveryPrice" v-model.number="shop.deliveryPrice">
      <span v-if="!shop.deliveryPrice" class="error-msg">快递费不能为空!</span>
    </div>
    <button @click="addshop">新增</button>
    <p v-if="errorMsg" class="error-msg">{
    
    {
    
    errorMsg}}</p>
  </div>
</template>

<script>
import qs from 'qs'
import axios from 'axios'
export default {
    
    
  data() {
    
    
    return {
    
    
      shop: {
    
    
        shopName: '',
        shopAddress: '',
        shopExplain: '',
        salePrice: '',
        deliveryPrice: '',
        action: 'addshop'
      },
      errorMsg: ''
    }
  },
  methods: {
    
    
    addshop() {
    
     
      if (!this.shop.shopName) {
    
    
        //商家名称不能为空
        this.errorMsg = '商家名称不能为空!'
      } else if (!this.shop.shopAddress) {
    
    
        //商家地址不能为空
        this.errorMsg = '商家地址不能为空!'
      } else if (!this.shop.shopExplain) {
    
    
        //商家介绍不能为空
        this.errorMsg = '商家介绍不能为空!'
      } else if (!this.shop.salePrice) {
    
    
        //商品价格不能为空
        this.errorMsg = '商品价格不能为空!'
      } else if (!this.shop.deliveryPrice) {
    
    
        //快递费不能为空
        this.errorMsg = '快递费不能为空!'
      } else {
    
    
        axios.post('http://localhost:8888/taobao_admin/shop', qs.stringify(this.shop))
          .then(response => {
    
    
            alert(response.data);
          })
      }
    }
  },
  components: {
    
    },
  computed: {
    
    },
  watch: {
    
    },
  mounted() {
    
    }
}
</script>

<style scoped>
.form-group {
    
    
  margin-bottom: 10px;
}

.error-msg {
    
    
  color: red;
  margin-left: 10px;
}
</style>

Output effect:
insert image description here
insert image description here

delete business

Delete Merchant Backend

The delete method uses thedelshop

under the dao package:

	// 删除商家
	public int deleteShopId(int shopId) {
    
    
		int result = 0;
		Connection connection = JdbcUtil.createConnection();
		PreparedStatement statement = null;

		try {
    
    
			statement = connection.prepareStatement("delete from shop where shopId = ?");
			statement.setInt(1, shopId);

			result = statement.executeUpdate();
			
		} catch (SQLException e) {
    
    
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		} finally {
    
    
			JdbcUtil.close(statement, connection);
		}
		return result;
	}

service package:

	public String remove(int shopId) {
    
    
		return dao.deleteShopId(shopId)>0?"商家删除成功":"商家删除失败";
	}

controller package:

	else if (action.equals("delshop")) {
    
    
	String shopId = req.getParameter("shopId");
	String result = service.remove(Integer.parseInt(shopId));
	writer.print(result);

Backend tests:
insert image description here

Delete Merchant Frontend

under query view

    // i:下标
    delshop(i){
    
    
        // alert(this.items[i].shopId)
        axios.post('http://localhost:8888/taobao_admin/shop',qs.stringify({
    
    
            action: 'delshop',
            shopId: this.items[i].shopId
        })).then((response)=>{
    
    
            alert(response.data)
            // 查询删完后的结果
            this.queryshop()
        })
    }

insert image description here


Next, add a small style to the delete merchant function: when the merchant still has products for sale, it cannot be deleted

First, in the backend service package, the delete function is changed to:

	public String remove(int shopId) {
    
    
		return dao.deleteShopId(shopId)>0?"商家删除成功":"该商家仍有菜品不允许删除";
	}

First check the merchant ID in the food table, and then delete the merchant ID in the merchant table

dao package code:

	// 删除商家
	public int deleteShopId(int shopId) {
    
    
		int result = 0;
		Connection connection = JdbcUtil.createConnection();
		PreparedStatement statement = null;
		try {
    
    
			statement = connection.prepareStatement("delete from shop where shopId = ?");
			statement.setInt(1, shopId);
			result = statement.executeUpdate();
		} catch (SQLException e) {
    
    
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		} finally {
    
    
			JdbcUtil.close(statement, connection);
		}
		return result;
	}

Controller package code:

		  else if (action.equals("delshop")) {
    
    
			String shopId = req.getParameter("shopId");
			String result = service.remove(Integer.parseInt(shopId));
			writer.print(result);
		}

Front-end code:

    // i:下标
    delshop(i){
    
    
        // alert(this.items[i].shopId)
        axios.post('http://localhost:8888/taobao_admin/shop',qs.stringify({
    
    
            action: 'delshop',
            shopId: this.items[i].shopId
        })).then((response)=>{
    
    
            alert(response.data)
            // 查询删完后的结果
            this.queryshop()
        })
    }

write back
insert image description here

edit business

The method used is:updateshop

Modify Merchant Backend

dao layer:

	// 更新商家
	public int UpdateShop(Shop shop) {
    
    
		int result = 0;
		Connection connection = null;
		PreparedStatement statement = null;
		connection = JdbcUtil.createConnection();

		try {
    
    
			statement = connection.prepareStatement("update shop set shopName=?,shopAddress=?,shopExplain=?,salePrice=?,deliveryPrice=? where shopId=?");
			statement.setString(1, shop.getShopName());
			statement.setString(2, shop.getShopAddress());
			statement.setString(3, shop.getShopExplain());
			statement.setDouble(4, shop.getSalePrice());
			statement.setDouble(5, shop.getDeliveryPrice());
			statement.setInt(6, shop.getShopId());
			result = statement.executeUpdate();
		} catch (SQLException e) {
    
    
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		} finally {
    
    
			JdbcUtil.close(statement, connection);
		}
		return result;

	}

service layer:

	public String remove(int shopId) {
    
    
		return dao.deleteShopId(shopId)>0?"商家删除成功":"该商家仍有菜品不允许删除";
	}

controller layer:

		  else if (action.equals("updateshop")) {
    
    
			String shopId = req.getParameter("shopId");
			String shopName = req.getParameter("shopName");
			String shopAddress = req.getParameter("shopAddress");
			String shopExplain = req.getParameter("shopExplain");
			String salePrice = req.getParameter("salePrice");
			String deliveryPrice = req.getParameter("deliveryPrice");
			
			Shop shop = new Shop();
			shop.setShopId(Integer.parseInt(shopId));
			shop.setShopName(shopName);
			shop.setShopAddress(shopAddress);
			shop.setShopExplain(shopExplain);
			shop.setSalePrice(Double.parseDouble(salePrice));
			shop.setDeliveryPrice(Double.parseDouble(deliveryPrice));
			
			String result = service.updateshop(shop);
			writer.print(result);
			
		}

Modify Merchant Frontend

under the index.js folder

      {
    
    
        path: '/updateshop',
        name: 'updateshop',
        component: () => import('@/views/shop/ShopUpdateView')
      }

query view

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

Modify view: ShopUpdateView

<template>
  <div>
    商家编号:<input type="text" readonly v-model="shop.shopId"> <br>
    商家名称:<input type="text" v-model="shop.shopName"> <br>
    商家地址:<input type="text" v-model="shop.shopAddress"> <br>
    商家介绍:<input type="text" v-model="shop.shopExplain"> <br>
    商品价格:<input type="text" v-model="shop.salePrice"> <br>
    快递费:&ensp;&ensp;<input type="text" v-model="shop.deliveryPrice"> <br>
    <button @click="updateshop">修改</button>
  </div>
</template>

<script>
import axios from 'axios'
import qs from 'qs'
export default {
    
    
  data () {
    
    
    return {
    
    
      shop:{
    
    
        shopId:this.$route.query.shopId,
        shopName:this.$route.query.shopName,
        shopAddress:this.$route.query.shopAddress,
        shopExplain:this.$route.query.shopExplain,
        salePrice:this.$route.query.salePrice,
        deliveryPrice:this.$route.query.deliveryPrice,
        action: 'update'
      }
    }
  },
  methods: {
    
    
    // 发请求,1.导入  2.处理响应 .then   resp:响应信息
    updateshop(){
    
    
      axios.post('http://localhost:8888/taobao_admin/shop?action=updateshop',qs.stringify( this.shop ))
      .then( (resp)=>{
    
     
        alert( resp.data )
      })
    }
  },
  components: {
    
    },
  computed: {
    
    },
  watch: {
    
    },
  mounted () {
    
    
   
  }
}
</script>
<style scoped>
</style> 

insert image description here


提示:以下是项目另一组增删改查,下面代码可供参考

3️⃣Shoe Management

First let him have a jump in the main page view

<router-link to="querygoods">鞋子信息</router-link> <br>

Configure child routes in the index.js file

      {
    
    
        path: '/querygoods',
        name: 'querygoods',
        component: () => import('@/views/goods/GoodsQueryView')
      }

query shoes

Here is hoping that the same query button can find both the name of the shoe and the name of the merchant to which it belongs

Query the shoe backend

dao class code:

    // 鞋子名模糊查询,这里用到多表连接
	public ArrayList<Goods> nameQuery(String name) {
    
    
		Connection connection = JdbcUtil.createConnection();
		PreparedStatement statement = null;
		ResultSet resultSet = null;
		ArrayList<Goods> list = new ArrayList<>();
		try {
    
    
			statement = connection.prepareStatement("select goods.goodsId,goods.goodsName,goods.goodsExplain,goods.goodsPrice,goods.shopId,shop.shopName from goods,shop where shop.shopName=? and goods.shopId=shop.shopId");
			statement.setString(1, name);
			resultSet = statement.executeQuery();
			while(resultSet.next()) {
    
    
				Goods f =new Goods();
				f.setGoodsId( resultSet.getInt("goodsId")  );
				f.setGoodsName( resultSet.getString("goodsName"));
				f.setGoodsExplain( resultSet.getString("goodsExplain"));
				f.setGoodsPrice( resultSet.getDouble("goodsPrice"));
				f.setShopId(resultSet.getInt("shopId"));
				f.setShopName( resultSet.getString("shopName"));
				list.add(f);
			}
		} catch (SQLException e) {
    
    
			e.printStackTrace();
		} finally {
    
    
			JdbcUtil.close(resultSet, statement, connection);
		}
		return list;
	}
	public ArrayList<Goods> goodsQuery(Goods goods){
    
    
		ArrayList<Goods> list = new ArrayList<>();
		Connection connection = JdbcUtil.createConnection();
		PreparedStatement statement=null;
		ResultSet resultSet=null;
		
		try {
    
    
			StringBuilder sql = new StringBuilder();
			sql.append(" select goods.goodsId,goods.goodsName,goods.goodsExplain,goods.goodsPrice,goods.shopId,shop.shopName");
			sql.append(" from goods,shop");
			sql.append(" where goods.shopId=shop.shopId");
			if ( goods.getGoodsName()!=null ) {
    
    
				sql.append(" and goods.goodsName like ?" );
			}
			if ( goods.getShopName()!=null ) {
    
    
				sql.append(" and shop.shopName like ?");
			}
			if ( goods.getShopId()!= null) {
    
    
				sql.append(" and goods.shopId=?");
			}
			
			statement = connection.prepareStatement(sql.toString());
			int index=1;
			if ( goods.getGoodsName()!=null ) {
    
    
				statement.setString(index++, "%"+goods.getGoodsName()+"%");
			}
			if ( goods.getShopName()!=null ) {
    
    
				statement.setString(index++, "%"+goods.getShopName()+"%");
			}
			if ( goods.getShopId()!=null ) {
    
    
				statement.setInt(index++, goods.getShopId());
			}
			resultSet = statement.executeQuery();
			while ( resultSet.next() ) {
    
    
				Goods f =new Goods();
				f.setGoodsId( resultSet.getInt("goodsId")  );
				f.setGoodsName( resultSet.getString("goodsName"));
				f.setGoodsExplain( resultSet.getString("goodsExplain"));
				f.setGoodsPrice( resultSet.getDouble("goodsPrice"));
				f.setShopId(resultSet.getInt("shopId"));
				f.setShopName( resultSet.getString("shopName"));
				list.add(f);
			}
			
			
		} catch (SQLException e) {
    
    
			e.printStackTrace();
		}finally {
    
    
			JdbcUtil.close(resultSet, statement, connection);
		}
		
		return list;
	}

Service code:

	public String query(Goods goods) {
    
    
		return new Gson().toJson(dao.goodsQuery(goods));
	}
	public String nameQuery(String name) {
    
    
		return new Gson().toJson(dao.nameQuery(name));
	}

Controller class code:

          if (action.equals("query")) {
    
    
			Goods goods = new Goods();
			String goodsName = req.getParameter("goodsName");
			String shopName = req.getParameter("shopName");
			String shopId = req.getParameter("shopId");
			goods.setGoodsName(goodsName);
			goods.setShopName(shopName);
			if (!shopId.isEmpty()) {
    
    				
				goods.setShopId(Integer.parseInt(shopId));	
			}
			String result = service.query(goods);
			writer.print(result);
		
		}else if (action.equals("queryS")) {
    
    
			String name = req.getParameter("name");
			String result = service.nameQuery(name);
			writer.print(result);
		}

Query the front end of the shoe

<template>
  <div>
    <h1>鞋子查询页面</h1>
    <select v-model="id">
      <option value="">店铺名称</option>
      <option v-for="(shop, index) in shopes" :value="shop.shopId" :key="index">{
    
    {
    
     shop.shopName }}</option>
    </select>
    鞋子名字:<input type="text" v-model="goodsName" />
    所属商家:<input type="text" v-model="shopName" />
    <button @click="querynames">查询</button>
    <button @click="addgoods">新增</button> <br>
    
    <table>
      <tr>
        <th>鞋子编号</th>
        <th>鞋子名称</th>
        <th>鞋子介绍</th>
        <th>鞋子价格</th>
        <th>所属商家编号</th>
        <th>所属商家名字</th>
        <th>修改</th>
        <th>删除</th>
      </tr>
      <tr v-for="(goods, index) in goodses" :key="index">
        <th>{
    
    {
    
     goods.goodsId }}</th>
        <th>{
    
    {
    
     goods.goodsName }}</th>
        <th>{
    
    {
    
     goods.goodsExplain }}</th>
        <th>{
    
    {
    
     goods.goodsPrice }}</th>
        <th>{
    
    {
    
     goods.shopId }}</th>
        <th>{
    
    {
    
     goods.shopName }}</th>
        <th><button @click="gotoSession(index)">修改</button></th>
        <th><button @click="delgoods(index)">删除</button></th>
      </tr>
    </table>
  </div>
</template>

<script>
import axios from 'axios'
import qs from 'qs'
export default {
    
    
  data() {
    
    
    return {
    
    
      goodsName: '',
      goodses: [],
      shopes: [],
      shopName: '',
      id: ''
    }
  },
  methods: {
    
    
    querynames() {
    
    
      axios.get(`http://localhost:8888/taobao_admin/goods?action=query&goodsName=${
      
      this.goodsName}&shopName=${
      
      this.shopName}&shopId=${
      
      this.id}`)
      .then((resp) => {
    
    
        this.goodses = resp.data
      })
    },
  },
  components: {
    
    },
  computed: {
    
    },
  watch: {
    
    },
  mounted() {
    
    
    axios.get(`http://localhost:8888/taobao_admin/shop?shopName=&action=queryshop`)
    .then((resp) => {
    
    
      this.shopes = resp.data
    })
  },
}
</script>

<style scoped>
table {
    
    
  width: 700px;
  border: 1px solid #1fb121;
  border-collapse: collapse;
}

th {
    
    
  border: 1px solid #1f5eb1;
}
</style>

insert image description here

add shoes

Here is a drop-down box to display the name of the merchant. When clicking the Add button, you can choose the merchant

addgoods method

Increase the rear end of the shoe

dao package:

	public int InsertGoods(Goods goods) {
    
     
        int result = 0;
        Connection connection = null; 
        PreparedStatement statement = null;
        connection = JdbcUtil.createConnection(); 
        try {
    
    
            statement = connection.prepareStatement("insert into goods (goodsName,goodsExplain,goodsPrice,shopId) values (?,?,?,?)"); 
            // 给? 赋值,用setXXX方法
            statement.setString(1, goods.getGoodsName()); 
            statement.setString(2, goods.getGoodsExplain()); 
            statement.setDouble(3, goods.getGoodsPrice()); 
            statement.setInt(4, goods.getShopId()); 
            result = statement.executeUpdate(); 
        } catch (SQLException e) {
    
    
            // TODO try/catch 包围
            e.printStackTrace();
        } finally {
    
    
            JdbcUtil.close(statement, connection); 
        }
        return result; 
    }

service package:

    public String addgoods(Goods goods) {
    
    
        return dao.InsertGoods(goods) > 0 ? "鞋子增加成功" : "鞋子增加失败";
    }

controller package:

        else if (action.equals("addgoods")) {
    
     
            String goodsName = req.getParameter("goodsName");
            String goodsExplain = req.getParameter("goodsExplain");
            String goodsPrice = req.getParameter("goodsPrice");
            String shopId = req.getParameter("shopId");

            Goods goods = new Goods();
            goods.setGoodsName(goodsName);
            goods.setGoodsExplain(goodsExplain);
            goods.setGoodsPrice(Double.parseDouble(goodsPrice)); 
            goods.setShopId(Integer.parseInt(shopId));
            String result = service.addgoods(goods);
            writer.print(result);

        }

Increase the front of the shoe

The qs framework has been imported during the previous query, so there is no need to repeat it here
Add: addgoods method to the methods in the query view

    addgoods() {
    
    
      this.$router.push('/addgoods')
    },

Create a new GoodsAddView view and add routing configuration to the index.js file

      {
    
    
        path: '/addgoods',
        name: 'addgoods',
        component: () => import('@/views/goods/GoodsAddView')
      }

GoodsAddView view:

<template>
  <div>
    鞋子名称:<input type="text" v-model="goods.goodsName" required> <br>
    <p v-show="!goods.goodsName" class="err">输入鞋子名称不能为空!</p>
    鞋子描述:<input type="text" v-model="goods.goodsExplain" required> <br>
    <p v-show="!goods.goodsExplain" class="err">输入鞋子描述不能为空!</p>
    鞋子价格:<input type="text" v-model="goods.goodsPrice" required> <br>
    <p v-show="!goods.goodsPrice" class="err">输入鞋子价格不能为空!</p>
    <select v-model="goods.shopId">
      <option value="">所属商家编号</option>
      <option :value="this.shopes[index].shopId" v-for="(shop, index) in shopes" :key="index">{
    
    {
    
     shop.shopName }}</option>
    </select>

    <p class="err">所选商家编号不能为空!</p>
    <button @click="addgoods">新增</button>
  </div>
</template>


<script>
import axios from 'axios'
import qs from 'qs'

export default {
    
    
  data () {
    
    
    return {
    
    
      goods: {
    
    
        goodsName: '',
        goodsExplain: '',
        goodsPrice: '',
        shopId: '',
        // postman后端匹配  action前是?
        action: 'addgoods'  
      },
      shopes: [],
    }
  },
  methods: {
    
    
    addgoods () {
    
    
      axios.post('http://localhost:8888/taobao_admin/goods', qs.stringify(this.goods))
        .then((resp)=>{
    
    
          alert(resp.data)
        })
    }
  },

components: {
    
    },
  computed: {
    
    },
  watch: {
    
    },
  mounted() {
    
    
    axios.get(`http://localhost:8888/taobao_admin/shop?action=queryshop&shopName`)
    .then((resp) => {
    
    
      this.shopes = resp.data
      this.goods.shopId = this.shopes[0].shopId
    })
  },
}
</script>

<style scoped>
.err{
    
    
  color: red;
}
</style>

Please add a picture description

delete shoes

delgoods method

delete shoe backend

dao package code:

    // 删除指定鞋子信息       按照主键删除
    public int DeleteGoodsId(int goodsId) {
    
    
        int result = 0; 
        Connection connection = null; 
        PreparedStatement statement = null; 
        connection = JdbcUtil.createConnection(); 
        try {
    
    
            statement = connection.prepareStatement("delete from goods where goodsId=?"); 
            statement.setInt(1, goodsId); 
            result = statement.executeUpdate(); 
        } catch (SQLException e) {
    
    
            e.printStackTrace();
        } finally {
    
    
            JdbcUtil.close(statement, connection); 
        }
        return result; 
    }

service package:

    public String remove(int goodsId) {
    
    
        return dao.DeleteGoodsId(goodsId) > 0 ? "鞋子删除成功" : "鞋子删除失败";
    }

controller package:

          else if (action.equals("delgoods")) {
    
    
            String goodsId = req.getParameter("goodsId");
            String result = service.remove(Integer.parseInt(goodsId));

            writer.print(result);
        }

Delete the front of the shoe

Add the delgoods method under the query view (this method has been defined when writing the query)

    delgoods(i) {
    
    
      axios.post('http://localhost:8888/taobao_admin/goods', qs.stringify({
    
    
        action: 'delgoods',
        goodsId: this.goodses[i].goodsId
      }))
        .then((resp) => {
    
    
          alert(resp.data)
          this.querynames()
        })
    }

insert image description here

modify shoes

Modify with session method

Modify the shoe backend

dao package code:

    // 修改鞋子信息
    public int UpdateGoods(Goods goods) {
    
     
        int result = 0; 
        Connection connection = null; 
        PreparedStatement statement = null; 
        connection = JdbcUtil.createConnection(); 
        try {
    
    
            statement = connection.prepareStatement("update goods set goodsName=?,goodsExplain=?,goodsPrice=?,shopId=? where goodsId=?"); 
            // 给? 赋值
            statement.setString(1,goods.getGoodsName()); 
            statement.setString(2,goods.getGoodsExplain()); 
            statement.setDouble(3,goods.getGoodsPrice()); 
            statement.setInt(4,goods.getShopId()); 
            statement.setInt(5,goods.getGoodsId());
            result = statement.executeUpdate(); 
        } catch (SQLException e) {
    
    
            // TODO 自动生成的 catch 块
            e.printStackTrace();
        } finally {
    
    
            JdbcUtil.close(statement, connection); 
        }
        return result; 
    }

service package code:

    public String update(Goods goods) {
    
    
        return dao.UpdateGoods(goods) > 0 ? "鞋子修改成功" : "鞋子修改失败";
    }

Controller package code:

        } else if (action.equals("updategoods")) {
    
    
            String goodsId = req.getParameter("goodsId");
            String goodsName = req.getParameter("goodsName");
            String goodsExplain = req.getParameter("goodsExplain");
            String goodsPrice = req.getParameter("goodsPrice");
            String shopId = req.getParameter("shopId");
            Goods goods = new Goods();
            goods.setGoodsId(Integer.parseInt(goodsId));
            goods.setGoodsName(goodsName);
            goods.setGoodsExplain(goodsExplain);
            goods.setGoodsPrice(Double.parseDouble(goodsPrice));
            goods.setShopId(Integer.parseInt(shopId));
            String result = service.update(goods);
            writer.print(result);
        }

Modify the front of the shoe

gotoSessionAdd the method to the query page

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

New view: GoodsUpdateSessionView

Configure routing in index.js file

      {
    
    
        path: '/session',
        name: 'session',
        component: () => import('@/views/goods/GoodsUpdateSessionView')
      }

Modify view page:

<template>
  <div>
    鞋子编号:<input type="text" readonly v-model="goods.goodsId"> <br>
    菜品名称:<input type="text" v-model="goods.goodsName"> <br>
    菜品描述:<input type="text" v-model="goods.goodsExplain"> <br>
    菜品价格:<input type="text" v-model="goods.goodsPrice"> <br>
    所属商家编号:<input type="text" readonly v-model="goods.shopId"> <br>
    <button @click="updategoods">修改</button>
  </div>
</template>

<script>
import axios from 'axios'
import qs from 'qs'
export default {
    
    
  data() {
    
    
    return {
    
    
      goods: {
    
    

      }
    }
  },
  methods: {
    
    
    // 发请求,1.导入  2.处理响应 .then   resp:响应信息
    // action与后端对应  controller
    updategoods() {
    
    
      this.goods['action'] = 'updategoods'
      axios.post('http://localhost:8888/taobao_admin/goods', qs.stringify(this.goods))
        .then((resp) => {
    
    
          alert(resp.data)
        })
    }
  },
  components: {
    
    },
  computed: {
    
    },
  watch: {
    
    },
  mounted() {
    
    
    let goods = sessionStorage.getItem('goods')
    goods = JSON.parse(goods)
    this.goods = goods
  }
}
</script>
<style scoped></style>

insert image description here


Next you can change the style

Guess you like

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