Spring MVC的静态资源映射

一 点睛

Spring MVC的定制配置需要配置类继承WebMvcConfigurerAdapter类,并在此类使用@EnableWebMvc,来开启对Spring MVC的配置支持,这样就可以重写这个类的方法,完成常用的配置。

程序的静态文件(js、css、图片)等需要直接访问,这时可以在配置文件中重写addResourceHandlers方法来实现、

二 实战

1 添加资源文件

在src/main/resources下建立assets/js目录,并复制一个jquery.js放在此目录下。

2 配置代码

package com.wisely.highlight_springmvc4;

import java.util.List;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;

import com.wisely.highlight_springmvc4.interceptor.DemoInterceptor;
import com.wisely.highlight_springmvc4.messageconverter.MyMessageConverter;

@Configuration
@EnableWebMvc// 开启Spring MVC的支持,如果没这句,重写WebMvcConfigurerAdapter方法将无效。
@EnableScheduling
@ComponentScan("com.wisely.highlight_springmvc4")
// 继承WebMvcConfigurerAdapter类,重写该类的方法可对Spring MVC进行配置
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) {
        //addResourceLocations指的是资源文件放置的目录
        //addResourceHandler是对外暴露的访问路径
        registry.addResourceHandler("/assets/**").addResourceLocations(
                "classpath:/assets/");

    }
}

猜你喜欢

转载自blog.csdn.net/chengqiuming/article/details/81709598