网站怎么做付款平台,wordpress卡密销售插件,有没有免费手游代理,重庆做网站建设哪里好我们从两个角度研究EnableWebMvc#xff1a;
EnableWebMvc的使用EnableWebMvc的底层原理
EnableWebMvc的使用
EnableWebMvc需要和java配置类结合起来才能生效#xff0c;其实Spring有好多Enablexxxx的注解#xff0c;其生效方式都一样#xff0c;通过和Configuration结合…我们从两个角度研究EnableWebMvc
EnableWebMvc的使用EnableWebMvc的底层原理
EnableWebMvc的使用
EnableWebMvc需要和java配置类结合起来才能生效其实Spring有好多Enablexxxx的注解其生效方式都一样通过和Configuration结合、使得Enablexxxx中的配置类大多通过Bean注解注入到Spring IoC容器中。
理解这一配置原则EnableWebMvc的使用其实非常简单。
我们还是使用前面文章的案例进行配置。
新增配置类
在org.example.configuration包下新增一个配置类
Configuration
EnableWebMvc
ComponentScan({org.example.controller})
public class MvcConfiguration{Overridepublic void extendMessageConverters(ListHttpMessageConverter? converters) {for(HttpMessageConverter httpMessageConverter:converters){if(StringHttpMessageConverter.class.isAssignableFrom(httpMessageConverter.getClass())){((StringHttpMessageConverter)httpMessageConverter).setDefaultCharset(Charset.forName(UTF-8));}}}
}配置类增加controller的包扫描路径添加EnableWebMvc注解其他不需要干啥。
简化web.xml
由于使用了EnableWebMvc所以web.xml可以简化只需要启动Spring IoC容器、添加DispatcherServlet配置即可
?xml version1.0 encodingUTF-8?
web-app xmlns:xsihttp://www.w3.org/2001/XMLSchema-instancexmlnshttp://xmlns.jcp.org/xml/ns/javaeexsi:schemaLocationhttp://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsdidWebApp_ID version3.1
!-- 1、启动Spring的容器--context-paramparam-namecontextConfigLocation/param-nameparam-valueclasspath:applicationContext.xml/param-value/context-paramlistenerlistener-classorg.springframework.web.context.ContextLoaderListener/listener-class/listenerservletservlet-namedispatcherServlet/servlet-nameservlet-classorg.springframework.web.servlet.DispatcherServlet/servlet-classinit-paramparam-namecontextConfigLocation/param-nameparam-valueclasspath:springmvc.xml/param-value/init-paramload-on-startup1/load-on-startup/servletservlet-mappingservlet-namedispatcherServlet/servlet-nameurl-pattern//url-pattern/servlet-mapping/web-appapplicationContext.xml
Spring IoC容器的配置文件指定包扫描路径即可
?xml version1.0 encodingUTF-8?
beans xmlnshttp://www.springframework.org/schema/beansxmlns:xsihttp://www.w3.org/2001/XMLSchema-instancexmlns:contexthttp://www.springframework.org/schema/contextxmlns:aophttp://www.springframework.org/schema/aopxmlns:txhttp://www.springframework.org/schema/txxsi:schemaLocationhttp://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsdhttp://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsdhttp://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsdcontext:component-scan base-packageorg.examplecontext:exclude-filter typeannotationexpressionorg.springframework.stereotype.Controller //context:component-scan
/beansSpringmvc.xml
springmvc.xml文件也可以简化只包含一个视图解析器及静态资源解析的配置即可其他的都交给EnableWebMvc即可
?xml version1.0 encodingUTF-8?
beans xmlnshttp://www.springframework.org/schema/beansxmlns:mvchttp://www.springframework.org/schema/mvcxmlns:contexthttp://www.springframework.org/schema/contextxmlns:xsihttp://www.w3.org/2001/XMLSchema-instancexsi:schemaLocationhttp://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/mvchttp://www.springframework.org/schema/mvc/spring-mvc.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsd!-- 放行静态资源 --mvc:default-servlet-handler /!-- 视图解析器 --bean idviewResolver classorg.springframework.web.servlet.view.InternalResourceViewResolver!-- 视图前缀 --property nameprefix value/ /!-- 视图后缀 --property namesuffix value.jsp //bean/beans测试
添加一个controller
Controller
public class HelloWorldController {GetMapping(value/hello)ResponseBodypublic String hello(ModelAndView model){return h1EnableWebMvc 你好/h1;}
}启动应用测试
发现有中文乱码。
解决中文乱码
参考上一篇文章改造一下MvcConfiguration配置文件实现WebMvcConfigurer接口、重写其extendMessageConverters方法 Configuration
EnableWebMvc
ComponentScan({org.example.controller})
public class MvcConfiguration implements WebMvcConfigurer{public MvcConfiguration(){System.out.println(mvc configuration constructor...);}
// 通过EnableWebMVC配置的时候起作用Overridepublic void extendMessageConverters(ListHttpMessageConverter? converters) {for(HttpMessageConverter httpMessageConverter:converters){if(StringHttpMessageConverter.class.isAssignableFrom(httpMessageConverter.getClass())){((StringHttpMessageConverter)httpMessageConverter).setDefaultCharset(Charset.forName(UTF-8));}}}}重启系统测试
中文乱码问题已解决。
问题EnableWebMvc的作用
上述案例已经可以正常运行可我们可以看到web.xml、applicationContext.xml以及springmvc.xml等配置文件都还在一个都没少。
那么EnableWebMvc究竟起什么作用
我们去掉EnableWebMvc配置文件试试看项目中删掉MvcConfiguration文件。
重新启动项目访问localhost:8080/hello报404
回忆一下MvcConfiguration文件中定义了controller的包扫描路径现在MvcConfiguration文件被我们直接删掉了controller的包扫描路径需要以其他方式定义我们重新修改springmvc.xml文件把controller包扫描路径加回来。
同时我们需要把SpringMVC的注解驱动配置加回来 !-- 扫描包 --context:component-scan base-packageorg.example.controller/mvc:annotation-driven /以上两行加入到springmvc.xml配置文件中重新启动应用
应用可以正常访问了中文乱码问题请参考上一篇文章此处忽略。
因此我们是否可以猜测EnableWebMvc起到的作用等同于配置文件中的 mvc:annotation-driven / ?
EnableWebMvc的底层原理
其实Spring的所有Enablexxx注解的实现原理基本一致和Configuration注解结合、通过Import注解引入其他配置类从而实现向Spring IoC容器注入Bean。
EnableWebMvc也不例外。
Retention(RetentionPolicy.RUNTIME)
Target(ElementType.TYPE)
Documented
Import(DelegatingWebMvcConfiguration.class)
public interface EnableWebMvc {
}EnableWebMvc引入了DelegatingWebMvcConfiguration类。看一眼DelegatingWebMvcConfiguration类肯定也加了Configuration注解的
Configuration(proxyBeanMethods false)
public class DelegatingWebMvcConfiguration extends WebMvcConfigurationSupport {...DelegatingWebMvcConfiguration类扩展自WebMvcConfigurationSupport其实DelegatingWebMvcConfiguration并没有创建bean、实际创建bean的是他的父类WebMvcConfigurationSupport。
WebMvcConfigurationSupport按顺序注册如下HandlerMappings:
RequestMappingHandlerMapping ordered at 0 for mapping requests to annotated controller methods.HandlerMapping ordered at 1 to map URL paths directly to view names.BeanNameUrlHandlerMapping ordered at 2 to map URL paths to controller bean names.HandlerMapping ordered at Integer.MAX_VALUE-1 to serve static resource requests.HandlerMapping ordered at Integer.MAX_VALUE to forward requests to the default servlet.
并注册了如下HandlerAdapters:
RequestMappingHandlerAdapter for processing requests with annotated controller methods.HttpRequestHandlerAdapter for processing requests with HttpRequestHandlers.SimpleControllerHandlerAdapter for processing requests with interface-based Controllers.
注册了如下异常处理器HandlerExceptionResolverComposite
ExceptionHandlerExceptionResolver for handling exceptions through org.springframework.web.bind.annotation.ExceptionHandler methods.ResponseStatusExceptionResolver for exceptions annotated with org.springframework.web.bind.annotation.ResponseStatus.DefaultHandlerExceptionResolver for resolving known Spring exception types
以及 Registers an AntPathMatcher and a UrlPathHelper to be used by: the RequestMappingHandlerMapping,the HandlerMapping for ViewControllersand the HandlerMapping for serving resources Note that those beans can be configured with a PathMatchConfigurer. Both the RequestMappingHandlerAdapter and the ExceptionHandlerExceptionResolver are configured with default instances of the following by default: a ContentNegotiationManagera DefaultFormattingConversionServicean org.springframework.validation.beanvalidation.OptionalValidatorFactoryBean if a JSR-303 implementation is available on the classpatha range of HttpMessageConverters depending on the third-party libraries available on the classpath.
因此EnableWebMvc确实与 mvc:annotation-driven / 起到了类似的作用注册SpringWebMVC所需要的各种特殊类型的bean到Spring容器中以便在DispatcherServlet初始化及处理请求的过程中生效
上一篇 Spring MVC 十一中文乱码