项目实战:优化Servlet,把所有围绕Fruit操作的Servlet封装成一个Servlet

1、FruitServlet

  • 这些Servlet都是围绕着Fruit进行的
  • 把所有对水果增删改查的Servlet放到一个Servlet里面,让tomcat实例化一个Servlet对象
package com.csdn.fruit.servlet;
import com.csdn.fruit.dto.PageInfo;
import com.csdn.fruit.dto.PageQueryParam;
import com.csdn.fruit.dto.Result;
import com.csdn.fruit.pojo.Fruit;
import com.csdn.fruit.service.FruitService;
import com.csdn.fruit.service.impl.FruitServiceImpl;
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("/fruit/*")
public class FruitServlet extends HttpServlet {
    private FruitService fruitService = new FruitServiceImpl();
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //     /fruit/index
        String uri = req.getRequestURI();
        uri = uri.substring(1);
        String[] split = uri.split("/");
        String methodName = split[1];
        switch (methodName) {
            case "index" ->index(req,resp);
            case "add"-> add(req, resp);
            case "del"->del(req,resp);
            case "edit"->edit(req,resp);
            case "getFname"-> getFname(req, resp);
            case "update"  -> update(req, resp);
        }
    }

    protected void index(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Integer pageNo = 1;
        String pageNoStr = req.getParameter("pageNo");
        if (pageNoStr != null && !"".equals(pageNoStr)) {
            pageNo = Integer.parseInt(pageNoStr);
        }

        String keyword = "";
        String keywordStr = req.getParameter("keyword");
        if (keywordStr != null) {
            keyword = keywordStr;
        }
        PageQueryParam pageQueryParam = new PageQueryParam(pageNo, 5, keyword);
        PageInfo pageInfo = fruitService.getFruitPageInfo(pageQueryParam);

        Result result = Result.OK(pageInfo);

        ResponseUtil.print(resp, result);
    }

    protected void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Fruit fruit = (Fruit) RequestUtil.readObject(req, Fruit.class);
        fruitService.addFruit(fruit);
        ResponseUtil.print(resp, Result.OK());
    }

    protected void del(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Integer fid = Integer.parseInt(req.getParameter("fid"));
        fruitService.delFruit(fid);
        ResponseUtil.print(resp, Result.OK());
    }

    protected void edit(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Integer fid = Integer.parseInt(req.getParameter("fid"));
        Fruit fruit = fruitService.getFruitById(fid);
        ResponseUtil.print(resp, Result.OK(fruit));
    }

    public void getFname(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String fname = req.getParameter("fname");
        Fruit fruit = fruitService.getFruitByFname(fname);
        ResponseUtil.print(resp, fruit == null ? Result.OK() : Result.Fail());
    }

    protected void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Fruit fruit = (Fruit) RequestUtil.readObject(req, Fruit.class);
        fruitService.updateFruit(fruit);
        ResponseUtil.print(resp, Result.OK());
    }
}

 2、修改js中axios中的url路径

 2.2、公共的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)
        }
    }
}

2.2.1、index.js

let pageNo = 1;
let pageCount = 0;
let keyword=""

//当页面加载完成,执行匿名函数
window.onload=function(){
    loadData();
}
function search() {
    keyword=$("#keyword").value
    loadData(pageNo)
}

function page(str) {
    if (str) {
        if (str == "first") {
            pageNo = 1;
        }else if (str == "pre") {
            pageNo = pageNo - 1;
        }else if (str == "next") {
            pageNo = pageNo + 1;
        }else if (str == "last") {
            pageNo = pageCount;
        }
        if (pageNo > pageCount) {
            pageNo=pageCount
        }
        if (pageNo <= 0) {
            pageNo=1
        }
    }
    loadData(pageNo)
}
loadData=function(pageNo=1){//pageNo这个参数有默认值,如果没有传值,则使用默认值 1
    axios({
        method: 'get',
        url: '/fruit/index',
        params: {
            pageNo: pageNo,
            keyword:keyword
        }
    }).then(response => {
        debugger
        let fruitList = response.data.data.list
        pageNo = response.data.data.pageNo
        pageCount = response.data.data.pageCount
        // 此处使用的是axios,那么响应回来的数据自动就是json,
        // 不需要再进行parse(如果是原始的ajax操作,那么一定需要parse)
        // let fruitArr = JSON.parse(fruitList)
        let fruitArr = fruitList;
        let fruitTbl = $("#fruit_tbl")
        //向表格中添加行之前,先删除原来的行
        let rows=fruitTbl.rows
        for (let i = rows.length - 1; i >= 1; i--) {
            fruitTbl.deleteRow(i);
        }

        for (let i = 0; i < fruitArr.length; i++) {
            let tr = fruitTbl.insertRow();
            let fnameTD = tr.insertCell();
            let priceTD = tr.insertCell();
            let fcountTD = tr.insertCell();
            let operTD = tr.insertCell();

            let fruit = fruitArr[i];
            //fnameTD.innerText = fruit.fname
            fnameTD.innerHTML = '' + fruit.fname + '';
            priceTD.innerText = fruit.price;
            fcountTD.innerText = fruit.fcount;
            operTD.innerHTML = "";
        }
    });
}

delFruit = function (fid) {
    if (window.confirm('是否确认删除?')) {
        axios({
            method: 'get',
            url: '/fruit/del',
            params:{
                fid: fid,
            }
        }).then(response=>{
            if (response.data.flag) {
                window.location.reload();
            }
        });
    }
};

2.2.2、edit.js

let queryString = window.location.search.substring(1)
if(queryString){
    var fid = queryString.split("=")[1]

    window.onload=function(){
        loadFruit(fid)
    }

    loadFruit = function(fid){
        axios({
            method:'get',
            url:'/fruit/edit',
            params:{
                fid:fid
            }
        }).then(response=>{
            debugger
            let fruit = response.data.data
            $("#fid").value=fruit.fid
            $("#fname").value=fruit.fname
            $("#price").value=fruit.price
            $("#fcount").value=fruit.fcount
            $("#remark").value=fruit.remark
        })
    }

    update=function(){
        let fid = $("#fid").value
        let fname = $("#fname").value
        let price = $("#price").value
        let fcount = $("#fcount").value
        let remark = $("#remark").value
        axios({
            method:'post',
            url:"/fruit/update",
            data:{
                fid:fid,
                fname:fname,
                price:price,
                fcount:fcount,
                remark:remark
            }
        }).then(response=>{
            if(response.data.flag){
                window.location.href="index.html"
            }
        })
    }
}

2.2.3、add.js

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:'/fruit/add',
        data:fruit
    }).then(response=>{
        if(response.data.flag){
            window.location.href='index.html'
        }
    })
}

function checkFname(fname){
    axios({
        method:'get',
        url:"/fruit/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'
        }
    })
}

项目实战:优化Servlet,把所有围绕Fruit操作的Servlet封装成一个Servlet_第1张图片 

你可能感兴趣的:(#,IOC_MVC,javascript,WebServlet,axios,getRequestURI,substring,split,switchcase)