SpringBoot笔记(三):静态资源和动态模板

SSM中的静态资源配置

Spring xml中通过mvc:resource节点配置静态资源:

<mvc:resources mapping="/js/**" location="/js/"/>
<mvc:resources mapping="/css/**" location="/css/"/>
<mvc:resources mapping="/html/**" location="/html/"/>

还有一种简化的配置风格:

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

除了xml配置还可以通过java代码来配置静态资源:

@Configuration
public class SpringMVCConfig extends WebMvcConfigurationSupport {
    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**").addResourceLocations("/");
    }
}

只需定义一个类继承WebMvcConfigurationSupport,重写addResourceHandlers方法即可。

SpringBoot中静态资源配置

通常我们创建SpringBoot项目时resources资源目录下会创建static的目录,这个目录默认存放静态资源。但是静态资源就只能存在再static目录中吗?下面我们来看下SpringBoot中默认存放静态资源的目录及如何自定义存放目录。

默认存放位置

  • classpath:/META-INF/resources/
  • classpath:/resources/
  • classpath:/static/
  • classpath:/public/
  • /

源码分析

在这里插入图片描述
this.mvcProperties.getStaticPathPattern()对应的目录是/,下面的getResourceLocations方法另外加入其他四个目录。
访问路径: 启动项目,端口号8080,当我们在static目录下存放图片a.jpg时,此时的访问路径为:

http://location:8080/a.jpg

就是因为使用的默认配置目录,自动去static目录下寻找,此时如果在路径上加static反而会报404的错误。

自定义位置

除了默认的目录位置,还可以在配置文件中自定义静态资源的存放目录

#  自定义目录
spring.resources.static-locations=classpath:/
#  访问路径
spring.mvc.static-path-pattern=/**

动态模板

SpringBoot并不自带支持JSP,需要我们自己进行配置,在现在的Web开发中JSP也使用的越来越少,SpringBoot自动支持Thymeleaf 和reemarker。下面我们就来看看

整合Thymeleaf

依赖:

# 动态模板
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

# web开发
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

其实此时我们就可以使用thymeleaf动态模板了不需要任何配置,动态模板默认存放在template目录下,以.html结尾。下面我们来稍微了解一下为什么就可以直接使用了,此处涉及到SpringBoot的自动化配置,在后面的学习中我们还会专门讲到。
首先看下thymeleaf的自动化配置类org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration

@Configuration
@EnableConfigurationProperties(ThymeleafProperties.class)
@ConditionalOnClass({ TemplateMode.class, SpringTemplateEngine.class })
@AutoConfigureAfter({ WebMvcAutoConfiguration.class, WebFluxAutoConfiguration.class })
public class ThymeleafAutoConfiguration {
}

@Confoguration说明这是一个配置类
@EnableConfigurationProperties引入ThymeleafProperties的属性配置并使其生效
@ConditionalOnClass条件注解,必须在以下类存在的情况下才能生效,即引入thymeleaf依赖
@AutoConfigureAfter 控制加载顺序,在WebMvcAutoConfiguration,WebFluxAutoConfiguration之后被加载

再来看看ThymeleafProperties类中配置了哪些属性:

@ConfigurationProperties(prefix = "spring.thymeleaf")
public class ThymeleafProperties {
        private static final Charset DEFAULT_ENCODING = StandardCharsets.UTF_8;
        public static final String DEFAULT_PREFIX = "classpath:/templates/";
        public static final String DEFAULT_SUFFIX = ".html";
        private boolean checkTemplate = true;
        private boolean checkTemplateLocation = true;
        private String prefix = DEFAULT_PREFIX;
        private String suffix = DEFAULT_SUFFIX;
        private String mode = "HTML";
        private Charset encoding = DEFAULT_ENCODING;
        private boolean cache = true;
        //...
}

@ConfigurationProperties 对应配置文件中的配置,需要修改时我们只要改spring.thymeleaf开头的属性即可。类中默认定义了存放位置、文件后缀等。

定义Controller:

@Controller
public class IndexController {
    @GetMapping("/index")
    public String index(Model model) {
        List<User> users = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            User u = new User();
            u.setId((long) i);
            u.setName("javaboy:" + i);
            u.setAddress("深圳:" + i);
            users.add(u);
        }
        model.addAttribute("users", users);
        return "index";
    }
}
public class User {
    private Long id;
    private String name;
    private String address;
    //省略 getter/setter
}

此时只要在template中定义一个index.html文件,引入thymeleaf语法即可。thymeleaf语法参考:https://www.thymeleaf.org

Freemarker

依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

自动化配置同理于thymeleaf此处就不多做赘述,直接上源码:

@Configuration
@ConditionalOnClass({ freemarker.template.Configuration.class, FreeMarkerConfigurationFactory.class })
@EnableConfigurationProperties(FreeMarkerProperties.class)
@Import({ FreeMarkerServletWebConfiguration.class, FreeMarkerReactiveWebConfiguration.class,
                FreeMarkerNonWebConfiguration.class })
public class FreeMarkerAutoConfiguration {
}
@ConfigurationProperties(prefix = "spring.freemarker")
public class FreeMarkerProperties extends AbstractTemplateViewResolverProperties {
        public static final String DEFAULT_TEMPLATE_LOADER_PATH = "classpath:/templates/";
        public static final String DEFAULT_PREFIX = "";
        public static final String DEFAULT_SUFFIX = ".ftl";
        /**
         * Well-known FreeMarker keys which are passed to FreeMarker's Configuration.
         */
        private Map<String, String> settings = new HashMap<>();
}

如需自定义配置,只需改动spring.freemarker开头的属性即可。

posted @ 2022-03-02 15:35  浪淘沙V  阅读(183)  评论(0编辑  收藏  举报