栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

SpringMVC执行流程

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SpringMVC执行流程

Spring MVC 请求处理流程


流程说明:

第⼀步:⽤户发送请求⾄前端控制器DispatcherServlet第⼆步:DispatcherServlet收到请求调⽤HandlerMapping处理器映射器第三步:处理器映射器根据请求Url找到具体的Handler(后端控制器),⽣成处理器对象及处理器拦截器(如果 有则⽣成)⼀并返回DispatcherServlet第四步:DispatcherServlet调⽤HandlerAdapter处理器适配器去调⽤Handler第五步:处理器适配器执⾏Handler第六步:Handler执⾏完成给处理器适配器返回ModelAndView第七步:处理器适配器向前端控制器返回 ModelAndView,ModelAndView 是SpringMVC 框架的⼀个底层对 象,包括 Model 和 View第⼋步:前端控制器请求视图解析器去进⾏视图解析,根据逻辑视图名来解析真正的视图。第九步:视图解析器向前端控制器返回View第⼗步:前端控制器进⾏视图渲染,就是将模型数据(在 ModelAndView 对象中)填充到 request - 域第⼗⼀步:前端控制器向⽤户响应结果

⼿写 MVC 框架


手写MVC框架之注解开发:

LagouAutowired

import java.lang.annotation.*;

@documented
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface LagouAutowired {
    String value() default "";
}

LagouController

import java.lang.annotation.*;

@documented
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface LagouController {
    String value() default "";
}

LagouService

import java.lang.annotation.*;

@documented
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface LagouService {
    String value() default "";
}

LagouRequestMapping

import java.lang.annotation.*;

@documented
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface LagouRequestMapping {
    String value() default "";
}

Pojo类Handler

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;


public class Handler {
    private Object controller; // method.invoke(obj,)
    private Method method;
    private Pattern pattern; // spring中url是⽀持正则的
    private Map paramIndexMapping; // 参数顺序,是为了进⾏参数绑定,key是参数名,value代表是第⼏个参数 

    public Handler(Object controller, Method method, Pattern pattern) {
        this.controller = controller;
        this.method = method;
        this.pattern = pattern;
        this.paramIndexMapping = new HashMap<>();
    }

    public Object getController() {
        return controller;
    }

    public void setController(Object controller) {
        this.controller = controller;
    }

    public Method getMethod() {
        return method;
    }

    public void setMethod(Method method) {
        this.method = method;
    }

    public Pattern getPattern() {
        return pattern;
    }

    public void setPattern(Pattern pattern) {
        this.pattern = pattern;
    }

    public Map getParamIndexMapping() {
        return paramIndexMapping;
    }

    public void setParamIndexMapping(Map paramIndexMapping) {
        this.paramIndexMapping = paramIndexMapping;
    }
}

web.xml




  Archetype Created Web Application


  
    lgoumvc
    com.lagou.edu.mvcframework.servlet.LgDispatcherServlet
    
      contextConfigLocation
      springmvc.properties
    
  
  
  
    lgoumvc
    
    @Override
    public void init(ServletConfig config) throws ServletException {
        // 1. 加载配置⽂件 springmvc.properties
        String contextConfigLocation = config.getInitParameter("contextConfigLocation");
        doLoadConfig(contextConfigLocation);
        // 2. 扫描相关的类,扫描注解
        doScan(properties.getProperty("scanPackage"));
        // 3. 初始化bean对象(实现ioc容器,基于注解)
        doInstance();
        // 4. 实现依赖注⼊ ->属性赋值
        doAutoWired();
        // 5. 构造⼀个HandlerMapping处理器映射器,将配置好的url和Method建⽴映射关系
        initHandlerMapping();


        System.out.println("lagou mvc 初始化完成....");
        // 等待请求进⼊,处理请求
    }

    
    private void initHandlerMapping() {
        if (ioc.isEmpty()) {
            return;
        }
        for (Map.Entry entry : ioc.entrySet()) {
            // 获取ioc中当前遍历的对象的class类型
            Class aClass = entry.getValue().getClass();
            // 只处理controller层,不处理service层
            if (!aClass.isAnnotationPresent(LagouController.class)) {
                continue;
            }
            String baseUrl = "";
            if (aClass.isAnnotationPresent(LagouRequestMapping.class)) {
                LagouRequestMapping annotation = aClass.getAnnotation(LagouRequestMapping.class);
                baseUrl = annotation.value(); // 等同于  /demo
            }
            // 获取⽅法
            Method[] methods = aClass.getMethods();
            for (int i = 0; i < methods.length; i++) {
                Method method = methods[i]; // ⽅法没有标识LagouRequestMapping,就不处理
                if (!method.isAnnotationPresent(LagouRequestMapping.class)) {
                    continue;
                }
                // 如果标识,就处理
                LagouRequestMapping annotation = method.getAnnotation(LagouRequestMapping.class);
                String methodUrl = annotation.value(); // /query
                String url = baseUrl + methodUrl; // 计算出来的url /demo/query

                // 把method所有信息及url封装为⼀个Handler
                Handler handler = new Handler(entry.getValue(),method, Pattern.compile(url));
                // 计算⽅法的参数位置信息
                // query(HttpServletRequest request, HttpServletResponse response,String name)
                Parameter[] parameters = method.getParameters();
                for (int j = 0; j < parameters.length; j++) {
                    Parameter parameter = parameters[j];
                    if(parameter.getType() == HttpServletRequest.class || parameter.getType() == HttpServletResponse.class) {
                        // 如果是request和response对象,那么参数名称写HttpServletRequest和HttpServletResponse
                        handler.getParamIndexMapping().put(parameter.getType().getSimpleName(), j);
                    } else {
                        handler.getParamIndexMapping().put(parameter.getName(), j); // 
                    }
                }
                // 建⽴url和method之间的映射关系(map缓存起来)
                handlerMapping.add(handler);
            }
        }
    }

    
    private void doAutoWired() {
        if (ioc.isEmpty()) {
            return;
        }
        // 有对象,再进⾏依赖注⼊处理
        // 遍历ioc中所有对象,查看对象中的字段,是否有@LagouAutowired注解,如果有需要维护依赖注⼊关系
        for(Map.Entry entry: ioc.entrySet()) {
            // 获取bean对象中的字段信息
            Field[] declaredFields = entry.getValue().getClass().getDeclaredFields();
            // 遍历判断处理
            for (int i = 0; i < declaredFields.length; i++) {
                Field declaredField = declaredFields[i];
                // @LagouAutowired private IDemoService demoService;
                if (!declaredField.isAnnotationPresent(LagouAutowired.class)) {
                    continue;
                }
                // 有该注解
                LagouAutowired annotation = declaredField.getAnnotation(LagouAutowired.class);
                String beanName = annotation.value();
                // 需要注⼊的bean的id
                if("".equals(beanName.trim())) {
                    // 没有配置具体的bean id,那就需要根据当前字段类型注⼊(接⼝注⼊)IDemoService
                    beanName = declaredField.getType().getName();
                }
                // 开启赋值
                declaredField.setAccessible(true);
                try {
                    declaredField.set(entry.getValue(), ioc.get(beanName));
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    
    private void doInstance() {
        if (classNames.size() == 0) return;
        try {
            for (int i = 0; i < classNames.size(); i++) {
                String className = classNames.get(i); // com.lagou.demo.controller.DemoController
                // 反射
                Class aClass = Class.forName(className);
                // 区分controller,区分service
                if(aClass.isAnnotationPresent(LagouController.class)) {
                    // controller的id此处不做过多处理,不取value了,就拿类的⾸字⺟⼩写作为id,保存到ioc中
                    String simpleName = aClass.getSimpleName();// DemoController
                    String lowerFirstSimpleName = lowerFirst(simpleName); // demoController
                    Object o = aClass.newInstance();
                    ioc.put(lowerFirstSimpleName, o);
                } else if (aClass.isAnnotationPresent(LagouService.class)) {
                    LagouService annotation = aClass.getAnnotation(LagouService.class);
                    //获取注解value值
                    String beanName = annotation.value();
                    // 如果指定了id,就以指定的为准
                    if(!"".equals(beanName.trim())) {
                        ioc.put(beanName, aClass.newInstance());
                    } else {
                        // 如果没有指定,就以类名⾸字⺟⼩写
                        beanName = lowerFirst(aClass.getSimpleName());
                        ioc.put(beanName, aClass.newInstance());
                    }
                    // service层往往是有接⼝的,⾯向接⼝开发,此时再以接⼝名为id,放⼊⼀份对象到ioc中,便于后期根据接⼝类型注⼊
                    Class[] interfaces = aClass.getInterfaces();
                    for (int j = 0; j < interfaces.length; j++) {
                        Class anInterface = interfaces[j];
                        // 以接⼝的全限定类名作为id放⼊
                        ioc.put(anInterface.getName(), aClass.newInstance());
                    }
                } else {
                    continue;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    
    public String lowerFirst(String str) {
        char[] chars = str.toCharArray();
        if ('A' <= chars[0] && chars[0] <= 'Z') {
            chars[0] += 32;
        }
        return String.valueOf(chars);
    }

    
    private void doScan(String scanPackage) {
        String scanPackagePath = Thread.currentThread().getContextClassLoader().getResource("").getPath() + scanPackage.replaceAll("\.", "/");
        File pack = new File(scanPackagePath);
        File[] files = pack.listFiles();
        for (File file : files) {
            if (file.isDirectory()) {
                // ⼦package
                // 递归
                doScan(scanPackage + "." + file.getName()); // com.lagou.demo.controller
            } else if (file.getName().endsWith(".class")) {
                String className = scanPackage + "." + file.getName().replaceAll(".class", "");
                classNames.add(className);
            }
        }
    }

    
    private void doLoadConfig(String contextConfigLocation) {
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream(contextConfigLocation);
        try {
            properties.load(resourceAsStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 处理请求:根据url,找到对应的Method⽅法,进⾏调⽤
        // 获取uri
        //String requestURI = req.getRequestURI();
        //Method method = handlerMapping.get(requestURI);
        // 获取到⼀个反射的⽅法
        // 反射调⽤,需要传⼊对象,需要传⼊参数,此处无法完成调⽤,没有把对象缓存起来,也没有参数!!!!改造initHandlerMapping();
        // method.invoke()
        // 根据uri获取到能够处理当前请求的hanlder(从handlermapping中(list))


        Handler handler = getHandler(req);
        if (handler == null) {
            resp.getWriter().write("404 not found");
            return;
        }
        // 参数绑定
        // 获取所有参数类型数组,这个数组的⻓度就是我们最后要传⼊的args数组的⻓度
        Class[] parameterTypes = handler.getMethod().getParameterTypes();
        // 根据上述数组⻓度创建⼀个新的数组(参数数组,是要传⼊反射调⽤的)
        Object[] paraValues = new Object[parameterTypes.length];
        // 以下就是为了向参数数组中塞值,⽽且还得保证参数的顺序和⽅法中形参顺序⼀致
        Map parameterMap = req.getParameterMap();

        // 遍历request中所有参数 (填充除了request,response之外的参数)
        for(Map.Entry param: parameterMap.entrySet()) {
            // name=1&name=2 name [1,2]
            String value = StringUtils.join(param.getValue(), ","); // 如同 1,2
            // 如果参数和⽅法中的参数匹配上了,填充数据
            if (!handler.getParamIndexMapping().containsKey(param.getKey())) {
                continue;
            }
            // ⽅法形参确实有该参数,找到它的索引位置,对应的把参数值放⼊paraValues
            Integer index = handler.getParamIndexMapping().get(param.getKey());
            //name在第 2 个位置
            paraValues[index] = value;
            // 把前台传递过来的参数值填充到对应的位置去
        }
        //request,response对象直接取出就可以
        int requestIndex = handler.getParamIndexMapping().get(HttpServletRequest.class.getSimpleName());// 0
        paraValues[requestIndex] = req;
        int responseIndex = handler.getParamIndexMapping().get(HttpServletResponse.class.getSimpleName());// 1
        paraValues[responseIndex] = resp;

        // 最终调⽤handler的method属性
        try {
            // Pojo类Handler
            handler.getMethod().invoke(handler.getController(), paraValues);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    
    private Handler getHandler(HttpServletRequest req) {
        if (handlerMapping.isEmpty()) {
            return null;
        }
        String url = req.getRequestURI();
        for (Handler handler : handlerMapping) {
            Matcher matcher = handler.getPattern().matcher(url);
            if (!matcher.matches()) {
                continue;
            }
            return handler;
        }
        return null;
    }

}

Spring MVC请求参数绑定

默认⽀持 Servlet API 作为⽅法参数

绑定简单类型参数
简单数据类型:⼋种基本数据类型及其包装类型
参数类型推荐使⽤包装数据类型,因为基础数据类型不可以为null
整型:Integer、int
字符串:String
单精度:Float、float
双精度:Double、double
布尔型:Boolean、boolean
说明:对于布尔类型的参数,请求的参数值为true或false。或者1或0

@RequestMapping("/handle03")
public ModelAndView handle03(@RequestParam("ids") Integer id,Boolean flag) {

    Date date = new Date();
    ModelAndView modelAndView = new ModelAndView();
    modelAndView.addObject("date",date);
    modelAndView.setViewName("success");
    return modelAndView;
}

绑定Pojo包装对象参数

@RequestMapping("/handle04")
public ModelAndView handle04(User user) {

    Date date = new Date();
    ModelAndView modelAndView = new ModelAndView();
    modelAndView.addObject("date",date);
    modelAndView.setViewName("success");
    return modelAndView;
}

绑定日期类型参数(需要配置自定义类型转换器)

1.DateConverter.java:

import org.springframework.core.convert.converter.Converter;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;


public class DateConverter implements Converter {
    @Override
    public Date convert(String source) {
        // 完成字符串向日期的转换
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");

        try {
            Date parse = simpleDateFormat.parse(source);
            return parse;
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return null;
    }
}

2.springmvc.xml中:


    
        
            
        
    

3.controller类中的方法使用:

@RequestMapping("/handle06")
public ModelAndView handle06(Date birthday) {
   Date date = new Date();ModelAndView modelAndView = new ModelAndView();
   modelAndView.addObject("date",date);
   modelAndView.setViewName("success");
   return modelAndView;
}

Restful 风格请求

 
@RequestMapping(value = "/handle/{id}/{name}",method = {RequestMethod.GET})
public ModelAndView handlePut(@PathVariable("id") Integer id,@PathVariable("name") String username) {

    Date date = new Date();
    ModelAndView modelAndView = new ModelAndView();
    modelAndView.addObject("date",date);
    modelAndView.setViewName("success");
    return modelAndView;
}

Ajax Json交互

1)前端到后台:前端ajax发送json格式字符串,后台直接接收为pojo参数,使⽤注解@RequstBody
2)后台到前端:后台直接返回pojo对象,前端直接接收为json对象或者字符串,使⽤注解@ResponseBody

@RequestMapping("/handle07")
// 添加@ResponseBody之后,不再走视图解析器那个流程,而是等同于response直接输出数据

public @ResponseBody User handle07(@RequestBody User user) {

    // 业务逻辑处理,修改name为张三丰
    user.setName("张三丰");
    return user;
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/735238.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号