一. 点睛
Spring
MVC
的定制配置需要我们的配置类继承一个WebMvcConfigurerAdapter
类,并在此类使用@EnableWebMvc
注解,来开启对Spring
MVC
的配置支持,这样我们就可以重写这个类的方法,完成我们的常用配置。
我们将前面文章中的MyMvcConfig
配置类继承WebMvcConfigurerAdapter
,以后如果不做特别说明,则关于配置的相关内容都在MyMvcConfig
里面编写。
程序的静态文件(js
,css
,图片)等需要直接访问,这时我们可以在配置里重写addResourceHandlers
方法来实现。
二. 示例
1. 添加静态资源
在src/main/resources
下建立assets/js
目录,并复制一个jquery.js
放置在该目录下,如下图所示:
配置代码:
package org.light4j.springMvc4;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
@Configuration
@EnableWebMvc// ①
@ComponentScan("org.light4j.springMvc4")
public class MyMvcConfig extends WebMvcConfigurerAdapter {// ②
@Bean
public InternalResourceViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/classes/views/");
viewResolver.setSuffix(".jsp");
viewResolver.setViewClass(JstlView.class);
return viewResolver;
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/assets/**").addResourceLocations("classpath:/assets/");// ③
}
}
代码解释:
① @EnableWebMvc
开启SpringMvc
支持,若无此句,重写WebMvcConfigurerAdapter
的方法无效。
② 继承WebMvcConfigurerAdapter
类,重写其方法可对Spring
MVC
进行配置。
③ addResourceLocations
指的是文件放置的目录,addResourceHandler
指的是对外暴露的访问路径。
2. 测试
启动程序,在浏览器输入地址:http://localhost/springMvc4.x-staticResources/assets/js/jquery.js,可以在浏览器直接访问到静态资源。如下图所示:
三. 源代码示例:
公众号ID:longjiazuoA

未经允许不得转载:人生设计师 » SpringMvc4.x基本配置(一):静态资源映射