spring mvc常用配置-静态资源映射
spring mvc的定制配置需要我们的配置类集成一个webmvcConfigurerAdapter类,并在此类使用@EnableWebMvc注解,来
开启对spring mvc的配置支持,这样我们可以重写这个类的方法,完成常用配置。
继承webmvcConfigurerAdapter
1.静态资源映射
让静态文件(js、css、图片)可以直接访问,重写addResourceHandlers方法来实现。
(1)添加静态资源文件。
①@enableWebMvc:开始springmvc支持,如果不开启则重写webmvcConfigurerAdapter内部方法无效。
②继承webmvcConfigurerAdapter,可重写其方法对springmvc进行配置。
spring mvc的定制配置需要我们的配置类集成一个webmvcConfigurerAdapter类,并在此类使用@EnableWebMvc注解,来
开启对spring mvc的配置支持,这样我们可以重写这个类的方法,完成常用配置。
继承webmvcConfigurerAdapter
1.静态资源映射
让静态文件(js、css、图片)可以直接访问,重写addResourceHandlers方法来实现。
(1)添加静态资源文件。
①@enableWebMvc:开始springmvc支持,如果不开启则重写webmvcConfigurerAdapter内部方法无效。
②继承webmvcConfigurerAdapter,可重写其方法对springmvc进行配置。
③addResourceLocations:文件放置的目录,addResourceHandler:对外暴漏的访问路径。
基于前篇的运行环境继承webmvcConfigurerAdapter重写addResourceHandlers
package com.boot.springmvc;
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;
/**
* @Bean
public InternalResourceViewResolver viewResolver();
* 注入InternalResourceViewResolver类:
* 说明:springmvc下有一个接口叫ViewResolver,(我们的viewResolver都实现该接口),实现这个接口要重写
* resolverName(),这个方法的返回值接口View,而view的职责就是使用model、request、response对象,并
* 渲染视图(不一定是html、可能是json、xml、pdf等)给浏览器 。
*
*/
@Configuration
@EnableWebMvc // 1开启默认配置
@EnableScheduling
@ComponentScan("com.boot.springmvc")
public class MyMvcConfig extends WebMvcConfigurerAdapter{//2
@Bean
public InternalResourceViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
//viewResolver.setPrefix("/WEB-INF/classes/views/");//打war后默认编译的路径
viewResolver.setPrefix("/WEB-INF/views/");//使用tomcat7:run插件后要放的位置
viewResolver.setSuffix(".jsp");
viewResolver.setViewClass(JstlView.class);
return viewResolver;
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/assets/**").addResourceLocations("classpath:/assets/");
}// 3
}