自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

本篇文章將帶你真正的搞定SpringMVC工作原理

開發(fā) 前端
參數(shù)解析器的作用就是用來(lái)解析通過(guò)請(qǐng)求URI找到對(duì)應(yīng)的處理器方法(PackMethodHandler)。也就是從上面PackHandlerMapping類中保存到Map集合中的通過(guò)請(qǐng)求的URI找到對(duì)應(yīng)的PackMethodHandler對(duì)象。

環(huán)境:Spring5.3.23

1. 簡(jiǎn)介

在Spring中要定義一個(gè)接口是非常的簡(jiǎn)單,如下示例:

@RestController
@RequestMapping("/demos")
public class DemoController {
  @GetMapping("/index")
  public Object index() {
    return "index" ;
  }
}

通過(guò)上面的@RestController, @RequestMapping就完成了一個(gè)簡(jiǎn)單的接口定義。

實(shí)際Spring Web底層是做了很多的工作,其核心組件有HandlerMapping, HandlerAdapter, ViewResolver等組件。

  • HandlerMapping
    根據(jù)當(dāng)前請(qǐng)求的URI,查找對(duì)應(yīng)的Handler,如:HandlerExecutionChain,包裝的HandlerMethod
  • HandlerAdapter
    根據(jù)上面的確定的HandlerMethod, 找到能夠處理該Handler的Adapter,進(jìn)行調(diào)用
  • ViewResolver
    如果返回的ModelAndView對(duì)象那么會(huì)通過(guò)相應(yīng)的ViewResolver進(jìn)行渲染輸出

了解了上面的幾個(gè)核心組件之后,接下來(lái)就是自定義實(shí)現(xiàn)上面的核心類,來(lái)完成接口的請(qǐng)求處理。

2. 實(shí)戰(zhàn)案例

2.1 自定義Endpoint

自定義@PackEndpoint注解,該注解的功能就類似@Controller標(biāo)記這個(gè)類是一個(gè)處理器類。

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface PackEndpoint {}

參數(shù)注解,該注解的作用就類似@RequestParam

@Target(ElementType.PARAMETER)
 @Retention(RetentionPolicy.RUNTIME)
 @Documented
 public @interface PackParam {
 }

2.2 參數(shù)封裝對(duì)象

該類的作用用來(lái)保存方法的參數(shù)相關(guān)的信息進(jìn)行封裝,如:參數(shù)名稱,參數(shù)的類型及對(duì)應(yīng)的方法Method。

public class PackMethodParameter {
  // 用來(lái)解析接口參數(shù)的名稱
  private ParameterNameDiscoverer parameterNameDiscoverer = new LocalVariableTableParameterNameDiscoverer() ;
  private String name ;
  private Executable executable ;
  private int parameterIndex ;
  private Class<?> type ;


  public PackMethodParameter(String name, int parameterIndex, Executable executable) {
    this.name = name;
    this.parameterIndex = parameterIndex ;
    this.executable = executable ;
  }


  public PackMethodParameter(int parameterIndex, Executable executable, Class<?> type) {
    this.parameterIndex = parameterIndex ;
    this.executable = executable ;
    this.type = type ;
  }


  public boolean hasParameterAnnotation(Class<? extends Annotation> clazz) {
    Method method = (Method) this.executable ;
    Parameter[] parameters = method.getParameters() ;
    return parameters[this.parameterIndex].isAnnotationPresent(clazz) ;
  }


  public String getParameterName() {
    String[] parameterNames = parameterNameDiscoverer.getParameterNames((Method) this.executable) ;
    return parameterNames[this.parameterIndex] ;
  }


}

2.3 自定義HandlerMapping

自定義實(shí)現(xiàn)了SpringMVC標(biāo)準(zhǔn)的HandlerMapping,這樣在DispatcherServlet中才能夠識(shí)別。HandlerMapping的作用就是用來(lái)匹配一個(gè)請(qǐng)求的URI與那個(gè)處理器(Controller)進(jìn)行對(duì)應(yīng)。

public class PackHandlerMapping implements HandlerMapping, InitializingBean, ApplicationContextAware {


  private ApplicationContext context;
  private Map<String, PackMethodHandler> mapping = new HashMap<>();


  @Override
  public HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception {
    String requestPath = request.getRequestURI();
    Optional<PackMethodHandler> opt = mapping.entrySet().stream().filter(entry -> entry.getKey().equals(requestPath)).findFirst()
        .map(Map.Entry::getValue);
    if (opt.isPresent()) {
      HandlerExecutionChain executionChain = new HandlerExecutionChain(opt.get()) ;
      return executionChain ;
    }
    return null;
  }


  // Bean初始化時(shí),從容器中查找所有符合條件的Bean對(duì)象,即Bean對(duì)象上有@PackEndpoint注解
  @Override
  public void afterPropertiesSet() throws Exception {
    String[] beanNames = context.getBeanNamesForType(Object.class) ;
    for (String beanName : beanNames) {
      Object bean = this.context.getBean(beanName) ;
      Class<?> clazz = bean.getClass() ;
      // 判斷當(dāng)前的Bean上是否有PackEndpoint注解,只對(duì)有該注解的類進(jìn)行處理
      if (clazz.getAnnotation(PackEndpoint.class) != null) {
        RequestMapping clazzMapping = clazz.getAnnotation(RequestMapping.class) ;
        String rootPath = clazzMapping.value()[0] ;
        if (clazzMapping != null) {
          // 遍歷當(dāng)前類中的所有方法,查找使用了@RequestMapping注解的方法
          ReflectionUtils.doWithMethods(clazz, method -> {
            RequestMapping nestMapping = AnnotatedElementUtils.findMergedAnnotation(method, RequestMapping.class) ;
            if (nestMapping != null) {
              String nestPath = nestMapping.value()[0] ;
              String path = rootPath + nestPath ;
              // 所有信息都封裝到該對(duì)象
              PackMethodHandler handler = new PackMethodHandler(method, bean) ;
              // 將請(qǐng)求的URI及對(duì)應(yīng)的Handler進(jìn)行對(duì)應(yīng),這樣就可以通過(guò)請(qǐng)求的URI找到對(duì)應(yīng)的處理器方法了
              mapping.put(path, handler) ;
            }
          }) ;
        }
      }
    }
  }
  @Override
  public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    this.context = applicationContext;
  }
  // 該類的作用:用來(lái)記錄接口對(duì)應(yīng)的信息,方法,對(duì)應(yīng)的實(shí)例,參數(shù)信息
  public static class PackMethodHandler {
    private Method method;
    private Object instance;
    private PackMethodParameter[] parameters ;
    public Method getMethod() {
      return method;
    }
    public void setMethod(Method method) {
      this.method = method;
    }
    public Object getInstance() {
      return instance;
    }
    public void setInstance(Object instance) {
      this.instance = instance;
    }
    public PackMethodHandler(Method method, Object instance) {
      super();
      this.method = method;
      this.instance = instance;
      Parameter[] params = method.getParameters() ;
      this.parameters = new PackMethodParameter[params.length] ;
      for (int i = 0; i < params.length; i++) {
        this.parameters[i] = new PackMethodParameter(i, method, params[i].getType()) ;
      }
    }
    public PackMethodParameter[] getParameter() {
      return this.parameters ;
    }
  }
}

2.4 自定義參數(shù)解析器

參數(shù)解析器的作用就是用來(lái)解析通過(guò)請(qǐng)求URI找到對(duì)應(yīng)的處理器方法(PackMethodHandler)。也就是從上面PackHandlerMapping類中保存到Map集合中的通過(guò)請(qǐng)求的URI找到對(duì)應(yīng)的PackMethodHandler對(duì)象。

public interface PackHandlerMethodArgumentResolver {
  boolean supportsParameter(PackMethodParameter methodParameter) ;
  Object resolveArgument(PackMethodParameter methodParameter, HttpServletRequest request);
}
public class PackParamHandlerMethodArgumentResolver implements PackHandlerMethodArgumentResolver {


  @Override
  public boolean supportsParameter(PackMethodParameter methodParameter) {
    return methodParameter.hasParameterAnnotation(PackParam.class) ;
  }


  @Override
  public Object resolveArgument(PackMethodParameter methodParameter, HttpServletRequest request) {
    String name = methodParameter.getParameterName() ;
    Object arg = null;
    String[] parameterValues = request.getParameterValues(name) ;
    if (parameterValues != null) {
      arg = parameterValues.length == 1 ? parameterValues[0] : parameterValues ;
    }
    return arg ;
  }


}

2.5 自定義HandlerAdapter

自定義實(shí)現(xiàn)了SpringMVC標(biāo)準(zhǔn)的HandlerAdatper,這樣在DispatcherServlet中才能夠識(shí)別。該類的核心就是用來(lái)真正的調(diào)用目標(biāo)方法的(PackMethodHandler)。

public class PackHandlerAdapter implements HandlerAdapter{


  @Resource
  private ConversionService conversionService ;


  private PackParamHandlerMethodArgumentResolver argumentResolver = new PackParamHandlerMethodArgumentResolver() ;


  @Override
  public boolean supports(Object handler) {
    return handler instanceof PackMethodHandler;
  }


  @Override
  public ModelAndView handle(HttpServletRequest request, HttpServletResponse response, Object handler)
      throws Exception {
    PackMethodHandler methodHandler = (PackMethodHandler) handler ;


    PackMethodParameter[] parameters = methodHandler.getParameter() ;
    Object[] args = new Object[parameters.length] ;
    for (int i = 0; i < args.length; i++) {
      if (this.argumentResolver.supportsParameter(parameters[i])) {
        // 解析對(duì)應(yīng)的方法參數(shù)
        args[i] = this.argumentResolver.resolveArgument(parameters[i], request) ;
        // 類型轉(zhuǎn)換
        args[i] = this.conversionService.convert(args[i], parameters[i].getType()) ;
      }
    }
    // 調(diào)用目標(biāo)方法
    Object result = methodHandler.getMethod().invoke(methodHandler.getInstance(), args) ;
    // 設(shè)置響應(yīng)header,輸出內(nèi)容
    response.setHeader("Content-Type", "text/plain;charset=utf8") ;
    PrintWriter out = response.getWriter() ;
    out.write((String) result) ;
    out.flush() ;
    out.close() ; 
    return null ;
  }


  @Override
  public long getLastModified(HttpServletRequest request, Object handler) {
    return -1 ;
  }


}

2.6 測(cè)試

@PackEndpoint
@RequestMapping("/users")
public class UserController {
  
  @GetMapping("/index")
  public Object index(@PackParam Long id, @PackParam String name) {
    return "id = " + id + ", name = " + name ;
  }
}

通過(guò)以上的步驟就完成了一個(gè)完全自定義SpringMVC核心組件的實(shí)現(xiàn)。而這就是底層SpringMVC的核心工作原理。

以上是本篇文章的全部?jī)?nèi)容,希望對(duì)你有幫助。

責(zé)任編輯:武曉燕 來(lái)源: Spring全家桶實(shí)戰(zhàn)案例源碼
相關(guān)推薦

2020-02-28 11:29:00

ElasticSear概念類比

2024-04-17 13:21:02

Python匿名函數(shù)

2022-05-28 15:59:55

PythonPandas數(shù)據(jù)可視化

2021-05-15 10:16:14

Python匿名函數(shù)

2021-11-17 10:11:08

PythonLogging模塊

2022-03-30 10:51:40

JavaScript性能調(diào)優(yōu)

2021-03-06 10:05:03

Python函數(shù)變量

2021-11-10 09:19:41

PythonShutil模塊

2021-05-31 08:59:57

Java數(shù)據(jù)庫(kù)訪問(wèn)JDBC

2021-03-15 08:38:42

StringBuffeJava基礎(chǔ)Java開發(fā)

2021-11-13 10:11:45

Pythonurllib庫(kù)Python基礎(chǔ)

2021-01-13 08:40:04

Go語(yǔ)言文件操作

2021-02-20 10:06:14

語(yǔ)言文件操作

2021-02-27 10:20:18

Go語(yǔ)言flag包開發(fā)技術(shù)

2022-04-14 10:10:59

Nginx開源Linux

2022-02-21 09:44:45

Git開源分布式

2023-05-12 08:19:12

Netty程序框架

2021-06-30 00:20:12

Hangfire.NET平臺(tái)

2023-07-30 15:18:54

JavaScript屬性

2023-05-08 08:21:15

JavaNIO編程
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)