spring boot之spring mvc常用配置-静态资源映射(3)

spring mvc常用配置-静态资源映射
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
	
	
	
	
	
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值