使用Spring Boot开发WEB页面

前面一章我们用Spring Boot开发了一个RESTful,本章我们开发一个WEB界面。

目前Spring官方已经不推荐使用JSP来开发WEB了,而是推荐使用如下几种模板引擎来开发:

  • Thymeleaf(Spring官方推荐)
  • FreeMarker
  • Velocity
  • Groovy
  • Mustache

目前业界使用最广泛的还是FreeMaker和Velocity,我现在就以FreeMaker为例,介绍如何和Spring Boot集成。

添加FreeMaker依赖

首先在pom.xml中添加FreeMaker的依赖

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

编写一个welcome.ftl

Spring Boot默认存放模板的路径在src/main/resources/templates,不过我们也可以自行修改,文章最后会有一个Sping MVC的配置文件示例。

<!DOCTYPE html>
<html>
<body>
Hello,${name}.欢迎阅读《${bookTitle}》
</body>
</html>

编写Controller来渲染模板

@Controller
public class HelloController {

    @Value("${userName}")
    private String userName;

    @Value("${bookTitle}")
    private String bookTitle;

    @RequestMapping("/")
    public String index(ModelMap map) {
        // 加入一个属性,用来在模板中读取
        map.addAttribute("name", userName);
        map.addAttribute("bookTitle", bookTitle);
        // return模板文件的名称,对应src/main/resources/templates/welcome.html
        return "welcome";
    }
}

上述代码中的userName和bookTitle我们在application.properties中做了设置

userName=Alex
bookTitle=Spring Boot入门教程

最后启动Spring Boot,输入http://localhost:8080/,页面如下所示

FreeMaker示例

静态资源加载

我们在开发WEB页面的时候,还需要加载很多静态资源,比如js、图片、css等文件,那这些文件应该放在哪里呢?

我们在启动Spring Boot的时候,可以看到控制台输出如下一些信息

2016-09-20 15:18:55.445  INFO 16210 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2016-09-20 15:18:55.445  INFO 16210 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2016-09-20 15:18:55.474  INFO 16210 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]

其中默认配置的 /** 映射到 /static (或/public、/resources、/META-INF/resources)
其中默认配置的 /webjars/** 映射到 classpath:/META-INF/resources/webjars/
PS:上面的 static、public、resources 等目录都在 classpath: 下面(例如 src/main/resources/static)。

假如我们的文件是如下图放置,当我们输入http://localhost:8080/dog.jpg的时候,显示的是哪张图片呢?大家可以自行验证一下,这边先告诉大家Spring Boot的加载顺序是
META-INF/resources > resources > static > public

静态资源加载顺序

小结

Spring Boot为我们WEB开发已经准备好了很多默认的配置,一般来说我们已经够用了,如有需要可自行修改,部分常用配置如下,更多常用的配置可参见SpringBoot常用配置

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/>这种形式,还是<br></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阅读 151,688评论 1 330
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 64,559评论 1 273
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 101,749评论 0 226
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 42,581评论 0 191
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 50,741评论 3 271
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 39,684评论 1 192
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,122评论 2 292
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 29,847评论 0 182
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 33,441评论 0 228
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 29,939评论 2 232
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,333评论 1 242
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 27,783评论 2 236
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,275评论 3 220
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 25,830评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,444评论 0 180
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 34,553评论 2 249
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 34,618评论 2 249

推荐阅读更多精彩内容