当前位置: 首页 > news >正文

项目实战:中央控制器实现(2)-优化Controller,将共性动作抽取到中央控制器

 1、FruitController

  • FruitController已经和Web没有关系了,和Web容器解耦,可以脱离Web容器做单元测试
package com.csdn.fruit.controller;
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.mymvc.annotation.*;
@Controller
@RequestMapping("/fruit")
public class FruitController {
    @Autowire
    private FruitService fruitService;

    @GetMapping("/index")
    public Result index(Integer pageNo,String keyword) {
        if (pageNo == null) {
            pageNo = 1;
        }
        if (keyword == null) {
            keyword = "";
        }
        PageQueryParam pageQueryParam = new PageQueryParam(pageNo, 5, keyword);
        PageInfo<Fruit> pageInfo = fruitService.getFruitPageInfo(pageQueryParam);

       return Result.OK(pageInfo);

    }

    @PostMapping("/add")
    public Result add(@RequestBody Fruit fruit)  {
        fruitService.addFruit(fruit);
        return Result.OK();
    }

    @GetMapping("/del")
    public Result del(Integer fid){
        fruitService.delFruit(fid);
        return Result.OK();
    }

    @GetMapping("/edit")
    public Result edit(Integer fid){
        Fruit fruit = fruitService.getFruitById(fid);
        return Result.OK(fruit);
    }

    @GetMapping("/getFname")
    public Result getFname(String fname){ //fname是请求参数
        Fruit fruit = fruitService.getFruitByFname(fname);
         return fruit == null ? Result.OK() : Result.Fail();
    }

    @PostMapping("/update")
    public Result update(@RequestBody Fruit fruit){ //fruit是请求体参数
        fruitService.updateFruit(fruit);
        return Result.OK();
    }
}

2、DispatcherServlet

package com.csdn.mymvc.core;
import com.csdn.fruit.dto.Result;
import com.csdn.fruit.util.ResponseUtil;
import jakarta.servlet.RequestDispatcher;
import jakarta.servlet.ServletContext;
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 org.junit.Test;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Map;
@WebServlet("/*")
public class DispatcherServlet extends HttpServlet {

    private final String BEAN_FACTORY = "beanFactory";
    private final String CONTROLLER_BEAN_MAP = "controllerBeanMap";

    @Test
    public void uri() {
        String uri = "/fruit/index";
        String[] arr = uri.split("/");
        System.out.println(Arrays.toString(arr));//[, fruit, index]
    }
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String[] staticResourceSuffixes = {".html", ".jsp", ".jpg", ".png", ".gif", ".css", ".js", ".ico"};
        String uri = req.getRequestURI();
        if (Arrays.stream(staticResourceSuffixes).anyMatch(uri::endsWith)) {
            RequestDispatcher defaultDispatcher = req.getServletContext().getNamedDispatcher("default");
            defaultDispatcher.forward(req, resp);
        } else {
            String[] arr = uri.split("/");
            if (arr == null || arr.length != 3) {
                throw new RuntimeException(uri + "非法!");
            }
            //[, fruit, index]
            String requestMapping = "/" + arr[1];
            String methodMapping = "/" + arr[2];

            ServletContext application = getServletContext();
            ControllerDefinition controllerDefinition = ((Map<String, ControllerDefinition>) application.getAttribute(CONTROLLER_BEAN_MAP))
                    .get(requestMapping);

            if (controllerDefinition == null) {
                throw new RuntimeException(requestMapping + "对应的controller组件不存在!");
            }
            //获取请求方式,例如:get或者post
            String requestMethodStr = req.getMethod().toLowerCase();
            //get_/index
            Method method = controllerDefinition.getMethodMappingMap().get(requestMethodStr + "_" + methodMapping);
            Object controllerBean = controllerDefinition.getControllerBean();

            try {
                //第 1 步:参数处理

                //第 2 步:方法调用

                //调用controllerBean对象中的method方法
                method.setAccessible(true);
                Object returnObj = method.invoke(controllerBean, req, resp);
                if (returnObj != null && returnObj instanceof Result) {
                    Result result= (Result) returnObj;
                    ResponseUtil.print(resp,result);
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            } catch (InvocationTargetException e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }

        }
    }
}

相关文章:

  • Redis系列-Redis集群模式【8】
  • Qt 4.8.6 的下载与安装
  • VS2010配置gdal1.10.0 gdal1.10.1编译
  • 【原创】java+swing+mysql爱心捐赠管理系统设计与实现
  • mysql---存储引擎
  • 2、音视频基础
  • 配置OSPF特殊区域
  • 边缘计算多角色智能计量插座:用电监测和资产管理的未来智能化引擎
  • log4j CVE-2021-44228 RCE漏洞复现
  • wpf Grid布局详解 `Auto` 和 `*` 是两种常见的设置方式 行或列占多个单元格,有点像excel里的合并单元格。使其余的列平均分配剩余的空间
  • 嵌入式Linux HID多指触控/触摸设备报表描述符
  • 浅谈余压监控系统在某高层住宅的应用方案
  • 【数据结构】手撕单链表
  • 生态环境领域基于R语言piecewiseSEM结构方程模型
  • ubuntu20.04 安装cudnn
  • SpringBoot上传与下载文件
  • 如何对ppt文件设置修改权限?
  • Django初窥门径-oauth登录认证
  • C++线程库的基本使用(初级)
  • RabbitMQ
  • 瑞幸首度牵手成都国际非遗节,用一杯饮品将非遗之美推向全国
  • 一周人物|收藏家瓦尔特捐出藏品,女性艺术家“对话”摄影
  • 全总联合六部门印发工作指引,共保劳动者合法权益
  • 中科院合肥物质院迎来新一届领导班子:刘建国继续担任院长
  • 蒲慕明院士:好的科普应以“质疑、讨论公众关切的科学问题”为切入点
  • 涉案资金超2亿元 “健康投资”骗局,专挑老年人下手