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

1、FruitServlet

  • 这些Servlet都是围绕着Fruit进行的
  • 把所有对水果增删改查的Servlet放到一个Servlet里面,让tomcat实例化一个Servlet对象
java 复制代码
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<Fruit> 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

javascript 复制代码
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

javascript 复制代码
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 = '<a href="edit.html?fid=' + fruit.fid + '">' + fruit.fname + '</a>';
            priceTD.innerText = fruit.price;
            fcountTD.innerText = fruit.fcount;
            operTD.innerHTML = "<img class=\"delImg\" src=\"imgs/del.png\" onclick=\"delFruit(" + fruit.fid + ")\"/>";
        }
    });
}

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

javascript 复制代码
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

javascript 复制代码
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'
        }
    })
}
相关推荐
高山我梦口香糖37 分钟前
[react]searchParams转普通对象
开发语言·前端·javascript
black^sugar2 小时前
纯前端实现更新检测
开发语言·前端·javascript
2401_857600953 小时前
SSM 与 Vue 共筑电脑测评系统:精准洞察电脑世界
前端·javascript·vue.js
2401_857600953 小时前
数字时代的医疗挂号变革:SSM+Vue 系统设计与实现之道
前端·javascript·vue.js
GDAL3 小时前
vue入门教程:组件透传 Attributes
前端·javascript·vue.js
小白学大数据3 小时前
如何使用Selenium处理JavaScript动态加载的内容?
大数据·javascript·爬虫·selenium·测试工具
2402_857583493 小时前
基于 SSM 框架的 Vue 电脑测评系统:照亮电脑品质之路
前端·javascript·vue.js
java_heartLake4 小时前
Vue3之性能优化
javascript·vue.js·性能优化
Swift社区4 小时前
HarmonyOS 实践 - 设计模式在代码中的作用
javascript
少年姜太公4 小时前
从零开始详解js中的this(下)
前端·javascript·程序员