spring 的WebMvc 配置

WebMvcConfigurationSupport、WebMvcConfigurer、@EnableWebMvc

问题:为什么继承了WebMvcConfigurationSupport后有些配置会不生效呢?WebMvcConfigurer又是什么呢?

简介:

SpringBoot帮我们做了很多的事情,但是有的时候会有自定义的Handler,Interceptor,ViewResolver,MessageConverter等,该怎么配置呢?为什么继承了WebMvcConfigurationSupport后有些配置会不生效呢?WebMvcConfigurer又是什么呢?我们继承WebMvcConfigurationSupport可以自定义SpringMvc的配置。

SpringBoot帮我们做了很多的事情,但是有的时候会有自定义的Handler,Interceptor,ViewResolver,MessageConverter等,该怎么配置呢?为什么继承了WebMvcConfigurationSupport后有些配置会不生效呢?WebMvcConfigurer又是什么呢?

1、WebMvcConfigurationSupport

我们继承WebMvcConfigurationSupport可以自定义SpringMvc的配置。

跟踪发现DelegatingWebMvcConfiguration类是WebMvcConfigurationSupport的一个实现类,DelegatingWebMvcConfiguration类的setConfigurers方法可以收集所有的WebMvcConfigurer实现类中的配置组合起来,组成一个超级配置(这些配置会覆盖掉默认的配置)。而@EnableWebMvc又引入了DelegatingWebMvcConfiguration。

什么是DelegatingWebMvcConfiguration?

DelegatingWebMvcConfiguration是对Spring MVC进行配置的一个代理类。它结合缺省配置和用户配置定义Spring MVC运行时最终使用的配置。

	private final WebMvcConfigurerComposite configurer
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring MVC 是一个用于构建 Web 应用程序的框架,它基于 Spring 框架之上,提供了一套强大的处理请求、响应和视图的机制。下面是一个简单的 Spring MVC 配置示例: 1. 首先,你需要在 pom.xml 文件中添加 Spring MVC 相关的依赖项: ```xml <dependencies> <!-- Spring MVC --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.3.9</version> </dependency> <!-- 其他依赖项 --> </dependencies> ``` 2. 创建一个配置类(例如 `WebConfig.java`),并配置 Spring MVC: ```java @Configuration @EnableWebMvc @ComponentScan(basePackages = "com.example.controller") // 指定控制器所在的包路径 public class WebConfig implements WebMvcConfigurer { @Override public void configureViewResolvers(ViewResolverRegistry registry) { registry.jsp("/WEB-INF/views/", ".jsp"); // 配置 JSP 视图解析器 } @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/static/**") .addResourceLocations("/static/"); // 配置静态资源访问路径 } } ``` 3. 创建一个控制器类(例如 `HelloController.java`): ```java @Controller public class HelloController { @RequestMapping("/") public String hello() { return "hello"; // 返回视图名称 } } ``` 4. 创建一个 JSP 视图文件(例如 `hello.jsp`): ```jsp <html> <body> <h1>Hello, Spring MVC!</h1> </body> </html> ``` 以上是一个简单的 Spring MVC 配置示例,你可以根据自己的需求进行进一步的配置和扩展。希望可以帮助到你!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值