在 Spring Boot 中使用 WebMvcConfigurer

WebMvcConfigurer 是 Spring MVC 提供的一个扩展接口,用于配置 Spring MVC 的各种功能。在 Spring Boot 应用中,通过实现 WebMvcConfigurer 接口,可以定制和扩展默认的 Spring MVC 配置。WebMvcConfigurer 接口提供了一组回调方法,用于配置 Spring MVC 的各种方面,如视图解析器、拦截器、跨域请求、消息转换器等。通过实现这些方法,可以方便地自定义 MVC 配置。

1. 创建配置类

创建一个配置类并实现 WebMvcConfigurer 接口,通常加上 @Configuration 注解使其成为配置类。

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

@Configuration
@EnableWebMvc
public class MyWebMvcConfig implements WebMvcConfigurer {
    // 自定义配置在这里添加
}

2. 配置视图解析器

通过实现 configureViewResolvers 方法,可以自定义视图解析器。

复制代码
import org.springframework.web.servlet.config.annotation.ViewResolverRegistry;

@Override
public void configureViewResolvers(ViewResolverRegistry registry) {
    registry.jsp("/WEB-INF/views/", ".jsp");
}
​

3. 添加拦截器

通过实现 addInterceptors 方法,可以添加拦截器。

复制代码
@Override
public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor(new MyInterceptor())
            .addPathPatterns("/**")
            .excludePathPatterns("/login", "/css/**");
}
  • addInterceptor: 添加自定义拦截器。
  • addPathPatterns: 指定拦截路径。
  • excludePathPatterns: 排除某些路径不拦截。

4. 配置跨域请求

通过实现 addCorsMappings 方法,可以配置跨域请求。

复制代码
@Override
public void addCorsMappings(CorsRegistry registry) {
    registry.addMapping("/api/**")
            .allowedOrigins("http://example.com")
            .allowedMethods("GET", "POST")
            .allowCredentials(true);
}

注意事项

  • 不要继承 WebMvcConfigurationSupport:除非你想完全接管 Spring MVC 配置。否则推荐直接实现 WebMvcConfigurer。
  • 多个配置类:如果有多个类实现了 WebMvcConfigurer,可以使用 @Order 控制顺序。
  • Spring Boot 2.x 及以上兼容性良好:大多数配置开箱即用,无需额外依赖。

5. 添加静态资源处理

通过实现 addResourceHandlers 方法,可以配置静态资源的处理。

复制代码
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/static/**")
            .addResourceLocations("classpath:/static/");
}
​

6. 配置消息转换器

通过实现 configureMessageConverters 方法,可以添加或自定义消息转换器。

复制代码
import org.springframework.http.converter.HttpMessageConverter;

@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    converters.add(new MyCustomMessageConverter());
}
​

权限完整例子

复制代码
import java.util.concurrent.ExecutorService;
import net.hworld.interceptor.AccessInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.support.TaskExecutorAdapter;
import org.springframework.web.servlet.config.annotation.AsyncSupportConfigurer;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration(proxyBeanMethods = false)
public class WebMvcConfig implements WebMvcConfigurer {

  @Autowired
  private AccessInterceptor accessInterceptor;

  @Autowired
  private ExecutorService executorService;

  @Override
  public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor(accessInterceptor).order(2).addPathPatterns("/**")
        .excludePathPatterns("/actuator/**", "/favicon.ico", "/demo/**");
  }

  @Override
  public void configureAsyncSupport(AsyncSupportConfigurer configurer) {
    configurer.setTaskExecutor(new TaskExecutorAdapter(executorService));
  }
}

接口认证

复制代码
/**
 * 权限判断
 */
@Slf4j
@Component
@Order(2)
public class AccessInterceptor implements HandlerInterceptor {

  @Autowired
  private AuthUtils authUtils;

  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
      throws Exception {

    if (handler instanceof HandlerMethod) {
      HandlerMethod method = (HandlerMethod) handler;

      //内网不需要token
      NotVerifyToken notVerifyTokenCls = method.getMethod().getDeclaringClass().getAnnotation(NotVerifyToken.class);
      NotVerifyToken notVerifyTokenMtd = method.getMethod().getAnnotation(NotVerifyToken.class);
      if (notVerifyTokenCls != null || notVerifyTokenMtd != null) {
        return true;
      }

      // 认证
      String authorization = request.getHeader(HttpHeaders.AUTHORIZATION);
      if (StringUtils.isBlank(authorization)){
        authorization = request.getParameter("accessToken");
      }

      if (StringUtils.isNotBlank(authorization)) {
        authorization = authorization.replace("Bearer ", "");
        log.info("authorization is {}", authorization);
        try {
          authUtils.authorize(authorization, false);
        } catch (RuntimeException e) {
          log.warn("token error 401: {},{}", authorization, e.getMessage());
          this.handle401(response, WebResponse.fail(WebResponseCode.AUTH_EXCEPTION));
          return false;
        }
      } else {
        log.warn("token is empty");
        this.handle401(response, WebResponse.fail(WebResponseCode.AUTH_EXCEPTION));
        return false;
      }
    }
    return true;
  }

  void handle401(HttpServletResponse response, WebResponse<Object> webResponse) throws IOException {
    response.setStatus(HttpStatus.OK.value());
    response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
    IOUtils.write(JsonUtil.bean2Json(webResponse), response.getWriter());
    response.getWriter().close();
  }

}

绕开认证注解

复制代码
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface NotVerifyToken {

}
相关推荐
期待のcode8 小时前
前后端分离项目 Springboot+vue 在云服务器上的部署
服务器·vue.js·spring boot
ProgramHan9 小时前
Spring Boot 3.2 新特性:虚拟线程的落地实践
java·jvm·spring boot
源码获取_wx:Fegn089510 小时前
基于 vue智慧养老院系统
开发语言·前端·javascript·vue.js·spring boot·后端·课程设计
毕设源码_郑学姐11 小时前
计算机毕业设计springboot基于HTML5的酒店预订管理系统 基于Spring Boot框架的HTML5酒店预订管理平台设计与实现 HTML5与Spring Boot技术驱动的酒店预订管理系统开
spring boot·后端·课程设计
不吃香菜学java11 小时前
spring-依赖注入
java·spring boot·后端·spring·ssm
南部余额11 小时前
Spring Boot 整合 MinIO:封装常用工具类简化文件上传、启动项目初始化桶
java·spring boot·后端·文件上传·工具类·minio·minioutils
QQ196328847511 小时前
ssm基于Springboot+的球鞋销售商城网站vue
vue.js·spring boot·后端
太空眼睛11 小时前
【MCP】使用SpringBoot基于Streamable-HTTP构建MCP-Server
spring boot·sse·curl·mcp·mcp-server·spring-ai·streamable
幽络源小助理11 小时前
springboot校园车辆管理系统源码 – SpringBoot+Vue项目免费下载 | 幽络源
vue.js·spring boot·后端
幽络源小助理12 小时前
SpringBoot+Vue车票管理系统源码下载 – 幽络源免费项目实战代码
vue.js·spring boot·后端