SpringBoot-配置Spring MVC

一、Spring MVC回顾

Spring MVC是一种常用的Java Web框架,它提供了一种基于MVC模式的开发方式,可以方便地实现Web应用程序。在Spring MVC中,WebMvcConfigurer是一种常用的配置方式,可以允许我们自定义Spring MVC的行为,比如添加拦截器、消息转换器等。

可以看到WebMvcConfigurer是一个非常灵活和强大的工具,它可以让我们实现自己的业务需求并提高代码的可读性和可维护性。而且我们在Spring、SpringBoot都可以很简单的使用WebMvcConfigurer,下面主要在SpringBoot中说明配置


二、配置Spring MVC

官方建议:直接创建一个MyMvcConfig类,在类上加上@Configuration注解,并且实现WebMvcConfigurer接口(相当与SpringMVC项目中的applicationContext.xml文件 ),并且不能使用@EnableWebMvc注解

java 复制代码
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {

}

为什么不能使用@EnableWebMvc注解

@EnableWebMvc导入了DelegatingWebMvcConfiguration类

DelegatingWebMvcConfiguration又继承了WebMvcConfigurationSupport

但是我们查看WebMvcAutoConfiguration类发现添加了@ConditionalOnMissingBean(WebMvcConfigurationSupport.class),那么在使用@EnableWebMvc注解时,WebMvcAutoConfiguration这个自动配置类就不会在进行加载


如果需要全面接管SpringMVC可以使用该注解,当然在开发中,不推荐使用全面接管SpringMVC


三、配置拦截器

配置拦截器实现登录拦截,需要实现HandlerInterceptor 接口并且实现preHandle方法即可

java 复制代码
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        if (session.getAttribute("loginUser") == null) {
            request.setAttribute("msg", "身份未验证,请先登录");
            request.getRequestDispatcher("/index.html").forward(request, response);
            return false;
        } else {
            return true;
        }
    }
}

在SpirngMVC配置文件中添加拦截器,即可实现登录拦截。(相当于注册拦截器)

java 复制代码
    @Override
    // 重写addInterceptors方法,用于添加拦截器
    public void addInterceptors(InterceptorRegistry registry) {
        // 添加LoginInterceptor拦截器
        registry.addInterceptor(new LoginInterceptor())
                // 拦截所有路径
                .addPathPatterns("/**")
                // 排除指定路径
                .excludePathPatterns("/index.html", "/", "/user/login", "/css/**", "/img/**", "/js/**");
    }
相关推荐
我是无敌小恐龙28 分钟前
Java SE 零基础入门Day01 超详细笔记(开发前言+环境搭建+基础语法)
java·开发语言·人工智能·opencv·spring·机器学习
做个文艺程序员3 小时前
流式输出(SSE)在 Spring Boot 中的实现【OpenClAW + Spring Boot 系列 第3篇】
java·spring boot·后端
云烟成雨TD3 小时前
Spring AI Alibaba 1.x 系列【28】Nacos Skill 管理中心功能说明
java·人工智能·spring
QC·Rex4 小时前
Spring AI MCP Apps 实战:打造聊天与富 UI 融合的智能化应用
人工智能·spring·ui·spring ai·mcp
俺爱吃萝卜4 小时前
Spring Boot 3 + JDK 17:新一代微服务架构最佳实践
java·spring boot·架构
Predestination王瀞潞4 小时前
Java EE3-我独自整合(第七章:Spring AOP 通知类型)
python·spring·java-ee
曹牧4 小时前
Spring :component-scan
java·后端·spring
做个文艺程序员4 小时前
Spring Boot 项目集成 OpenClAW【OpenClAW + Spring Boot 系列 第1篇】
java·人工智能·spring boot·开源
曹牧5 小时前
Spring:@RequestMapping
java·后端·spring
霸道流氓气质5 小时前
SpringBoot+LangChain4j+Ollama实现本地大模型语言LLM的搭建、集成和示例流程
java·spring boot·后端