SpringMVC无xml文件之静态资源,拦截器配置和@EnableWebMvc

本文主要是介绍SpringMVC无xml文件之静态资源,拦截器配置和@EnableWebMvc,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

文章目录

  • 1 SpringMVC配置
    • 1.1 原项目参考
    • 1.2 静态资源映射
    • 1.3 拦截器配置
    • 1.4 其他配置
    • 1.5 @EnableWebMvc
      • 1.5.1 对spring boot项目影响
      • 1.5.2 @EnableWebMvc、WebMvcConfigurationSupport、WebMvcConfigurationAdapter

1 SpringMVC配置

1.1 原项目参考

一下变更大都是在此无xml基础上整合的
先看原无xml项目地

1.2 静态资源映射

程序的静态文件(js、css等)需要直接访问,这时我们可以在配置里重写addResourceHandler方法,类似于在springmvc的地方配置静态资源放行

由于优雅REST风格的资源URL不希望带.html.do 等后缀.由于早期的Spring MVC不能很好地处理静态资源,所以在web.xml中配置DispatcherServlet的请求映射,往往使用 *.do 、 *.xhtml等方式。这就决定了请求URL必须是一个带后缀的URL,而无法采用真正的REST风格的URL
如果将DispatcherServlet请求映射配置为/,则Spring MVC将捕获Web容器所有的请求,包括静态资源的请求,Spring MVC会将它们当成一个普通请求处理,因此找不到对应处理器将导致错误,所以需要放行静态资源

@Configuration
@EnableWebMvc
@ComponentScan("cn.jzh")
public class MyMvcConfig implements WebMvcConfigurer {/*** 此处相当于web项目中 springmvc.xml文件* @return*/@Beanpublic InternalResourceViewResolver viewResolver (){InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();viewResolver.setPrefix("/WEB-INF/views/");viewResolver.setSuffix(".jsp");viewResolver.setViewClass(JstlView.class);return viewResolver;}/*** 静态资源放行*/@Overridepublic void addResourceHandlers(ResourceHandlerRegistry registry) {//ResourceHandler对外暴露路径  ResourceLocations:资源位置registry.addResourceHandler("/jquery/**").addResourceLocations("classpath*:/WEB-INF/jquery/");}
}

注意:
classpathclasspath*spring加载资源的时候是不同的:

  • classpath:只能加载找到的第一个资源文件
  • classpath*:能加载多个路径下的资源文件

1.3 拦截器配置

拦截器实现一个请求处理前和处理后进行相关业务处理,类似ServletFilter

可以是实现HandlerInterceptor接口或者继承HandlerInterceptorAdapter来实现自定义的拦截器

package cn.jzh.config;import cn.jzh.controller.JspController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;/*** SpringMVC拦截器配置*/
@Component
public class MyMvcInterceptor extends HandlerInterceptorAdapter {private  Logger log = LoggerFactory.getLogger(getClass());@Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {log.info("请求处理器前开始执行。。。。。。");long startTimes = System.currentTimeMillis();request.setAttribute("startTimes",startTimes);return true;}@Overridepublic void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {log.info("请求处理器后开始执行。。。。。。");long endTimes = System.currentTimeMillis();long startTimes = (Long)request.getAttribute("startTimes");request.removeAttribute("startTimes");long handTimes = endTimes - startTimes;log.info("本次请求处理时间:{}",handTimes);}
}

配置到springmvc相关配置中去

package cn.jzh.config;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.*;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;@Configuration
@EnableWebMvc
@ComponentScan("cn.jzh")
public class MyMvcConfig implements WebMvcConfigurer {@Autowiredprivate MyMvcInterceptor interceptor;/*** 此处相当于web项目中 springmvc.xml文件* @return*/@Beanpublic InternalResourceViewResolver viewResolver (){InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();viewResolver.setPrefix("/WEB-INF/views/");viewResolver.setSuffix(".jsp");viewResolver.setViewClass(JstlView.class);return viewResolver;}/*** 拦截器部分*/@Overridepublic void addInterceptors(InterceptorRegistry registry) {registry.addInterceptor(interceptor);}
}

1.4 其他配置

视图层配置ViewController
在项目开发过程中,经常会涉及页面跳转问题,而且这个页面跳转没有任何业务逻辑过程,只是单纯的路由过程 ( 点击一个按钮跳转到一个页面 )
常规写法如下:

@RequestMapping("/toview")public String view(){return "view";}

如果项目中有很多类似的无业务逻辑跳转过程,那样会有很多类似的代码

那么如何可以简单编写,这种代码?
Spring MVC中提供了一个方法,可以把类似代码统一管理,减少类似代码的书写(根据项目要求,或者代码规范,不一定非要统一管理页面跳转,有时会把相同业务逻辑的代码放在一个类中)
在实现WebMvcConfigurer的MyMvcConfig类中重载addViewControllers

  @Overridepublic void addViewControllers(ViewControllerRegistry registry) {registry.addViewController("/toview").setViewName("/view");//添加更多}

以上代码等效于第一种写法

1.5 @EnableWebMvc

1.5.1 对spring boot项目影响

假如是springboot项目,springboot默认可以访问以下路径文件:

  • classpath:/static
  • classpath:/public
  • classpath:/resources
  • classpath:/META-INF/resources

当使用了@EnableWebMvc时,默认的静态资源访问无效了因为默认情况下mvc使用的配置是WebMvcAutoConfiguration,加入该配置变成了WebMvcConfigurationSupport

1.5.2 @EnableWebMvc、WebMvcConfigurationSupport、WebMvcConfigurationAdapter

@EnableWebMvc=WebMvcConfigurationSupport,使用了@EnableWebMvc注解等于扩展了WebMvcConfigurationSupport但是没有重写任何方法
看源码如下:
同时可以看下@EnableWebMvc源码

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
@Import(DelegatingWebMvcConfiguration.class)
public @interface EnableWebMvc {
}

其中@Import(DelegatingWebMvcConfiguration.class)为该注解的核心,

@Configuration
public class DelegatingWebMvcConfiguration extends WebMvcConfigurationSupport {
private final WebMvcConfigurerComposite configurers = new WebMvcConfigurerComposite();@Autowired(required = false)
public void setConfigurers(List<WebMvcConfigurer> configurers) {if (!CollectionUtils.isEmpty(configurers)) {this.configurers.addWebMvcConfigurers(configurers);}
}

可以看到,该类DelegatingWebMvcConfiguration也是WebMvcConfigurationSupport的子类,但是相对而言,添加了自己的扩展配置,同时从setConfigurers可以看到,所有WebMvcConfigurer的子类也会被添加到配置中

各个组合搭配情况:

  • @EnableWebMvc+extends WebMvcConfigurationAdapter,在扩展的类中重写父类的方法即可,这种方式会屏蔽springbootWebMvcAutoConfiguration中的设置
  • @EnableWebMvc+extends WebMvcConfigurationSupport 只会使用@EnableWebMvc
  • extends WebMvcConfigurationSupport,在扩展的类中重写父类的方法即可,这种方式会屏蔽springboot@WebMvcAutoConfiguration中的设置
  • extends WebMvcConfigurationAdapter,在扩展的类中重写父类的方法即可,这种方式依旧使用springbootWebMvcAutoConfiguration中的设置
  • @EnableWebMvc+implements WebMvcConfigurer的方式可以实现springbootWebMvcAutoConfiguration中的设置的配置加上自己的配置

springboot2.x中,WebMvcConfigurationAdapter已经过时,通过实现接口WebMvcConfigurer可以替代原有规则
在默认情况下,springboot是启用WebMvcAutoConfiguration,这点可以在spring-boot-autoconfigure.jar/META-INF/spring.factories中看到

org.springframework.boot.autoconfigure.EnableAutoConfiguration=org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration
但是打开WebMvcAutoConfiguration可以看到

@Configuration
@ConditionalOnWebApplication
@ConditionalOnClass({ Servlet.class, DispatcherServlet.class,WebMvcConfigurerAdapter.class })
@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE + 10)
@AutoConfigureAfter({ DispatcherServletAutoConfiguration.class,ValidationAutoConfiguration.class })
public class WebMvcAutoConfiguration{
}

其中@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)说明,当没有WebMvcConfigurationSupport对应的bean时,才会使用该配置,所以当我们使用继承WebMvcConfigurationSupport的方式类扩展mvc时,原有的配置则无效。

其中WebMvcConfigurerAdapter,也是WebMvcConfigurer的子类,
这就是为什么我们使用@EnableWebMvc+WebMvcConfigurer的方式可以实现EnableWebMvc的配置加上自己的配置了

这篇关于SpringMVC无xml文件之静态资源,拦截器配置和@EnableWebMvc的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1084919

相关文章

SpringBoot集成图片验证码框架easy-captcha的详细过程

《SpringBoot集成图片验证码框架easy-captcha的详细过程》本文介绍了如何将Easy-Captcha框架集成到SpringBoot项目中,实现图片验证码功能,Easy-Captcha是... 目录SpringBoot集成图片验证码框架easy-captcha一、引言二、依赖三、代码1. Ea

Springboot控制反转与Bean对象的方法

《Springboot控制反转与Bean对象的方法》文章介绍了SpringBoot中的控制反转(IoC)概念,描述了IoC容器如何管理Bean的生命周期和依赖关系,它详细讲解了Bean的注册过程,包括... 目录1 控制反转1.1 什么是控制反转1.2 SpringBoot中的控制反转2 Ioc容器对Bea

Spring Cloud Hystrix原理与注意事项小结

《SpringCloudHystrix原理与注意事项小结》本文介绍了Hystrix的基本概念、工作原理以及其在实际开发中的应用方式,通过对Hystrix的深入学习,开发者可以在分布式系统中实现精细... 目录一、Spring Cloud Hystrix概述和设计目标(一)Spring Cloud Hystr

Keepalived+Nginx双机配置小结

《Keepalived+Nginx双机配置小结》本文主要介绍了Keepalived+Nginx双机配置小结,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面... 目录1.1 软硬件要求1.2 部署前服务器配置调优1.3 Nginx+Keepalived部署1.3

Spring Boot整合消息队列RabbitMQ的实现示例

《SpringBoot整合消息队列RabbitMQ的实现示例》本文主要介绍了SpringBoot整合消息队列RabbitMQ的实现示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的... 目录RabbitMQ 简介与安装1. RabbitMQ 简介2. RabbitMQ 安装Spring

Apache伪静态(Rewrite).htaccess文件详解与配置技巧

《Apache伪静态(Rewrite).htaccess文件详解与配置技巧》Apache伪静态(Rewrite).htaccess是一个纯文本文件,它里面存放着Apache服务器配置相关的指令,主要的... 一、.htAccess的基本作用.htaccess是一个纯文本文件,它里面存放着Apache服务器

springMVC返回Http响应的实现

《springMVC返回Http响应的实现》本文主要介绍了在SpringBoot中使用@Controller、@ResponseBody和@RestController注解进行HTTP响应返回的方法,... 目录一、返回页面二、@Controller和@ResponseBody与RestController

nginx配置多域名共用服务器80端口

《nginx配置多域名共用服务器80端口》本文主要介绍了配置Nginx.conf文件,使得同一台服务器上的服务程序能够根据域名分发到相应的端口进行处理,从而实现用户通过abc.com或xyz.com直... 多个域名,比如两个域名,这两个域名其实共用一台服务器(意味着域名解析到同一个IP),一个域名为abc

JAVA集成本地部署的DeepSeek的图文教程

《JAVA集成本地部署的DeepSeek的图文教程》本文主要介绍了JAVA集成本地部署的DeepSeek的图文教程,包含配置环境变量及下载DeepSeek-R1模型并启动,具有一定的参考价值,感兴趣的... 目录一、下载部署DeepSeek1.下载ollama2.下载DeepSeek-R1模型并启动 二、J

nginx生成自签名SSL证书配置HTTPS的实现

《nginx生成自签名SSL证书配置HTTPS的实现》本文主要介绍在Nginx中生成自签名SSL证书并配置HTTPS,包括安装Nginx、创建证书、配置证书以及测试访问,具有一定的参考价值,感兴趣的可... 目录一、安装nginx二、创建证书三、配置证书并验证四、测试一、安装nginxnginx必须有"-