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

相关文章

java中pdf模版填充表单踩坑实战记录(itextPdf、openPdf、pdfbox)

《java中pdf模版填充表单踩坑实战记录(itextPdf、openPdf、pdfbox)》:本文主要介绍java中pdf模版填充表单踩坑的相关资料,OpenPDF、iText、PDFBox是三... 目录准备Pdf模版方法1:itextpdf7填充表单(1)加入依赖(2)代码(3)遇到的问题方法2:pd

Java Stream流之GroupBy的用法及应用场景

《JavaStream流之GroupBy的用法及应用场景》本教程将详细介绍如何在Java中使用Stream流的groupby方法,包括基本用法和一些常见的实际应用场景,感兴趣的朋友一起看看吧... 目录Java Stream流之GroupBy的用法1. 前言2. 基础概念什么是 GroupBy?Stream

Debian系和Redhat系防火墙配置方式

《Debian系和Redhat系防火墙配置方式》文章对比了Debian系UFW和Redhat系Firewalld防火墙的安装、启用禁用、端口管理、规则查看及注意事项,强调SSH端口需开放、规则持久化,... 目录Debian系UFW防火墙1. 安装2. 启用与禁用3. 基本命令4. 注意事项5. 示例配置R

SpringBoot监控API请求耗时的6中解决解决方案

《SpringBoot监控API请求耗时的6中解决解决方案》本文介绍SpringBoot中记录API请求耗时的6种方案,包括手动埋点、AOP切面、拦截器、Filter、事件监听、Micrometer+... 目录1. 简介2.实战案例2.1 手动记录2.2 自定义AOP记录2.3 拦截器技术2.4 使用Fi

最新Spring Security的基于内存用户认证方式

《最新SpringSecurity的基于内存用户认证方式》本文讲解SpringSecurity内存认证配置,适用于开发、测试等场景,通过代码创建用户及权限管理,支持密码加密,虽简单但不持久化,生产环... 目录1. 前言2. 因何选择内存认证?3. 基础配置实战❶ 创建Spring Security配置文件

Spring Security 单点登录与自动登录机制的实现原理

《SpringSecurity单点登录与自动登录机制的实现原理》本文探讨SpringSecurity实现单点登录(SSO)与自动登录机制,涵盖JWT跨系统认证、RememberMe持久化Token... 目录一、核心概念解析1.1 单点登录(SSO)1.2 自动登录(Remember Me)二、代码分析三、

PyCharm中配置PyQt的实现步骤

《PyCharm中配置PyQt的实现步骤》PyCharm是JetBrains推出的一款强大的PythonIDE,结合PyQt可以进行pythion高效开发桌面GUI应用程序,本文就来介绍一下PyCha... 目录1. 安装China编程PyQt1.PyQt 核心组件2. 基础 PyQt 应用程序结构3. 使用 Q

springboot自定义注解RateLimiter限流注解技术文档详解

《springboot自定义注解RateLimiter限流注解技术文档详解》文章介绍了限流技术的概念、作用及实现方式,通过SpringAOP拦截方法、缓存存储计数器,结合注解、枚举、异常类等核心组件,... 目录什么是限流系统架构核心组件详解1. 限流注解 (@RateLimiter)2. 限流类型枚举 (

Java Thread中join方法使用举例详解

《JavaThread中join方法使用举例详解》JavaThread中join()方法主要是让调用改方法的thread完成run方法里面的东西后,在执行join()方法后面的代码,这篇文章主要介绍... 目录前言1.join()方法的定义和作用2.join()方法的三个重载版本3.join()方法的工作原

Redis MCP 安装与配置指南

《RedisMCP安装与配置指南》本文将详细介绍如何安装和配置RedisMCP,包括快速启动、源码安装、Docker安装、以及相关的配置参数和环境变量设置,感兴趣的朋友一起看看吧... 目录一、Redis MCP 简介二、安www.chinasem.cn装 Redis MCP 服务2.1 快速启动(推荐)2.