1.使用tomcat默认的servlet,通常在web.xml文件中激活。代码如下:

<!-- 激活tomcat的defaultservlet拦截静态资源 -->
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.jpg</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.css</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.js</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.png</url-pattern>
</servlet-mapping>

2.使用spring3.0的朋友可以使用springmvc的<mvc:resources/>标签

<mvc:resources location="/static/" mapping="/static/**"/>

3.使用spring提供的标签<mvc:default-servlet-handler/>代码为:

<mvc:default-servlet-handler/>

4.基于spring零配置,在servlet的配置类中实现WebMvcConfigurer接口,重写addResourceHandlers方法

package com.wise.tiger.config;

import ...

@Configuration
@EnableWebMvc
@EnableAspectJAutoProxy
@ComponentScan(basePackages = "com.wise.tiger.web")
public class ServletConfig implements WebMvcConfigurer {
    @Bean
    public InternalResourceViewResolver viewResolver(){
        var viewResolver =new InternalResourceViewResolver();
        viewResolver.setViewClass(org.springframework.web.servlet.view.JstlView.class);
        viewResolver.setPrefix("/WEB-INF/book/");
        viewResolver.setSuffix(".jsp");
        return viewResolver;
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**")//过滤静态资源
                .addResourceLocations("/static/");
    }
}
05-28 22:04