关于@EnableWebMvc注解
我们知道SpringBoot帮我们在内部实现了很多自动配置,比如SpringMvc,以前需要我们自己编写很多xml文件,而现在SpringBoot都已经帮我们解决了。但是如果不想用SpringBoot帮我们配置,只需加上@EnableWebMvc即可。
扩展SpringMvc配置
尽管SpringBoot帮我们实现了很多功能,但是有时候有些功能还是无法满足,这时候就需要我们自己编写配置类。如:
package com.config;
import com.component.LoginHandlerInterceptor;
import com.component.MyLocalResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
public class MyMvcConfig extends WebMvcConfigurerAdapter {
/**
大部分时候访问一个资源,都需要编写controller类,但是也可以不通过controller方法就能访问资源
如下方法:当在浏览器 输入 : http://localhost:port/guigu 即跳转到 success.html页面
下面的 / 和 /index.html 也是一样
*/
@Override
public void addViewControllers(ViewControllerRegistry registry) {
// 浏览器发送 /guigu,请求来到success
registry.addViewController("/guigu").setViewName("success");
}
@Bean
public WebMvcConfigurerAdapter webMvcConfigurerAdapter(){
WebMvcConfigurerAdapter adapter = new WebMvcConfigurerAdapter() {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
System.out.println("===== into addView Controllers registry ======");
registry.addViewController("/").setViewName("login");
registry.addViewController("/index.html").setViewName("dashboard");
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
System.out.println("===== into add Interceptor registry ======");
registry.addInterceptor(new LoginHandlerInterceptor()).addPathPatterns("/**")
.excludePathPatterns("/index.html","/","/user/login");
}
};
return adapter;
}
}