Project actual combat: Central controller implementation (4) – implement the function of RequestBody annotation – obtain request body parameters

1. DispatcherServlet

package com.csdn.mymvc.core;
import com.csdn.fruit.dto.Result;
import com.csdn.fruit.util.RequestUtil;
import com.csdn.fruit.util.ResponseUtil;
import com.csdn.mymvc.annotation.RequestBody;
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.lang.reflect.Parameter;
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 + "Illegal!");
            }
            //[, 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 + "The corresponding controller component does not exist!");
            }
            //Get the request method, such as get or post
            String requestMethodStr = req.getMethod().toLowerCase();
            //get_/index
            Method method = controllerDefinition.getMethodMappingMap().get(requestMethodStr + "_" + methodMapping);
            Object controllerBean = controllerDefinition.getControllerBean();

            try {
                //Step 1: Parameter processing
                //Get the parameters on the method method
                Parameter[] parameters = method.getParameters();
                Object[] parameterValues = new Object[parameters.length];
                for (int i = 0; i < parameters.length; i + + ) {
                    Parameter parameter = parameters[i];

                    RequestBody requestBodyAnnotation = parameter.getDeclaredAnnotation(RequestBody.class);
                    Object parameterValue = null;
                    if (requestBodyAnnotation != null) {
                        parameterValue = RequestUtil.readObject(req, parameter.getType());
                    } else {
                        //Get parameter name
                        //Before JDK8, the parameter object (Parameter object) was obtained through reflection
                        //Then the name of the formal parameter cannot be obtained through the parameter.getName() method. What is returned is arg0, arg1, arg2....
                        //Starting from JDK8, the Class obtained by reflection technology can contain the names of method parameters, but an additional setting is required:
                        //Add a parameter to the java compiler: -parameters
                        String paramName = parameter.getName();
                        String paramValueStr = req.getParameter(paramName);
                        if (paramValueStr != null) {
                            //Get the type of parameter
                            String parameterTypeName = parameter.getType().getName();
                            parameterValue = switch (parameterTypeName) {
                                case "java.lang.String"-> paramValueStr;
                                case "java.lang.Integer"-> Integer.parseInt(paramValueStr);
                                default -> null;
                            };
                        }
                    }
                    parameterValues[i] = parameterValue;
                }
                //Step 2: Method call
                //Call the method method in the controllerBean object
                method.setAccessible(true);
                Object returnObj = method.invoke(controllerBean, parameterValues);
                if (returnObj != null & amp; & amp; 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);
            }

        }
    }
}

2. FruitController

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 is the request parameter
        Fruit fruit = fruitService.getFruitByFname(fname);
         return fruit == null ? Result.OK() : Result.Fail();
    }

    @PostMapping("/update")
    public Result update(@RequestBody Fruit fruit){ //fruit is the request body parameter
        fruitService.updateFruit(fruit);
        return Result.OK();
    }
}

The knowledge points of the article match the official knowledge files, and you can further learn related knowledge. Java Skill TreeHomepageOverview 139,294 people are learning the system