SpringMVC这篇文章吃透了,最少最少涨5000

四(2)springMVC框架 阅读详情

本文将通过阅读源码的方式带大家了解 springmv 容器启动的过程,SpringMVC 中的各种组件都是在容器启动的过程中组装的,所以如果熟悉整个过程后,你可以随意对 SpringMVC 进行扩展,SpringMVC 会被你玩的出神入化。

目录

  • 1、前言
  • 2、回顾全注解方式 2 个关键类
    • 2.1、MVC 初始化类
    • 2.2、MVC 配置类
  • 2、SpringMVC 容器的生命周期(9 个阶段)
  • 3、阶段 1:Servlet 容器初始化
    • 3.1、ServletContainerInitializer
    • 3.2、SpringServletContainerInitializer
    • 3.3、SpringServletContainerInitializer#onStartup 方法
    • 3.4、WebApplicationInitializer:web 应用初始化
    • 3.5、进入 AbstractDispatcherServletInitializer#onStartup 方法
  • 4、阶段 2:创建父容器
    • 4.1、过程
    • 4.2、①:负责创建父容器
    • 4.2、②:创建 ContextLoaderListener 监听器
  • 5、阶段 3&4:创建 springmvc 容器&注册 DispatcherServlet
  • 6、阶段 5:启动父容器:ContextLoaderListener
    • 6.1、过程
    • 6.2、代码 ①:配置父容器以及启动父容器
    • 6.3、ApplicationContextInitializer 接口:容器启动前用来初始化容器
  • 7、阶段 6:启动 springmvc 容器:DispatcherServlet#init()
    • 7.1、DispatcherServlet 类图
    • 7.2、HttpServletBean#init()
    • 7.3、FrameworkServlet#initServletBean
    • 7.4、FrameworkServlet#initWebApplicationContext
    • 7.5、FrameworkServlet#configureAndRefreshWebApplicationContext
  • 8、阶段 7:springmvc 容器启动过程中处理@WebMVC
    • 8.1、SpringMVC 配置类被处理
    • 8.2、@EnableWebMvc:配置 springmvc 所需组件
    • 8.3、进入 DelegatingWebMvcConfiguration 类
    • 8.4、WebMvcConfigurationSupport:配置 springmvc 所需所有组件
    • 8.5、WebMvcConfigurer 接口
  • 9、阶段 8:组装 DispatcherServlet 中各种 SpringMVC 需要的组件
    • 9.1、触发 ContextRefreshListener 监听器
    • 9.2、进入 FrameworkServlet.this.onApplicationEvent(event);
    • 9.3、进入 DispatcherServlet#onRefresh
    • 9.4、DispatcherServlet#initStrategies:初始化 DispatcherServlet 中的组件
    • 9.5、initHandlerMappings(context);
    • 9.6、DispatcherServlet#getDefaultStrategies:兜底的方案查找组件
  • 10、阶段 9:销毁容器
    • 10.1、销毁 springmvc 容器:DispatcherServlet#destroy
    • 10.2、销毁父容器:ContextLoaderListener#contextDestroyed
  • 11、带大家 debug 代码
    • 11.1、拉取源码
    • 11.2、将下面这个模块发布到 tomcat
    • 11.2、按照下面配置设置断点,启动,调试代码
  • 12、SpringMVC 系列目录
  • 13、更多好文章
  • 14、【路人甲 Java】所有系列高清 PDF

1、前言

SpringMVC,建议大家使用全注解的方式,全注解的方式及原理不了解的,先去看一下这篇文章:SpringMVC 全注解方式如何使用?

上面的文章看懂以后再来看本文,否则将出现消化不良的现象。

本文以全注解的方式为基础,来解说SpringMVC容器启动的整个流程。

2、回顾全注解方式 2 个关键类

全注解的方式重点就在于 2 个类:MVC 初始化类、MVC 配置类

2.1、MVC 初始化类

代码如下,这个类需要继承 AbstractAnnotationConfigDispatcherServletInitializer,会有 web 容器来调用,这个类中有 4 个方法需要实现,干了 4 件事情

getRootConfigClasses():获取父容器的配置类

getServletConfigClasses():获取 springmvc 容器的配置类,这个配置类相当于 springmvc xml 配置文件的功能

getServletMappings():获取 DispatcherServlet 能够处理的 url,相当于 web.xml 华国 servlet 指定的 url-pattern

getServletFilters():定义所有的 Filter

/**
 * ①:1、创建Mvc初始化类,需要继承AbstractAnnotationConfigDispatcherServletInitializer类
 */
public class MvcInit extends AbstractAnnotationConfigDispatcherServletInitializer {
    /**
     * springmvc容器的父容器spring配置类
     * 实际工作中我们的项目比较复杂,可以将controller层放在springmvc容器中
     * 其他层,如service层、dao层放在父容器了,bean管理起来更清晰一些
     * 也可以没有父容器,将所有bean都放在springmvc容器中
     *
     * @return
     */
    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class[0];
    }

    /**
     * ②:2、设置springmvc容器的spring配置类
     *
     * @return
     */
    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class[]{MvcConfig.class};
    }

    /**
     * ③:3、配置DispatcherServlet的url-pattern
     *
     * @return
     */
    @Override
    protected String[] getServletMappings() {
        return new String[]{"/"};
    }

    /**
     * ④:4、注册拦截器
     *
     * @return
     */
    @Override
    protected Filter[] getServletFilters() {
        //添加拦截器,解决乱码问题
        CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
        characterEncodingFilter.setEncoding("UTF-8");
        characterEncodingFilter.setForceRequestEncoding(true);
        characterEncodingFilter.setForceResponseEncoding(true);
        return new Filter[]{characterEncodingFilter};
    }
}

2.2、MVC 配置类

代码如下,这个配置类相当于 springmvc xml 配置文件的功能,可以在里面定义 springmvc 各种组件

/**
 * 1.开启springmvc注解配置
 * 2、配置视图解析器
 * 3、配置截器
 * 4、配置静态资源访问
 * 5、配置文件上传解析器
 * 6、配置全局异常处理器
 */
@Configuration
@ComponentScan("com.javacode2018.springmvc.chat12")
@EnableWebMvc //1:使用EnableWebMvc开启springmvc注解方式配置
public class MvcConfig implements WebMvcConfigurer {

    /**
     * 2、添加视图解析器(可以添加多个)
     *
     * @param registry
     */
    @Override
    public void configureViewResolvers(ViewResolverRegistry registry) {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("/WEB-INF/view/");
        resolver.setSuffix(".jsp");
        resolver.setOrder(Ordered.LOWEST_PRECEDENCE);
        registry.viewResolver(resolver);
    }

    @Autowired
    private MyInterceptor myInterceptor;

    /**
     * 3、添加拦截器(可以添加多个)
     *
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(this.myInterceptor).addPathPatterns("/**");
    }


    /**
     * 4、配置静态资源访问处理器
     *
     * @param registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**").addResourceLocations("/static/");
    }

    /**
     * 5、配置文件上传解析器
     *
     * @return
     */
    @Bean
    public CommonsMultipartResolver multipartResolver() {
        CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver();
        //maxUploadSizePerFile:单个文件大小限制(byte)
        //maxUploadSize:整个请求大小限制(byte)
        commonsMultipartResolver.setMaxUploadSizePerFile(10 * 1024 * 1024);
        commonsMultipartResolver.setMaxUploadSize(100 * 1024 * 1024);
        return commonsMultipartResolver;
    }
}

2、SpringMVC 容器的生命周期(9 个阶段)

  1. 阶段 1:Servlet 容器初始化
  2. 阶段 2:创建父容器
  3. 阶段 3:创建 springmvc 容器
  4. 阶段 4:Servlet 容器中注册 DispatcherServlet
  5. 阶段 5:启动父容器:ContextLoaderListener
  6. 阶段 6:启动 springmvc 容器:DispatcherServlet#init()
  7. 阶段 7:springmvc 容器启动过程中处理@WebMVC
  8. 阶段 8:组装 DispatcherServlet 中各种 SpringMVC 需要的组件
  9. 阶段 9:销毁 2 个容器

3、阶段 1:Servlet 容器初始化

3.1、ServletContainerInitializer

咱们知道 servlet3.0 中新增了一个接口:ServletContainerInitializer,这个接口功能特别的牛逼,有了它之后,web.xml 配置文件可要可不要了。

public interface ServletContainerInitializer {
    public void onStartup(Set<Class<?>> c, ServletContext ctx)
        throws ServletException;
}

这个接口的实现类,如果满足下面 2 个条件,Servlet 容器启动的过程中会自动实例化这些类,然后调用他们的 onStartUp 方法,然后我们就可以在这些类的 onStartUp 方法中干活了,在 web.xml 干的所有事情,都可以在这个方法中干,特别强大:

这个类必须实现 
ServletContainerInitializer 接口,且非抽象类

这个类的全类名必须要放在
META-INF/services/javax.servlet.ServletContainerInitializer这个文件中

3.2、SpringServletContainerInitializer

下面重点来了,springmvc 提供了一个类SpringServletContainerInitializer,满足了上面个条件。

SpringMVC这篇文章吃透了,最少最少涨5000

spring-web-5.3.6.jar!\META-INF\services\javax.servlet.ServletContainerInitializer

SpringMVC这篇文章吃透了,最少最少涨5000

所以 SpringServletContainerInitializer 的 onStart 方法会 servlet 容器自动被调用

3.3、SpringServletContainerInitializer#onStartup 方法

这个类的源码,大家先看一下,这个类干的事情:

类上有@HandlesTypes(
WebApplicationInitializer.class) 这个注解,注解的值为
WebApplicationInitializer.class,所以 onStartup 方法的第一个参数是WebApplicationInitializer类型的集合,这个集合由 web 容器自动扫描获取,然后传入进来

实例化 WebApplicationInitializer 集合

对 WebApplicationInitializer 集合进行排序

循环调用 WebApplicationInitializer 的 onStartup 方法

@HandlesTypes(WebApplicationInitializer.class) //@1
public class SpringServletContainerInitializer implements ServletContainerInitializer {

 @Override
 public void onStartup(@Nullable Set<Class<?>> webAppInitializerClasses, ServletContext servletContext)
   throws ServletException {

  List<WebApplicationInitializer> initializers = Collections.emptyList();

  if (webAppInitializerClasses != null) {
   initializers = new ArrayList<>(webAppInitializerClasses.size());
   for (Class<?> waiClass : webAppInitializerClasses) {
    // Be defensive: Some servlet containers provide us with invalid classes,
    // no matter what @HandlesTypes says...
    if (!waiClass.isInterface() && !Modifier.isAbstract(waiClass.getModifiers()) &&
      WebApplicationInitializer.class.isAssignableFrom(waiClass)) {
     try {
      initializers.add((WebApplicationInitializer)
        ReflectionUtils.accessibleConstructor(waiClass).newInstance());
     }
     catch (Throwable ex) {
      throw new ServletException("Failed to instantiate WebApplicationInitializer class", ex);
     }
    }
   }
  }

  if (initializers.isEmpty()) {
   servletContext.log("No Spring WebApplicationInitializer types detected on classpath");
   return;
  }

  servletContext.log(initializers.size() + " Spring WebApplicationInitializers detected on classpath");
  AnnotationAwareOrderComparator.sort(initializers);
  for (WebApplicationInitializer initializer : initializers) {
   initializer.onStartup(servletContext);
  }
 }

}

下面重点要看WebApplicationInitializer接口了。

3.4、WebApplicationInitializer:web 应用初始化

接口比较简单,就一个方法,参数是 servlet 上下文对象,有了个对象,可以干 web.xml 中的一切事情了,比如注册 servlet、filter、监听器等等

public interface WebApplicationInitializer {

 void onStartup(ServletContext servletContext) throws ServletException;

}

如下图,看一下类的继承关系,咱们的 MvcInit 就实现了这个接口,所以 MvcInit 的 onStartup 方法会被调费用

SpringMVC这篇文章吃透了,最少最少涨5000

关键代码在这 3 个类中

SpringMVC这篇文章吃透了,最少最少涨5000

3.5、进入 AbstractDispatcherServletInitializer#onStartup 方法

public void onStartup(ServletContext servletContext) throws ServletException {
    super.onStartup(servletContext);
    registerDispatcherServlet(servletContext);
}

这里是重点:这个方法中干了 4 件事情

创建父容器,只是实例化了,并未启动

创建了监听器 ContextLoaderListener,这是一个 ServletContextListener 类型的监听器,稍后会在这个监听器中启动父容器

创建 springmvc 容器,只是实例化了,并未启动,启动的事情会在 DispatcherServlet#init 中做,稍后会说

Servlet 容器中注册 DispatcherServlet

下面,咱们来详细看这几个步骤,把这几个步骤作为阶段来解读。

4、阶段 2:创建父容器

父容器可有可无,并不是必须的,为了更好的管理 bean,springmvc 建议我们用父子容器,controller 之外的 bean,比如 service,dao 等,建议放到父容器中,controller 层的和 springmvc 相关的一些 bean 放在 springmvc 容器中,咱们继续。

4.1、过程

AbstractDispatcherServletInitializer#onStartup方法中会调用父类的onStartup,即AbstractContextLoaderInitializer#onStartup,我们进到这个方法中,代码如下图,干了 2 个事情

图中编号 ①:创建父容器,只是实例化了,并未启动

图中编号 ②:创建了一个监听器 ContextLoaderListener,这是一个 ServletContextListener 类型的监听器,稍后会在这个监听器中启动父容器

SpringMVC这篇文章吃透了,最少最少涨5000

下面来分别来细说下上面 2 段代码干的活。

4.2、①:负责创建父容器

AbstractAnnotationConfigDispatcherServletInitializer#createRootApplicationContext,只是创建了一个AnnotationConfigWebApplicationContext对象,并将父容器配置类 rootConfigClass 注册到容器中,并没有启动这个容器,若 rootConfigClass 为空,父容器不会被创建,所以父容器可有可无。

SpringMVC这篇文章吃透了,最少最少涨5000

4.2、②:创建 ContextLoaderListener 监听器

代码如下,创建的时候将父容器对象 rootAContext 传进去了。

ContextLoaderListener listener = new ContextLoaderListener(rootAppContext);
//getRootApplicationContextInitializers()返回置为ApplicationContextInitializer数组,是个函数式接口,在父容器初始化的过程中,会作为一个扩展点预留给开发者用
listener.setContextInitializers(getRootApplicationContextInitializers());
servletContext.addListener(listener);

ContextLoaderListener,这是一个 ServletContextListener 类型的监听器,所以在 web 容器启动和销毁的过程中会被调用,如下图,这个监听器干了 2 件事

contextInitialized 方法:这个方法会在 web 容器启动时被调用,内部负责启动父容器

在 contextDestroyed 方法:这个方法会在 web 容器销毁时被调用,内部负责关闭父容器

SpringMVC这篇文章吃透了,最少最少涨5000

5、阶段 3&4:创建 springmvc 容器&注册 DispatcherServlet

在回到AbstractDispatcherServletInitializer#onStartup,看这个方法的第二行,如下图

SpringMVC这篇文章吃透了,最少最少涨5000

registerDispatcherServlet源码如下

protected void registerDispatcherServlet(ServletContext servletContext) {
    //①:DispatcherServlet的servlet名称,默认为:dispatcher
    String servletName = getServletName();

    //②:创建springmvc容器
    WebApplicationContext servletAppContext = createServletApplicationContext();

    //③:创建DispatcherServlet,注意这里将springmvc容器对象做为参数传递给DispatcherServlet了
    FrameworkServlet dispatcherServlet = createDispatcherServlet(servletAppContext);
    //设置ApplicationContextInitializer列表,可以对springmvc容器在启动之前进行定制化
    dispatcherServlet.setContextInitializers(getServletApplicationContextInitializers());

    //④:将 dispatcherServlet 注册到servlet上下文中
    ServletRegistration.Dynamic registration = servletContext.addServlet(servletName, dispatcherServlet);
    registration.setLoadOnStartup(1);
    registration.addMapping(getServletMappings());
    registration.setAsyncSupported(isAsyncSupported());

    //⑤:注册Filter
    Filter[] filters = getServletFilters();
    if (!ObjectUtils.isEmpty(filters)) {
        for (Filter filter : filters) {
            registerServletFilter(servletContext, filter);
        }
    }
    //⑥:这个方法预留给咱们自己去实现,可以对dispatcherServlet做一些特殊的配置
    customizeRegistration(registration);
}

protected FrameworkServlet createDispatcherServlet(WebApplicationContext servletAppContext) {
    return new DispatcherServlet(servletAppContext);
}

6、阶段 5:启动父容器:ContextLoaderListener

6.1、过程

上面的onStartup方法执行完毕之后,会执行监听器ContextLoaderListener的初始化,会进入到他的contextInitialized方法中

SpringMVC这篇文章吃透了,最少最少涨5000

initWebApplicationContext源码如下,截取了主要的几行

public WebApplicationContext initWebApplicationContext(ServletContext servletContext) {
    //this.context就是父容器对象
    ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) this.context;
    //①:配置及启动父容器
    configureAndRefreshWebApplicationContext(cwac, servletContext);
    //将父容器丢到servletContext中进行共享,方便其他地方获取
    servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context);
}

6.2、代码 ①:配置父容器以及启动父容器

//①:配置及启动父容器
configureAndRefreshWebApplicationContext(cwac, servletContext);

configureAndRefreshWebApplicationContext方法关键代码如下

protected void configureAndRefreshWebApplicationContext(ConfigurableWebApplicationContext wac, ServletContext sc) {
    //①:定制上线文,这里主要是遍历ApplicationContextInitializer列表,调用每个ApplicationContextInitializer#initialize方法来对容器进行定制,相当于一个扩展点,可以有程序员自己控制
    customizeContext(sc, wac);
    //②:刷新容器,就相当于启动容器了,此时就会组装里面的bean了
    wac.refresh();
}

customizeContext方法,我们进去看一下,这里涉及到了一个新的类,所以有必要去看一下,混个脸熟,源码如下,这是给开发者留的一个扩展点,通过ApplicationContextInitializer这个来做扩展,这是一个函数式接口,下面代码会遍历ApplicationContextInitializer列表,然后调用其initialize方法,我们可以在这个方法中对 spring 上线文进行定制

protected void customizeContext(ServletContext sc, ConfigurableWebApplicationContext wac) {
  List<Class<ApplicationContextInitializer<ConfigurableApplicationContext>>> initializerClasses =
    determineContextInitializerClasses(sc);

    for (Class<ApplicationContextInitializer<ConfigurableApplicationContext>> initializerClass : initializerClasses) {
        Class<?> initializerContextClass =
            GenericTypeResolver.resolveTypeArgument(initializerClass, ApplicationContextInitializer.class);
        if (initializerContextClass != null && !initializerContextClass.isInstance(wac)) {
            throw new ApplicationContextException(String.format(
                "Could not apply context initializer [%s] since its generic parameter [%s] " +
                "is not assignable from the type of application context used by this " +
                "context loader: [%s]", initializerClass.getName(), initializerContextClass.getName(),
                wac.getClass().getName()));
        }
        this.contextInitializers.add(BeanUtils.instantiateClass(initializerClass));
    }

    AnnotationAwareOrderComparator.sort(this.contextInitializers);
    for (ApplicationContextInitializer<ConfigurableApplicationContext> initializer : this.contextInitializers) {
        initializer.initialize(wac);
    }
}

6.3、ApplicationContextInitializer 接口:容器启动前用来初始化容器

是个函数式接口,在容器启动之前用来对容器进行定制,作为一个扩展点预留给开发者用,父容器和 springmvc 容器都用到了。

@FunctionalInterface
public interface ApplicationContextInitializer<C extends ConfigurableApplicationContext> {

 /**
  * 初始化给定的spring容器
  * @param applicationContext the application to configure
  */
 void initialize(C applicationContext);

}

7、阶段 6:启动 springmvc 容器:DispatcherServlet#init()

到目前为止父容器已经启动完毕了,此时 DispatcherServlet 会被初始化,会进入到他的 init()方法中。

7.1、DispatcherServlet 类图

SpringMVC这篇文章吃透了,最少最少涨5000

7.2、HttpServletBean#init()

这个方法会调用initServletBean()这个方法,其他的先不看

SpringMVC这篇文章吃透了,最少最少涨5000

7.3、FrameworkServlet#initServletBean

提取了关键的代码,就 2 行

@Override
protected final void initServletBean() throws ServletException {
    //初始化springmvc容器,就是启动springmvc容器
    this.webApplicationContext = initWebApplicationContext();
    //这个方法内部是空的,预留给子类去实现的,目前没啥用
    initFrameworkServlet();
}

下面咱们进到initWebApplicationContext方法中去。

7.4、FrameworkServlet#initWebApplicationContext

关键代码如下,干了 3 件事情:

从 servlet 上线文对象中找到父容器

为 springmvc 容器指定父容器

调用 
configureAndRefreshWebApplicationContext 方法配置 springmvc 容器以及启动容器,这个是关键咯

protected WebApplicationContext initWebApplicationContext() {
    //①:从servlet上线文中获取父容器
    WebApplicationContext rootContext =
        WebApplicationContextUtils.getWebApplicationContext(getServletContext());
    WebApplicationContext wac = null;
 //②:this.webApplicationContext就是springmvc容器,此时这个对对象不为null,所以满足条件
    if (this.webApplicationContext != null) {
        wac = this.webApplicationContext;
        if (wac instanceof ConfigurableWebApplicationContext) {
            ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) wac;
            //springmvc容器未启动
            if (!cwac.isActive()) {
                //springmvc容器未设置父容器,则给其设置父容器,此时rootContext可能为空,这个没什么关系
                if (cwac.getParent() == null) {
                    cwac.setParent(rootContext);
                }
                //③:配置springmvc容器以及启动springmvc容器
                configureAndRefreshWebApplicationContext(cwac);
            }
        }
    }
    //这里省略了一部分代码,如果springmvc采用配置文件的方式会走这部分代码
    ......
 //返回容器
    return wac;
}

7.5、FrameworkServlet#configureAndRefreshWebApplicationContext

为了让大家看清楚,如下代码,这里只提取了关键代码,主要干了 3 件事情

代码 ①:向 springmvc 容器中添加了一个 ContextRefreshListener 监听器,这个监听器非常非常重要,springmvc 容器启动完毕之后会被调用,会出现在阶段 8 中

代码 ②:给开发者预留的一个扩展点,通过 
ApplicationContextInitializer#initialize 方法对容器进行定制

代码 ③:启动容器

protected void configureAndRefreshWebApplicationContext(ConfigurableWebApplicationContext wac) {
 //①:向springmvc容器中添加了一个监听器对象,这个监听器特别重要,稍后在
    wac.addApplicationListener(new SourceFilteringListener(wac, new ContextRefreshListener()));
 //②:扩展点:循环遍历ApplicationContextInitializer列表,调用其initialize方法对容器进行定制
    applyInitializers(wac);
    //③:刷新容器,相当于启动容器
    wac.refresh();
}

8、阶段 7:springmvc 容器启动过程中处理@WebMVC

8.1、SpringMVC 配置类被处理

此时 springmvc 容器启动了,此时注意下MvcConfig这个类,由于其上有@Conguration 注解,所以会被当做一个配置类被处理,这个类有 2 个非常重要的特征。

标注了@EnableWebMvc 注解

实现了 WebMvcConfigurer 接口

SpringMVC这篇文章吃透了,最少最少涨5000

下面来说说这 2 个特征的作用。

8.2、@EnableWebMvc:配置 springmvc 所需组件

看一下这个注解的源码,如下,重点在于它上面的@Import(DelegatingWebMvcConfiguration.class)注解,这个注解的功能不知道的,可以回头去看我的 spring 系列,从头看一遍。

SpringMVC这篇文章吃透了,最少最少涨5000

8.3、进入 DelegatingWebMvcConfiguration 类

代码如下,先注意下面 3 个特征

代码编号 ①:标注有@Configuration 注解,说明是一个配置类

代码编号 ②:继承了 
WebMvcConfigurationSupport 类,这个类中有很多@Bean 标注的方法,用来定义了 springmvc 需要的所有组件

代码编号 ③:注入了WebMvcConfigurer列表,注意下,我们的 WebConfig 类就实现了 WebMvcConfigurer 这个接口,内部提供了很多方法可以用来对 springmvc 的组件进行自定义配置

SpringMVC这篇文章吃透了,最少最少涨5000

先来看看 WebMvcConfigurationSupport 这个类。

8.4、WebMvcConfigurationSupport:配置 springmvc 所需所有组件

这个类中会定义 springmvc 需要的所有组件,比如:RequestMapping、HandlerAdapter、HandlerInterceptor、HttpMessageConverter、HandlerMethodArgumentResolver、HandlerMethodReturnValueHandler 等等,所以如果你感觉@WebMVC 注解满足不了你的需求时,你可以直接继承这个类进行扩展。

这个类的源码我就不贴了,截几个图给大家看看

SpringMVC这篇文章吃透了,最少最少涨5000

8.5、WebMvcConfigurer 接口

这个接口就是我们用来对 springmvc 容器中的组件进行定制的,WebMvcConfigurationSupport 中创建 springmvc 组件的时候,会自动调用 WebMvcConfigurer 中对应的一些方法,来对组件进行定制,比如可以在 WebMvcConfigurer 中添加拦截器、配置默认 servlet 处理器、静态资源处理器等等,这个接口的源码如下

public interface WebMvcConfigurer {

 /**
  * 配置PathMatchConfigurer
  */
 default void configurePathMatch(PathMatchConfigurer configurer) {
 }

 /**
  * 配置ContentNegotiationConfigurer
  */
 default void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
 }

 /**
  * 异步处理配置
  */
 default void configureAsyncSupport(AsyncSupportConfigurer configurer) {
 }

 /**
  * 配置默认servlet处理器
  */
 default void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
 }

 /**
  * 配置Formatter
  */
 default void addFormatters(FormatterRegistry registry) {
 }

 /**
  * 添加拦截器
  */
 default void addInterceptors(InterceptorRegistry registry) {
 }

 /**
  * 静态资源配置
  */
 default void addResourceHandlers(ResourceHandlerRegistry registry) {
 }

 /**
  * 跨越的配置
  */
 default void addCorsMappings(CorsRegistry registry) {
 }

 /**
  * 配置ViewController
  */
 default void addViewControllers(ViewControllerRegistry registry) {
 }

 /**
  * 注册视图解析器(ViewResolverRegistry)
  */
 default void configureViewResolvers(ViewResolverRegistry registry) {
 }

 /**
  * 注册处理器方法参数解析器(HandlerMethodArgumentResolver)
  */
 default void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
 }

 /**
  * 注册处理器方法返回值处理器(HandlerMethodReturnValueHandler)
  */
 default void addReturnValueHandlers(List<HandlerMethodReturnValueHandler> handlers) {
 }

 /**
  * 注册http报文转换器(HttpMessageConverter)
  */
 default void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
 }

 /**
  * 扩展报文转换器
  */
 default void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
 }

 /**
  * 配置异常解析器(HandlerExceptionResolver)
  */
 default void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> resolvers) {
 }

 /**
  * 扩展异常解析器(HandlerExceptionResolver)
  */
 default void extendHandlerExceptionResolvers(List<HandlerExceptionResolver> resolvers) {
 }

 /**
  * 获得验证器
  */
 @Nullable
 default Validator getValidator() {
  return null;
 }

 /**
  * 获得MessageCodesResolver
  */
 @Nullable
 default MessageCodesResolver getMessageCodesResolver() {
  return null;
 }

}

9、阶段 8:组装 DispatcherServlet 中各种 SpringMVC 需要的组件

9.1、触发 ContextRefreshListener 监听器

大家回头看一下 8.5 中,有这样一段代码,注册了一个监听器ContextRefreshListener

SpringMVC这篇文章吃透了,最少最少涨5000

再来看看这个监听器的源码,如下图,包含 2 点信息

会监听 ContextRefreshedEvent 事件

监听到事件之后将执行
FrameworkServlet.this.onApplicationEvent(event);,稍后会具体说这个代码

SpringMVC这篇文章吃透了,最少最少涨5000

如下代码,springmvc 容器启动完毕之后,会发布一个ContextRefreshedEvent事件,会触发上面这个监听器的执行

SpringMVC这篇文章吃透了,最少最少涨5000

9.2、进入 FrameworkServlet.this.onApplicationEvent(event);

public void onApplicationEvent(ContextRefreshedEvent event) {
    //标记已收到刷新事件
    this.refreshEventReceived = true;
    synchronized (this.onRefreshMonitor) {
        onRefresh(event.getApplicationContext());
    }
}

上面的onRefresh(event.getApplicationContext());会进到DispatcherServlet#onRefresh方法中。

9.3、进入 DispatcherServlet#onRefresh

protected void onRefresh(ApplicationContext context) {
    initStrategies(context);
}

里面会调用initStrategies方法。

9.4、DispatcherServlet#initStrategies:初始化 DispatcherServlet 中的组件

代码如下,这里面会初始化 DispatcherServlet 中的各种组件,这里的所有方法初始化的过程基本上差不多,就是先从 springmvc 容器中找这个组件,如果找不到一般会有一个兜底的方案

protected void initStrategies(ApplicationContext context) {
    //初始化MultipartResolver
    initMultipartResolver(context);
    //初始化LocaleResolver
    initLocaleResolver(context);
    //初始化ThemeResolver
    initThemeResolver(context);
    //初始化HandlerMappings
    initHandlerMappings(context);
    //初始化HandlerAdapters
    initHandlerAdapters(context);
    //初始化HandlerExceptionResolvers
    initHandlerExceptionResolvers(context);
    //初始化RequestToViewNameTranslator
    initRequestToViewNameTranslator(context);
    //初始化视图解析器ViewResolvers
    initViewResolvers(context);
    //初始化FlashMapManager
    initFlashMapManager(context);
}

下面我们以initHandlerMappings(context);为例来看一下是如何初始化这些组件的。

9.5、initHandlerMappings(context);

源码如下,就是先从容器中找,找不到走兜底的方案。

private void initHandlerMappings(ApplicationContext context) {
    this.handlerMappings = null;
    //是否需要查找所有的HandlerMapping,默认为true
    if (this.detectAllHandlerMappings) {
        //从容器中查找所有的HandlerMapping
        Map<String, HandlerMapping> matchingBeans =
                BeanFactoryUtils.beansOfTypeIncludingAncestors(context, HandlerMapping.class, true, false);
        //对HandlerMapping列表进行排序
        if (!matchingBeans.isEmpty()) {
            this.handlerMappings = new ArrayList<>(matchingBeans.values());
            AnnotationAwareOrderComparator.sort(this.handlerMappings);
        }
    }
    else {
        try {
            //查找名称为handlerMapping的HandlerMapping
            HandlerMapping hm = context.getBean("handlerMapping", HandlerMapping.class);
            this.handlerMappings = Collections.singletonList(hm);
        }
        catch (NoSuchBeanDefinitionException ex) {
        }
    }

    // 如果没有找到HandlerMapping,则走兜底的方案
    if (this.handlerMappings == null) {
        this.handlerMappings = getDefaultStrategies(context, HandlerMapping.class);
    }
}

下面我们来看一下兜底的代码如何走的,进入 getDefaultStrategies 方法

9.6、DispatcherServlet#getDefaultStrategies:兜底的方案查找组件

这个方法的源码就不贴出来了,这里只说一下兜底的处理过程,springmvc 有个配置文件:spring-webmvc-5.3.6.jar!\org\springframework\web\servlet\DispatcherServlet.properties,properties 格式的文件,key 为组件的完整类名,value 为多个实现类的列表,在这个配置文件中指定了每种类型的组件兜底的情况下对应的实现类,比如没有找到 RequestMapping 的情况下,如下图红框的部分,有 3 个兜底的实现类,然后 springmvc 会实例化这 3 个类作为 RequestMapping。

SpringMVC这篇文章吃透了,最少最少涨5000

10、阶段 9:销毁容器

10.1、销毁 springmvc 容器:DispatcherServlet#destroy

DispatcherServlet 销毁的时候会关闭 springmvc 容器

public void destroy() {
    if (this.webApplicationContext instanceof ConfigurableApplicationContext && !this.webApplicationContextInjected) {
        ((ConfigurableApplicationContext) this.webApplicationContext).close();
    }
}

10.2、销毁父容器:ContextLoaderListener#contextDestroyed

父容器是在监听器中启动的,所以销毁的也是监听器负责的

public void contextDestroyed(ServletContextEvent event) {
    closeWebApplicationContext(event.getServletContext());
    ContextCleanupListener.cleanupAttributes(event.getServletContext());
}

springmvc 容器的生命周期到此就结束了,想掌握好这个过程,建议大家 debug 走几遍,就熟悉了,下面带大家 debug 一下代码。

11、带大家 debug 代码

11.1、拉取源码

https://gitee.com/javacode2018/springmvc-series

11.2、将下面这个模块发布到 tomcat

SpringMVC这篇文章吃透了,最少最少涨5000

11.2、按照下面配置设置断点,启动,调试代码

依次在下面这些方法中设置断点,然后启动 tomcat,一步步调试,我相信你们肯定可以吃透的。

1、org.springframework.web.SpringServletContainerInitializer#onStartup:入口
2、org.springframework.web.servlet.support.AbstractDispatcherServletInitializer#onStartup
3、org.springframework.web.context.AbstractContextLoaderInitializer#onStartup
4、org.springframework.web.context.AbstractContextLoaderInitializer#registerContextLoaderListener:创建父容器
5、org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer#createRootApplicationContext
6、org.springframework.web.servlet.support.AbstractDispatcherServletInitializer#registerDispatcherServlet
7、org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer#createServletApplicationContext:创建springmvc容器 & 注册DispatcherServlet
8、org.springframework.web.context.ContextLoaderListener#contextInitialized
9、org.springframework.web.context.ContextLoader#initWebApplicationContext
10、org.springframework.web.context.ContextLoader#configureAndRefreshWebApplicationContext:启动父容器
11、org.springframework.web.servlet.HttpServletBean#init
12、org.springframework.web.servlet.FrameworkServlet#initServletBean
13、org.springframework.web.servlet.FrameworkServlet#initWebApplicationContext:初始化springmvc容器&启动springmvc容器
14、org.springframework.web.servlet.FrameworkServlet#configureAndRefreshWebApplicationContext:启动springmvc容器
15、org.springframework.web.servlet.FrameworkServlet.ContextRefreshListener#onApplicationEvent
16、org.springframework.web.servlet.DispatcherServlet#onRefresh
17、org.springframework.web.servlet.DispatcherServlet#initStrategies:组装Dispathcer中
一文吃透 SpringMVC 中的转发和重定向 1、请求转发到其他页面 2、请求转发到其他控制器 3、返回 String 时的请求转发 4、返回 void 时的请求转发 5、请求重定向到其他页面 【1】通过 ModelAndView 中的 Model 携带参数 【2】使用 HttpSession 携带参数 6、请求重定向到其他控制器 【1】通过 ModelAndView 的 Model 携带参数 【2】使用 HttpSession 携带参数 7、返回 String 时的重定向 【1】重定向到页面时携带参数 【2】重定向到控制器时携带参数 阅读详情

相关推荐

AVL(Athena Vortex Lattice)如何编写与应用(一)

前两个是弦向的涡个数和以cos函数分布的间距参数(设为1即可)后两个可以在这里声明也可以写到后面的每一个section中,是展向的涡个数和以sin函数分布的间距参数。这个文件是用来建立飞机模型的文件,是一定要有的文件,其他的.run和.mass并不是必须要有的,甚至mass文件并没有看到有人在使用。Sref、Cref、Bref是飞机的参考面积参考弦长和参考的展长,我的理解就是所设计飞机的S,c,b这三个参数。———————————————以上是飞机的基本信息———————————————

dawangaa的博客 1510

SpringMVC 后台向前台传值

我们今天来尝试 SpringMVC从后台向前台Jsp传值 使用ModelAndView类用来存储处理完后的结果数据,以及显示该数据的视图。从名字上看ModelAndView中的Model代表模型,View代表视图,这个名字就很好地解释了该类的作用。业务处理器调用模型层处理完用户请求后,把结果数据存储在该类的model属性中,把要返回的视图信息存储在该类的view属性中,然后让该ModelAndV...

陌心的博客 1174

InSAR_ISCE软件数据处理流程之:利用哨兵数据获取2015年尼泊尔地震同震形变场

ISCE软件数据处理流程之:利用哨兵数据获取2015年尼泊尔地震同震形变场 ISCE软件做干涉只需要将数据准备好,并配置好insarApp.xml文件即可进行。 一、数据准备 1、SAR数据获取 本利中使用的数据为欧空局提供的sentinel-1A/B数据,可从阿拉斯加数据服务器上下载,具体下载方法可参考: 哨兵数据下载方法. 2、哨兵卫星轨道文件下载 哨兵数据处理除了需要SAR影像外,还需提供轨道参数文件,可从https://qc.sentinel1.eo.esa.int/aux_poeorb/下载。下载

weixin_42128764的博客 1万+

聊聊spring.mvc.servlet.load-on-startup

本文主要研究一下spring.mvc.servlet.load-on-startup。

go4it 592

大麦网抢票协议逆向分析:从Web安全到高并发风控实战

在当今高并发Web应用场景下,理解网络协议交互与反爬虫机制是后端开发和系统架构设计的核心技能。其基本原理涉及客户端与服务器之间通过HTTP/HTTPS协议进行数据交换,关键环节包括请求参数构造、身份认证与会话管理。这一技术的核心价值在于保障系统安全与公平性,通过动态令牌、签名算法及设备指纹等多重手段,有效抵御自动化脚本攻击。典型应用场景包括票务系统、电商秒杀等需要严格管控资源访问的高并发业务。本文以热门票务平台为例,深入剖析其**请求链与令牌体系**及**行为生物特征分析**等风控策略,通过实战演示协议逆向

weixin_34354173的博客 456

VS配置RTKLIB(卫星定位开源代码)环境

@RTKlib代码调试教程-Visual Studio 2019 你好! 这是你第一次使用 Markdown编辑器 所展示的欢迎页。如果你想学习如何使用Markdown编辑器, 可以仔细阅读这篇文章,了解一下Markdown的基本语法知识。 ##RTKLIB-rtklib_2.4.3 提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档 @RTKlib代码调试教程-Visual Studio 2019 提示:这里可以添加本文要记录的大概内容: 例如:随着人工智能的不断发展,机器学习这门技

qq_42209977的博客 4486

spring boot 配置多个DispatcherServlet

传统的web项目,只需要在web.xml里配置多个即可,并且支持多个url-pattern 在spring boot中,我们默认无需配置,系统会自动装配一个,感兴趣的可以看下源码 org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfiguration,里面有个 DispatcherServle...

zwzw1219的博客 5607

海康视觉平台VisionMaster使用学习笔记(1)

双击图像源设置图像源的属性,像素格式分为Mono8和RDB24分别对应导入的图像是彩色还是黑白。打开相机驱动软件MVS,对连接的相机进行属性上的配置,先对相机的IP进行对应的设置。将自动触发的使能打开,保存配置好的相机属性,默认保存到用户集1中。点击MVS软件中的触发按钮,查看相机是否进行正常的触发拍照。打开VM软件添加一个图像源,选择图像源选项拖出图像源。回到VM软件中将选择相机选项选择到配置好参数的相机。取图方式也可以调整为相机取图,将图像源改为相机。双击相机进行连接后对相机的属性进行配置。

A567852的博客 1万+

2022年,SpringMVC这篇文章吃透了,最少最少涨5000

本文将通过阅读源码的方式带大家了解 springmv 容器启动的过程,SpringMVC 中的各种组件都是在容器启动的过程中组装的,所以如果熟悉整个过程后,你可以随意对 SpringMVC 进行扩展,SpringMVC 会被你玩的出神入化。 目录 1、前言 2、回顾全注解方式 2 个关键类 2.1、MVC 初始化类 2.2、MVC 配置类 2、SpringMVC 容器的生命周期(9 个阶段) 3、阶段 1:Servlet 容器初始化 3.1、ServletContainerInitia

Javaesandyou的博客 614

Redash离线环境部署2020.1(centos+windows)

背景 Redash是一款开源的BI系统,核心功能是添加数据源,然后进行数据的可视化展示。一般会拿出来同Supervisor和Metabase进行选型比较,这里对三者的选型不做细致分析。而是给出在Redash开发环境部署踩过的坑,很多坑是自己琢磨出来的,网上几乎找不到更新的资料。适用于没怎么用过linux,也不怎么熟悉python的,用的是最新(master)的redash的代码(上一个发布版本...

Jone_wan的专栏 2139

vcs中systemverilog和c/c++联合仿真

前言 systemverilog中,可以通过DPI、PLI来与外部其它语言的程序进行交互。PLI又分为三类,TF、ACC和VPI,可以认为是PLI技术的三代演进: 其中VPI(PLI3.0)是TF/ACC的一个超集,目前使用的PLI基本上都是VPI。 与PLI技术相独立的另一个技术就是DPI,DPI技术简化了systemverilog与foreign language的交互步骤,对于开发者相对友好,所以使用相对广泛一些。 本文不对DPI中程序调用/数据交互展开讨论(这部分可以参考绿皮书..

kevindas的博客 1万+

2024年C C++最全SpringMVC这篇文章吃透了,最少最少涨5000(2),你还看不懂吗

只是创建了一个对象,并将父容器配置类 rootConfigClass 注册到容器中,并没有启动这个容器,若 rootConfigClass 为空,父容器不会被创建,所以父容器可有可无。

2401_84978503的博客 519

数模笔记_多变量最优化计算之牛顿法

Date: 2_22 Name: Guo Yehao Theme: Calculation in Optimality with multiple variables Reference: 数学建模方法与分析(华章) 在上一节中,我们讨论多变量最优化计算中的随机搜索算法,它的精度并不是众多算法中最高的。在精度问题上,有的时候问题本身就带有明显的误差性,以至于我们不能将其忽略,比如上一节消防站部署的问题,我们在区域划分时就有了误差,因此我们并不需要对结果要求很高的精确度,所以用一些比较粗略的算法就可以.

weixin_45358177的博客 2417

2024年SpringMVC这篇文章吃透了,最少最少涨5000(1),2024年最新可能是全网最细的C C++-资源加载机制剖析

父容器可有可无,并不是必须的,为了更好的管理 bean,springmvc 建议我们用父子容器,controller 之外的 bean,比如 service,dao 等,建议放到父容器中,controller 层的和 springmvc 相关的一些 bean 放在 springmvc 容器中,咱们继续。

2401_84975223的博客 825

怀旧版电脑GBC模拟器

再现原版GBC掌机的界面,电脑运行连游戏界面都一样大小,很怀旧,很真实,(英文版)强烈推荐,很小的文件,很难才找到的。

C# WinForm 基于DirectShow.dll编写的程序,可边预览边保存视频,音频和图片

基于微软的DirectShow.dll的二次开发1.自动识别连接的摄像头跟麦克风且可以对其进行选择(默认选中第一个)2.可录制wmv和avi两种格式的视频并且都带有音频,avi可以录制的分辨率和帧数进行选择,wmv默认进行了淸晰度优化如不喜欢可去除代码中有相关提示3.可在预览点开之后进行拍照,也可边录制视频边拍照4.添加了视频和音频的压缩功能(酌情使用)这次二次开发发现C#对DirectShow的相关信息太少,这次做完也不敢藏私共享出来,还望大家指正

SpringMVC这篇文章吃透了

SpringMVC这篇文章吃透了,最少最少涨5000

weixin_39183923的博客 138

efm32 入门.pdf

本PDF共计22页,介绍的是操作驱动API,下载与否自己斟酌。

2024年C C++最新SpringMVC这篇文章吃透了,最少最少涨5000,2024年阿里+头条+腾讯大厂C C++笔试真题

/①:定制上线文,这里主要是遍历ApplicationContextInitializer列表,调用每个ApplicationContextInitializer#initialize方法来对容器进行定制,相当于一个扩展点,可以有程序员自己控制。//getRootApplicationContextInitializers()返回置为ApplicationContextInitializer数组,是个函数式接口,在父容器初始化的过程中,会作为一个扩展点预留给开发者用。

2401_84975342的博客 992

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

【Spring MVC】一篇文章带你吃透 SpringMVC 请求

文章摘要 本文深入探讨了SpringMVC请求参数处理的三种场景: 单个参数传递 对比Integer与int类型的差异:未传参时Integer默认为null,int会抛出500错误 建议优先使用包装类类型 多参数与对象传递 多参数通过名称匹配,与顺序无关 对象参数支持自动属性映射,无参构造方法会初始化默认值 参数重命名 使用@RequestParam注解解决前后端参数名不一致问题 支持设置必传校验(required属性) 核心结论:SpringMVC通过「参数解析→类型转换→赋值」流程处理请求,合理使用包装

2301_81614213的博客 1519

一文吃透SpringMVC

一、SpringMVC简介 1、什么是MVC MVC是一种软件架构模式(是一种软件架构设计思想,不止Java开发中用到,其它语言也需要用到),它将应用分为三块: M:Model(模型),负责业务处理及数据的收集 V:View(视图),负责数据的展示 C:Controller(控制器),负责调度。它是一个调度中心,它来决定什么时候调用Model来处理业务,什么时候调用View视图来展示数据 MVC架构模式的描述:前端浏览器发送请求给web服务器,web服务器中的Controller接收到用户的请求,Co

Tyson0314的博客 941

三天吃透SpringMVC面试八股文

SpringMVC是一种基于 Java 的实现MVC设计模型的请求驱动类型的轻量级Web框架,属于Spring框架的一个模块。 它通过一套注解,让一个简单的Java类成为处理请求的控制器,而无须实现任何接口。同时它还支持RESTful编程风格的请求。

Tyson0314的博客 1277

一天吃透SpringMVC面试八股文

MVC的全名是,是模型(model)-视图(view)-控制器(controller)的缩写,是一种软件设计典范。它是用一种业务逻辑、数据与界面显示分离的方法来组织代码,将众多的业务逻辑聚集到一个部件里面,在需要改进和个性化定制界面及用户交互的同时,不需要重新编写业务逻辑,达到减少编码的时间。View,视图是指用户看到并与之交互的界面。比如由html元素组成的网页界面,或者软件的客户端界面。MVC的好处之一在于它能为应用程序处理很多不同的视图。

Tyson0314的博客 1149

吃透SpringMVC面试八股文

MVC的全名是,是模型(model)-视图(view)-控制器(controller)的缩写,是一种软件设计典范。它是用一种业务逻辑、数据与界面显示分离的方法来组织代码,将众多的业务逻辑聚集到一个部件里面,在需要改进和个性化定制界面及用户交互的同时,不需要重新编写业务逻辑,达到减少编码的时间。View,视图是指用户看到并与之交互的界面。比如由html元素组成的网页界面,或者软件的客户端界面。MVC的好处之一在于它能为应用程序处理很多不同的视图。

Tyson0314的博客 470

一文吃透SpringMVC面试八股文

MVC的全名是,是模型(model)-视图(view)-控制器(controller)的缩写,是一种软件设计典范。它是用一种业务逻辑、数据与界面显示分离的方法来组织代码,将众多的业务逻辑聚集到一个部件里面,在需要改进和个性化定制界面及用户交互的同时,不需要重新编写业务逻辑,达到减少编码的时间。View,视图是指用户看到并与之交互的界面。比如由html元素组成的网页界面,或者软件的客户端界面。MVC的好处之一在于它能为应用程序处理很多不同的视图。

Tyson0314的博客 466

一篇文章吃透SpringMVC全部知识点

本文涵盖了SpringMVC的全部知识点:包括1.MVC与SpringMVC的介绍、2.@RequestMapping注解属性分析、3.SpringMVC获取请求参数各种方式、4.域对象共享数据、5.SpringMVC视图技术、6.RESTful风格与案例详解、7.SpringMVC如何处理ajax请求、8.文件的上传与下载技术、9.拦截器、10.异常处理器、11.注解方式配置SpringMVC、12.SpringMVC执行流程分析

weixin_52536274的博客 417
上一篇: Spring 官方批处理框架真香,Spring 全家桶永远滴神
下一篇: 为什么总是用不好设计模式?
Javaesandyou
博客等级 码龄5年 742粉丝 563原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值