SpringBoot3 —— 整合SpringMVC

本文详细介绍了如何在SpringBoot3.0.5版本中整合SpringMVC,包括依赖配置、web应用启动、静态资源管理以及添加interceptor拦截器。通过实例展示了如何配置静态资源路径和启用拦截器功能。
摘要由CSDN通过智能技术生成

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());
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值