项目实战:优化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'
        }
    })
}
相关推荐
JerryXZR9 分钟前
前端开发中ES6的技术细节二
前端·javascript·es6
problc24 分钟前
Flutter中文字体设置指南:打造个性化的应用体验
android·javascript·flutter
Gavin_91528 分钟前
【JavaScript】模块化开发
前端·javascript·vue.js
懒大王爱吃狼2 小时前
Python教程:python枚举类定义和使用
开发语言·前端·javascript·python·python基础·python编程·python书籍
待磨的钝刨3 小时前
【格式化查看JSON文件】coco的json文件内容都在一行如何按照json格式查看
开发语言·javascript·json
前端青山8 小时前
Node.js-增强 API 安全性和性能优化
开发语言·前端·javascript·性能优化·前端框架·node.js
从兄9 小时前
vue 使用docx-preview 预览替换文档内的特定变量
javascript·vue.js·ecmascript
清灵xmf10 小时前
在 Vue 中实现与优化轮询技术
前端·javascript·vue·轮询
薛一半11 小时前
PC端查看历史消息,鼠标向上滚动加载数据时页面停留在上次查看的位置
前端·javascript·vue.js
过期的H2O211 小时前
【H2O2|全栈】JS进阶知识(四)Ajax
开发语言·javascript·ajax