javascript
java 方式配置ssm,关于SSM以及Spring boot中对于Spring MVC配置的问题
SSM中 Spring MVC配置
傳統的web.xml配置
web.xml
contextConfigLocation
classpath*:applicationContext.xml
org.springframework.web.context.ContextLoaderListener
encodingFilter
org.springframework.web.filter.CharacterEncodingFilter
encoding
UTF-8
encodingFilter
/*
SpringMVC
org.springframework.web.servlet.DispatcherServlet
contextConfigLocation
classpath:spring-mvc.xml
SpringMVC
/
spring-mvc.xml
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
id="internalResourceViewResolver">
基于java配置的方式
現在JavaConfig配置方式在逐步取代xml配置方式。而WebApplicationInitializer可以看做是Web.xml的替代,它是一個接口。通過實現WebApplicationInitializer,在其中可以添加servlet,listener等,在加載Web項目的時候會加載這個接口實現類,從而起到web.xml相同的作用。
SpittrWebAppInitializer 主配置類
//擴展自Abstrac~Initializer的任意類,都會自動地配置Dispatcher-Servlet和Spring應用上下文
//spring的應用上下文會位于程序的Servlet上下文之中
public class SpittrWebAppInitializer extends
AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class>[] getServletConfigClasses() {
return new Class>[] { WebConfig.class };
}
//映射“/”,表示會使用默認的Servlet
@Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
@Override
protected Class>[] getRootConfigClasses() {
// TODO Auto-generated method stub
return null;
}
@Override
protected Filter[] getServletFilters() {
final CharacterEncodingFilter encodingFilter = new CharacterEncodingFilter();
encodingFilter.setEncoding("UTF-8");
encodingFilter.setForceEncoding(true);
return new Filter[] { encodingFilter };
}
}
我們創建的SpittrWebAppInitializer這個類是繼承了
AbstractAnnotationConfigDispatcherServletInitializer,其繼承關系為:
AbstractAnnotationConfigDispatcherServletInitializer extends AbstractDispatcherServletInitializer extends AbstractContextLoaderInitializer implements WebApplicationInitializer
AbstractDispatcherServletInitializer對DispatcherServlet進行了自動配置和初始化;AbstractContextLoaderInitializer初始化和配置了Spring應用的上下文。因此,任意繼承自這個類的類都會通過創建DispatcherServlet和ContextLoaderListener,自動配置DispatcherServlet和Spring應用上下文,但是真正完成配置上下文的是WebApplicationInitializer接口。
WebApplicationInitializer接口
WebApplicationInitializer接口是如何完成配置的呢?其只有一個方法onStartup,看不出什么頭緒。但是,在這個包下有另外一個類,SpringServletContainerInitializer。
public interface WebApplicationInitializer {
void onStartup(ServletContext servletContext) throws ServletException;
}
@HandlesTypes(WebApplicationInitializer.class)
public class SpringServletContainerInitializer implements ServletContainerInitializer {
@Override
public void onStartup(Set> webAppInitializerClasses, ServletContext servletContext)
throws ServletException {
List initializers = new LinkedList();
if (webAppInitializerClasses != null) {
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) 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);
}
}
}
SpringServletContainerInitializer實現了ServletContainerInitializer接口,其在web容器啟動時為提供給第三方組件機會做一些初始化的工作,例如注冊servlet或者filtes等,servlet規范中通過ServletContainerInitializer實現此功能。每個框架要使用ServletContainerInitializer就必須在對應的jar包的META-INF/services 目錄創建一個名為javax.servlet.ServletContainerInitializer的文件,文件內容指定具體的ServletContainerInitializer實現類,那么,當web容器啟動時就會運行這個初始化器做一些組件內的初始化工作。
一般伴隨著ServletContainerInitializer一起使用的還有HandlesTypes注解,通過HandlesTypes可以將HandlesTypes指定的類或者實現該接口的類注入到SpringServletContainerInitializer的onStartup方法作為參數傳入。
Tomcat容器的ServletContainerInitializer機制的實現,主要交由Context容器和ContextConfig監聽器共同實現,ContextConfig監聽器負責在容器啟動時讀取每個web應用的WEB-INF/lib目錄下包含的jar包的META-INF/services/javax.servlet.ServletContainerInitializer,以及web根目錄下的META-INF/services/javax.servlet.ServletContainerInitializer,通過反射完成這些ServletContainerInitializer的實例化,然后再設置到Context容器中,最后Context容器啟動時就會分別調用每個ServletContainerInitializer的onStartup方法,并將感興趣的類作為參數傳入。
Spring Web中通常會有兩種應用上下文,一種是Spring MVC上下文,這種上下文通過DispatcherServlet加載,對應上邊的getServletConfigClasses()方法,另一種上下文是spring容器本身的上下文,就要通過ContextLoaderListerner創建,對應的是方法getRootConfigClasses()
WebConfig.java 類
@Configuration //標明了該類是一個配置類并且會將該類作為一個SpringBean添加到IOC容器內
@EnableWebMvc
//通過查看@EnableWebMvc的源碼,可以發現該注解就是為了引入一個DelegatingWebMvcConfiguration Java 配置類。并翻看DelegatingWebMvcConfiguration的源碼會發現該類似繼承于WebMvcConfigurationSupport的類。
@ComponentScan("spitter.web")
public class WebConfig extends WebMvcConfigurerAdapter {
/**
* 配置JSP視圖解析器,他會查找jsp文件,在查找的時候
* 他會在視圖名稱上加一個特定的前綴和后綴
* home的視圖——解析成為/WEB-INF/views/home.jsp
* @return
*/
@Bean
public ViewResolver viewResolver(){
InternalResourceViewResolver resolver=
new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
resolver.setExposeContextBeansAsAttributes(true);
return resolver;
}
/**
* 通過調用enable方法,我們要求DispatcherServelet將
* 對靜態資源的請求轉發到Servlet容器中的默認的Servlet上,
* 不是DispatcherServelet本身處理
* @param configurer
*/
public void configureDefaultServleHandling(DefaultServletHandlerConfigurer configurer){
configurer.enable();
}
}
WebConfig中的配置其實就是對應web.xml中spring-mvc.xml的配置。@EnableWebMvc注解內部使用了@Import(DelegatingWebMvcConfiguration.class),其作用是會把WebMvcConfigurationSupport當成配置文件來用,將其中所有標識有@Bean注解的方法配置成bean,這就成了Spring mvc的默認配置。
@Configuration
public class DelegatingWebMvcConfiguration extends WebMvcConfigurationSupport {
private final WebMvcConfigurerComposite configurers = new WebMvcConfigurerComposite();
@Autowired(required = false)
public void setConfigurers(List configurers) {
if (!CollectionUtils.isEmpty(configurers)) {
this.configurers.addWebMvcConfigurers(configurers);
}
}
....//省略其他方法
}
DelegatingWebMvcConfiguration繼承了WebMvcConfigurationSupport類,其setConfigurers()方法在覆蓋父類的方法之前,它會尋找容器中所有的WebMvcConfigurer實現類,將所有WebMvcConfigurer實現類中的配置組合起來,組成一個超級配置(WebMvcConfigurerAdapter是WebMvcConfigurer的實現類)。這樣,WebMvcConfigurationSupport中的bean發布時,就會把這所有配置都帶上了。
WebMvcConfigurer接口提供的功能如下表所示:
配置接口
接口說明
configurePathMatch
配置HandlerMapping路徑匹配參數
configureContentNegotiation
配置路徑到請求內容類型轉換的相關參數,如.pdf結尾的請求解析成PDF類型或者其它等
configureAsyncSupport
配置異步請求處理相關參數
configureDefaultServletHandling
配置是否需要以下功能:如果一個請求沒有被任何Handler處理,那是否使用DefaultServletHttpRequestHandler來進行處理?
addFormatters
增加額外的Converter和Formatter
addInterceptors
增加攔截器
addResourceHandlers
增加處理靜態資源的Handler
addCorsMappings
配置跨域請求相關參數
addViewControllers
使用特殊的Controller來處理指定的URL請求;
configureViewResolvers
配置將Controller返回的視圖名稱轉換成視圖的視圖解析器; 以便進行視圖渲染
addArgumentResolvers
添加支持個性化配置Controller的方法參數類型的Resolver。
addReturnValueHandlers
添加支持個性化處理Controller返回數據類型的處理器;
configureMessageConverters
配置消息轉換器;
extendMessageConverters
擴展消息轉換器
configureHandlerExceptionResolvers
配置異常處理器
extendHandlerExceptionResolvers
擴展異常處理器
注意:
spring-webmvc 從5.0開始已經廢除了WebMvcConfigurerAdapter類,對于spring mvc的配置可以通過直接實現WebMvcConfigurer接口來實現。
public class WebConfig implements WebMvcConfigurer
Spring boot
在spring boot中通過WebMvcAutoConfiguration自動配置類已經將配置的大部分工作完成了,可以簡單的認為,WebMvcAutoConfiguration完成了之前SpittrWebAppInitializer和WebConfig的工作,提供適用于多數應用的自動配置功能。自動配置添加了以下特性:
引入ContentNegotiatingViewResolver和BeanNameViewResolver beans。
對靜態資源的支持,包括對WebJars的支持。
自動注冊Converter,GenericConverter,Formatter beans。
對HttpMessageConverters的支持。
自動注冊MessageCodeResolver。
一般情況下是不需要改動mvc的配置的,但是如果需要添加其他mvc配置,有兩種方法:
全面棄用spring boot的自動配置
直接繼承WebMvcConfigurationSupport在擴展的類中重寫父類的方法
使用注解@Configuration + @EnableWebMvc,并繼承WebMvcConfigurationAdapter,重寫父類的方法
在spring boot自動配置的基礎上添加部分配置
繼承WebMvcConfigurationAdapter,在擴展的類中重寫父類的方法
注意:
spring boot 從2.0使用spring-webmvc 5.0因此繼承WebMvcConfigurationAdapter需要替換為實現WebMvcConfigurer接口
public class WebConfig implements WebMvcConfigurer
總結
以上是生活随笔為你收集整理的java 方式配置ssm,关于SSM以及Spring boot中对于Spring MVC配置的问题的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 安卓的好处和坏处(安卓的好处)
- 下一篇: 安卓好处在哪里(安卓好处)