spring boot 学习(配置页面模版)

此文做记录交流,如有不当,还望指正。

配置freemarker

SpringBoot配置freemarker非常简单,我们只用在pom中添加freemarker依赖就ok了,SpringBoot默认的freemarker的页面位置位于 /src/main/resources/templates下面

首先添加依赖

     <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
      <modelVersion>4.0.0</modelVersion>
    
      <groupId>com.demo</groupId>
      <artifactId>springboot-helloword</artifactId>
      <version>0.0.1-SNAPSHOT</version>
      <packaging>jar</packaging>
      <name>springboot-helloword</name>
      <url>http://maven.apache.org</url>
      <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
      </properties>
      <parent>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-parent</artifactId>
         <version>1.4.0.RELEASE</version>
      </parent>
      <dependencies>
        <dependency>
           <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-freemarker</artifactId>
        </dependency>


        <dependency>
          <groupId>junit</groupId>
          <artifactId>junit</artifactId>
          <scope>test</scope>
        </dependency>
      </dependencies>
    </project>

在resources下面创建templates文件夹,并且在文件夹下面创建一个hello.ftl的文件


image.png

在hello.ftl 中添加


image.png

在controller中调用页面模版
package com.demo.springboot_helloword.web;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    
    @Controller
    public class HelloController {
        @RequestMapping("/hello")
        public String hello(){
            return "hello";
        }
    }

启动项目访问http://localhost:8080/hello看看效果

配置其他模版的方式和配置freemarker的方式是一样的,Spring boot 支持 Thymeleaf FreeMarker Velocity Groovy Mustache

静态资源配置

Spring Boot 默认配置的/映射到/static(或/public ,/resources,/META-INF/resources),/webjars/会映射到classpath:/META-INF/resources/webjars/。
上面的 /public /resources /META-INF/resource 都位于classpath:下面,如 /src/main/resources/static
静态资源我们一般会放在/static 下面,
比如我们在static中创建img文件夹,后在里面放一张名为logo.png的图片

image.png

启动项目访问http://localhost:8080/img/logo.png看看效果

使用WebJars

添加jquery依赖:
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>1.11.3</version>
</dependency>
然后可以如下使用:
<script type="text/javascript" src="/webjars/jquery/1.11.3/jquery.js"></script>
你可能注意到href中的1.11.3版本号了,如果仅仅这么使用,那么当我们切换版本号的时候还要手动修改href,怪麻烦的,我们可以用如下方式解决。

先在pom.xml中添加依赖:

<dependency>
    <groupId>org.webjars</groupId>
    <artifactId>webjars-locator</artifactId>
</dependency>

增加一个WebJarController

@Controller
public class WebJarController {
    private final WebJarAssetLocator assetLocator = new WebJarAssetLocator();

    @ResponseBody
    @RequestMapping("/webjarslocator/{webjar}/**")
    public ResponseEntity locateWebjarAsset(@PathVariable String webjar, HttpServletRequest request) {
        try {
            String mvcPrefix = "/webjarslocator/" + webjar + "/";
            String mvcPath = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
            String fullPath = assetLocator.getFullPath(webjar, mvcPath.substring(mvcPrefix.length()));
            return new ResponseEntity(new ClassPathResource(fullPath), HttpStatus.OK);
        } catch (Exception e) {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
    }
}

然后使用的时候按照如下方式:

<script type="text/javascript" src="/webjarslocator/jquery/jquery.js"></script>

注意:这里不需要在写版本号了,但是注意写url的时候,只是在原来url基础上去掉了版本号,其他的都不能少!

静态资源版本管理

Spring MVC 提供了静态资源版本映射的功能。

用途:当我们资源内容发生变化时,由于浏览器缓存,用户本地的静态资源还是旧的资源,为了防止这种情况导致的问题,我们可能会手动在请求url的时候加个版本号或者其他方式。

版本号如:

<script type="text/javascript" src="/js/sample.js?v=1.0.1"></script>

Spring MVC 提供的功能可以很容易的帮助我们解决类似问题。

Spring MVC 有两种解决方式。

注意:下面的配置方式针对freemarker模板方式,其他的配置方式可以参考。

资源名-md5 方式

例如:

<link rel="stylesheet" type="text/css" href="/css/index-2b371326aa93ce4b611853a309b69b29.css">

Spring 会自动读取资源md5,然后添加到index.css的名字后面,因此当资源内容发生变化的时候,文件名发生变化,就会更新本地资源。

配置方式:

application.properties中做如下配置:

spring.resources.chain.strategy.content.enabled=true
spring.resources.chain.strategy.content.paths=/**

这样配置后,所有/**请求的静态资源都会被处理为上面例子的样子。

到这儿还没完,我们在写资源url的时候还要特殊处理。

首先增加如下配置:

@ControllerAdvice
public class ControllerConfig {

    @Autowired
    ResourceUrlProvider resourceUrlProvider;

    @ModelAttribute("urls")
    public ResourceUrlProvider urls() {
        return this.resourceUrlProvider;
    }

}

然后在页面写的时候用下面的写法:

<link rel="stylesheet" type="text/css" href="${urls.getForLookupPath('/css/index.css')}">

使用urls.getForLookupPath('/css/index.css')来得到处理后的资源名。

版本号 方式

application.properties中做如下配置:

spring.resources.chain.strategy.fixed.enabled=true
spring.resources.chain.strategy.fixed.paths=/js/**,/v1.0.0/**
spring.resources.chain.strategy.fixed.version=v1.0.0

这里配置需要特别注意,将version的值配置在paths中。原因我们在讲Spring MVC 处理逻辑的时候说。

在页面写的时候,写法如下:

<script type="text/javascript" src="${urls.getForLookupPath('/js/index.js')}"></script>

注意,这里仍然使用了urls.getForLookupPathurls配置方式见上一种方式。

在请求的实际页面中,会显示为:

<script type="text/javascript" src="/v1.0.0/js/index.js"></script>

可以看到这里的地址是/v1.0.0/js/index.js

静态资源版本管理 处理过程

在Freemarker模板首先会调用urls.getForLookupPath方法,返回一个/v1.0.0/js/index.js/css/index-2b371326aa93ce4b611853a309b69b29.css

这时页面上的内容就是处理后的资源地址。

这之后浏览器发起请求。

这里分开说。

第一种md5方式

请求/css/index-2b371326aa93ce4b611853a309b69b29.css,我们md5配置的paths=/**,所以Spring MVC 会尝试url中是否包含-,如果包含会去掉后面这部分,然后去映射的目录(如/static/)查找/css/index.css文件,如果能找到就返回。

第二种版本方式

请求/v1.0.0/js/index.js

如果我们paths中没有配置/v1.0.0,那么上面这个请求地址就不会按版本方式来处理,因此会找不到上面的资源。

如果配置了/v1.0.0,Spring 就会将/v1.0.0去掉再去找/js/index.js,最终会在/static/下面找到。

下面是模版的配置,引用使用Spring Boot开发WEB页面

mvc

spring.mvc.async.request-timeout
设定async请求的超时时间,以毫秒为单位,如果没有设置的话,以具体实现的超时时间为准,比如tomcat的servlet3的话是10秒.
spring.mvc.date-format
设定日期的格式,比如dd/MM/yyyy.
spring.mvc.favicon.enabled
是否支持favicon.ico,默认为: true
spring.mvc.ignore-default-model-on-redirect
在重定向时是否忽略默认model的内容,默认为true
spring.mvc.locale
指定使用的Locale.
spring.mvc.message-codes-resolver-format
指定message codes的格式化策略(PREFIX_ERROR_CODE,POSTFIX_ERROR_CODE).

view

spring.view.prefix
设定mvc视图的前缀.
spring.view.suffix
设定mvc视图的后缀.

resource

spring.resources.add-mappings
是否开启默认的资源处理,默认为true
spring.resources.cache-period
设定资源的缓存时效,以秒为单位.
spring.resources.chain.cache
是否开启缓存,默认为: true
spring.resources.chain.enabled
是否开启资源 handling chain,默认为false
spring.resources.chain.html-application-cache
是否开启h5应用的cache manifest重写,默认为: false
spring.resources.chain.strategy.content.enabled
是否开启内容版本策略,默认为false
spring.resources.chain.strategy.content.paths
指定要应用的版本的路径,多个以逗号分隔,默认为:[/**]
spring.resources.chain.strategy.fixed.enabled
是否开启固定的版本策略,默认为false
spring.resources.chain.strategy.fixed.paths
指定要应用版本策略的路径,多个以逗号分隔
spring.resources.chain.strategy.fixed.version
指定版本策略使用的版本号
spring.resources.static-locations
指定静态资源路径,默认为classpath:[/META-INF/resources/,/resources/, /static/, /public/]以及context:/

freemarker

spring.freemarker.allow-request-override
指定HttpServletRequest的属性是否可以覆盖controller的model的同名项
spring.freemarker.allow-session-override
指定HttpSession的属性是否可以覆盖controller的model的同名项
spring.freemarker.cache
是否开启template caching.
spring.freemarker.charset
设定Template的编码.
spring.freemarker.check-template-location
是否检查templates路径是否存在.
spring.freemarker.content-type
设定Content-Type.
spring.freemarker.enabled
是否允许mvc使用freemarker.
spring.freemarker.expose-request-attributes
设定所有request的属性在merge到模板的时候,是否要都添加到model中.
spring.freemarker.expose-session-attributes
设定所有HttpSession的属性在merge到模板的时候,是否要都添加到model中.
spring.freemarker.expose-spring-macro-helpers
设定是否以springMacroRequestContext的形式暴露RequestContext给Spring’s macro library使用
spring.freemarker.prefer-file-system-access
是否优先从文件系统加载template,以支持热加载,默认为true
spring.freemarker.prefix
设定freemarker模板的前缀.
spring.freemarker.request-context-attribute
指定RequestContext属性的名.
spring.freemarker.settings
设定FreeMarker keys.
spring.freemarker.suffix
设定模板的后缀.
spring.freemarker.template-loader-path
设定模板的加载路径,多个以逗号分隔,默认: ["classpath:/templates/"]
spring.freemarker.view-names
指定使用模板的视图列表.

velocity

spring.velocity.allow-request-override
指定HttpServletRequest的属性是否可以覆盖controller的model的同名项
spring.velocity.allow-session-override
指定HttpSession的属性是否可以覆盖controller的model的同名项
spring.velocity.cache
是否开启模板缓存
spring.velocity.charset
设定模板编码
spring.velocity.check-template-location
是否检查模板路径是否存在.
spring.velocity.content-type
设定ContentType的值
spring.velocity.date-tool-attribute
设定暴露给velocity上下文使用的DateTool的名
spring.velocity.enabled
设定是否允许mvc使用velocity
spring.velocity.expose-request-attributes
是否在merge模板的时候,将request属性都添加到model中
spring.velocity.expose-session-attributes
是否在merge模板的时候,将HttpSession属性都添加到model中
spring.velocity.expose-spring-macro-helpers
设定是否以springMacroRequestContext的名来暴露RequestContext给Spring’s macro类库使用
spring.velocity.number-tool-attribute
设定暴露给velocity上下文的NumberTool的名
spring.velocity.prefer-file-system-access
是否优先从文件系统加载模板以支持热加载,默认为true
spring.velocity.prefix
设定velocity模板的前缀.
spring.velocity.properties
设置velocity的额外属性.
spring.velocity.request-context-attribute
设定RequestContext attribute的名.
spring.velocity.resource-loader-path
设定模板路径,默认为: classpath:/templates/
spring.velocity.suffix
设定velocity模板的后缀.
spring.velocity.toolbox-config-location
设定Velocity Toolbox配置文件的路径,比如 /WEB-INF/toolbox.xml.
spring.velocity.view-names
设定需要解析的视图名称.

thymeleaf

spring.thymeleaf.cache
是否开启模板缓存,默认true
spring.thymeleaf.check-template-location
是否检查模板路径是否存在,默认true
spring.thymeleaf.content-type
指定Content-Type,默认为: text/html
spring.thymeleaf.enabled
是否允许MVC使用Thymeleaf,默认为: true
spring.thymeleaf.encoding
指定模板的编码,默认为: UTF-8
spring.thymeleaf.excluded-view-names
指定不使用模板的视图名称,多个以逗号分隔.
spring.thymeleaf.mode
指定模板的模式,具体查看StandardTemplateModeHandlers,默认为: HTML5
spring.thymeleaf.prefix
指定模板的前缀,默认为:classpath:/templates/
spring.thymeleaf.suffix
指定模板的后缀,默认为:.html
spring.thymeleaf.template-resolver-order
指定模板的解析顺序,默认为第一个.
spring.thymeleaf.view-names
指定使用模板的视图名,多个以逗号分隔.

groovy模板

spring.groovy.template.allow-request-override
指定HttpServletRequest的属性是否可以覆盖controller的model的同名项
spring.groovy.template.allow-session-override
指定HttpSession的属性是否可以覆盖controller的model的同名项
spring.groovy.template.cache
是否开启模板缓存.
spring.groovy.template.charset
指定Template编码.
spring.groovy.template.check-template-location
是否检查模板的路径是否存在.
spring.groovy.template.configuration.auto-escape
是否在渲染模板时自动排查model的变量,默认为: false
spring.groovy.template.configuration.auto-indent
是否在渲染模板时自动缩进,默认为false
spring.groovy.template.configuration.auto-indent-string
如果自动缩进启用的话,是使用SPACES还是TAB,默认为: SPACES
spring.groovy.template.configuration.auto-new-line
渲染模板时是否要输出换行,默认为false
spring.groovy.template.configuration.base-template-class
指定template base class.
spring.groovy.template.configuration.cache-templates
是否要缓存模板,默认为true
spring.groovy.template.configuration.declaration-encoding
在写入declaration header时使用的编码
spring.groovy.template.configuration.expand-empty-elements
是使用
这种形式,还是
</br>这种展开模式,默认为: false)
spring.groovy.template.configuration.locale
指定template locale.
spring.groovy.template.configuration.new-line-string
当启用自动换行时,换行的输出,默认为系统的line.separator属性的值
spring.groovy.template.configuration.resource-loader-path
指定groovy的模板路径,默认为classpath:/templates/
spring.groovy.template.configuration.use-double-quotes
指定属性要使用双引号还是单引号,默认为false
spring.groovy.template.content-type
指定Content-Type.
spring.groovy.template.enabled
是否开启groovy模板的支持.
spring.groovy.template.expose-request-attributes
设定所有request的属性在merge到模板的时候,是否要都添加到model中.
spring.groovy.template.expose-session-attributes
设定所有request的属性在merge到模板的时候,是否要都添加到model中.
spring.groovy.template.expose-spring-macro-helpers
设定是否以springMacroRequestContext的形式暴露RequestContext给Spring’s macro library使用
spring.groovy.template.prefix
指定模板的前缀.
spring.groovy.template.request-context-attribute
指定RequestContext属性的名.
spring.groovy.template.resource-loader-path
指定模板的路径,默认为: classpath:/templates/
spring.groovy.template.suffix
指定模板的后缀
spring.groovy.template.view-names
指定要使用模板的视图名称.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,242评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,769评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,484评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,133评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,007评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,080评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,496评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,190评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,464评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,549评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,330评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,205评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,567评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,889评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,160评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,475评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,650评论 2 335

推荐阅读更多精彩内容