WebMvcConfigurer用法

WebMvcConfigurer 是 Spring MVC 框架中的一个重要接口,它定义了一系列回调方法,用于自定义基于 Java 的 Spring MVC 配置。当你使用 @EnableWebMvc 注解来启用 Spring MVC 时,可以通过实现 WebMvcConfigurer 接口来自定义默认的 MVC 配置。以下是该接口在使用过程中的一些常见用法及功能:

1. 配置拦截器

拦截器可以在请求处理的前后执行一些操作,例如身份验证、日志记录等。你可以通过实现 addInterceptors 方法来注册拦截器。

java 复制代码
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 注册自定义拦截器
        registry.addInterceptor(new MyInterceptor())
               .addPathPatterns("/**") // 拦截所有请求
               .excludePathPatterns("/login"); // 排除登录请求
    }
}

2. 配置静态资源映射

你可以通过实现 addResourceHandlers 方法来配置静态资源的映射,例如 CSS、JavaScript、图片等。

java 复制代码
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 映射静态资源路径
        registry.addResourceHandler("/static/**")
               .addResourceLocations("classpath:/static/");
    }
}

3. 配置跨域请求处理

跨域请求(CORS)允许浏览器在不同域名之间进行数据交互。你可以通过实现 addCorsMappings 方法来配置跨域请求的处理。

java 复制代码
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
               .allowedOrigins("*") // 允许所有域名进行跨域调用
               .allowedMethods("GET", "POST", "PUT", "DELETE") // 允许的请求方法
               .allowedHeaders("*") // 允许任何请求头
               .allowCredentials(true) // 允许携带凭证
               .maxAge(3600); // 预检请求的有效期,单位为秒
    }
}

4. 配置视图解析器

视图解析器用于将控制器返回的逻辑视图名解析为实际的视图对象。你可以通过实现 configureViewResolvers 方法来配置视图解析器。

java 复制代码
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewResolverRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void configureViewResolvers(ViewResolverRegistry registry) {
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setPrefix("/WEB-INF/views/");
        viewResolver.setSuffix(".jsp");
        registry.viewResolver(viewResolver);
    }
}

5. 配置消息转换器

消息转换器用于将请求中的数据转换为 Java 对象,以及将 Java 对象转换为响应数据。你可以通过实现 configureMessageConverters 方法来配置消息转换器。

java 复制代码
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.ArrayList;
import java.util.List;

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);

        // 处理中文乱码问题
        List<MediaType> mediaTypes = new ArrayList<>();
        mediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
        converter.setSupportedMediaTypes(mediaTypes);

        converter.setFastJsonConfig(fastJsonConfig);
        converters.add(converter);
    }
}

总结

WebMvcConfigurer 接口提供了丰富的回调方法,允许你对 Spring MVC 的各个方面进行自定义配置。通过实现该接口,你可以灵活地定制 Spring MVC 应用的行为,满足不同的业务需求。

相关推荐
IsPrisoner2 小时前
Go语言安装proto并且使用gRPC服务(2025最新WINDOWS系统)
开发语言·后端·golang
tan180°3 小时前
Linux进程信号处理(26)
linux·c++·vscode·后端·信号处理
有梦想的攻城狮4 小时前
spring中的@MapperScan注解详解
java·后端·spring·mapperscan
柚个朵朵5 小时前
Spring的Validation,这是一套基于注解的权限校验框架
java·后端·spring
Asus.Blogs6 小时前
为什么go语言中返回的指针类型,不需要用*取值(解引用),就可以直接赋值呢?
开发语言·后端·golang
C_V_Better6 小时前
Java Spring Boot 控制器中处理用户数据详解
java·开发语言·spring boot·后端·spring
胡子洲6 小时前
Spring Boot 应用中实现基本的 SSE 功能
java·spring boot·后端
贰拾wan6 小时前
【Java-EE进阶】SpringBoot针对某个IP限流问题
java·spring boot·后端·idea
Paran-ia7 小时前
【2025版】Spring Boot面试题
java·spring boot·后端