SpringBoot3整合SpringMVC
1.实现过程
<!-- springmvc所需依赖 -->
<parent>
<!-- spring-boot -->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.0.5</version>
</parent>
<dependencies>
<!-- web启动器 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
@SpringBootApplication
public class Main {
public static void main(String[] args) {
// 自动创建ioc | 启动内置web服务器
SpringApplication.run(Main.class,args);
}
}
@RestController
@RequestMapping("hello")
public class HelloController {
@GetMapping("boot")
public String say(){
return "rehello";
}
}
打开浏览器输入 : http://localhost:8080/hello/boot
2.web相关配置
application.properties
# Spring Boot的配置文件中与Web应用程序相关的一些重要配置参数
server.port 应用程序的HTTP服务器端口号
server.servleet.context-path 应用程序在URL中的根路径
spring.mvc.view.profix / spring.mvc.view.suffix 视图解析器的前缀/后缀
spring.resources.static-locations 配置静态资源的位置
spring.http.encoding.charset / spring.http.encoding.enabled 配置HTTP请求/响应的字符编码
3.静态资源的访问:
静态资源在这些目录中任何一个,SpringMVC都会帮我们处理。 我们习惯会把静态资源放在classpath:/static/ 目录下,不需要写静态资源文件夹,直接访问文件即可。
1. 默认的静态资源路径为:
· classpath:/META-INF/resources/
· classpath:/resources/
· classpath:/static/
· classpath:/public/
打开浏览器输入 : http://localhost:8080/login.html
2. 自定义静态资源路径:
在application.yaml中配置
# 配置静态资源路径
spring:
web:
resources:
static-locations: classpath:/webapp
注:自定义静态资源路径后,原来默认的路径被覆盖,无法访问不生效,只按照自定义路径查找
4.interceptor拦截器
需要时配置即可
public class MyInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("request = " + request + ", response = " + response + ", handler = " + handler);
return true;
}
}
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new MyInterceptor());
}
}
id addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new MyInterceptor());
}
}