项目实战:添加新库存记录

1、在index.html添加超链接,添加新库存add.html




    
    Title
    
    
    
    


  

欢迎使用水果库存系统

名称 单价 库存 操作

2、编写add.html添加点击事件负责提交onclick




    
    Title
    
    
    
    


添加水果库存信息

名称:  
单价:
库存:
备注:

3、编写add.js

3.1、common.js

function $(key){
    if(key){
        if(key.startsWith("#")){
            key = key.substring(1)
            return document.getElementById(key)
        }else{
            let nodeList = document.getElementsByName(key)
            return Array.from(nodeList)
        }
    }
}
function add(){
    let fname = $("#fname").value
    let price = $("#price").value
    let fcount = $("#fcount").value
    let remark = $("#remark").value

    //let fruit = {"fname":fname,"price":price,"fcount":fcount,"remark":remark}
    let fruit = {}
    fruit.fname=fname
    fruit.price = price
    fruit.fcount=fcount
    fruit.remark=remark

    axios({
        method:'post',
        url:'add',
        data:fruit
    }).then(response=>{
        if(response.data.flag){
            window.location.href='index.html'
        }
    })
}

/*
function checkFname(fname){
    axios({
        method:'get',
        url:"getFname",
        params:{
            fname:fname
        }
    }).then(response=>{
        let fnameSpan= $("#fnameSpan");
        if(response.data.flag){
            fnameSpan.innerText = '名称可添加'
            fnameSpan.style.color='green'
        }else{
            fnameSpan.innerText = '名称已存在'
            fnameSpan.style.color='red'
        }
    })
}*/

4、编写Controller层AddServlet

package com.csdn.fruit.servlet;
import com.csdn.fruit.dao.FruitDao;
import com.csdn.fruit.dao.impl.FruitDaoImpl;
import com.csdn.fruit.dto.Result;
import com.csdn.fruit.pojo.Fruit;
import com.csdn.fruit.util.RequestUtil;
import com.csdn.fruit.util.ResponseUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/add")
public class AddServlet extends HttpServlet {
    private FruitDao fruitDao = new FruitDaoImpl();
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Fruit fruit = (Fruit) RequestUtil.readObject(req, Fruit.class);
        fruitDao.addFruit(fruit);
        ResponseUtil.print(resp, Result.OK());
    }
}

项目实战:添加新库存记录_第1张图片

你可能感兴趣的:(#,Tomcat-Servlet,javascript,axios,Servlet,WebServlet,onclick)