1. 程式人生 > >Spring MVC的靜態資源對映

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/");

    }
}