欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 房产 > 家装 > SpringBoot-配置Spring MVC

SpringBoot-配置Spring MVC

2025/11/22 20:14:09 来源:https://blog.csdn.net/weixin_53004298/article/details/148384797  浏览:    关键词: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注解

@Configuration
public class MyMvcConfig implements WebMvcConfigurer {}

 为什么不能使用@EnableWebMvc注解

@EnableWebMvc导入了DelegatingWebMvcConfiguration类

DelegatingWebMvcConfiguration又继承了WebMvcConfigurationSupport

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


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


三、配置拦截器

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

public class LoginInterceptor implements HandlerInterceptor {@Overridepublic 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配置文件中添加拦截器,即可实现登录拦截。(相当于注册拦截器)

    @Override// 重写addInterceptors方法,用于添加拦截器public void addInterceptors(InterceptorRegistry registry) {// 添加LoginInterceptor拦截器registry.addInterceptor(new LoginInterceptor())// 拦截所有路径.addPathPatterns("/**")// 排除指定路径.excludePathPatterns("/index.html", "/", "/user/login", "/css/**", "/img/**", "/js/**");}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词