3.Spring Boot的Web开发

来源:互联网 发布:开发一套软件多少钱 编辑:程序博客网 时间:2024/05/21 11:29

3.1 Spring Boot的Web开发支持

Spring boot提供了spring-boot-starter-web为web开发给以支持,spring-boot-starter-web提供了内嵌的tomcat以及springmvc的依赖。而web相关的自动配置是在spring-boot-autoconfigure.jar的web下。例如:
ServerPropertiesAutoConfiguration和ServerProperties自动配置内嵌的servlet容器
MultipartAutoConfiguration和MultipartProperties用来自动配置上传文件的属性
WebMvcAutoConfiguration和WebMvcProperties用来配置spring mvc。

3.2 Thymeleaf模板引擎

因为jsp在内嵌的servlet容器上运行有一些问题(内嵌的tomcat、jetty不支持以jar形式运行jsp,undertow不支持jsp),所以Spring boot提供了大量的模板引擎,包括FreeMarker,Groovy,Thymeleaf等等,spring boot也可以通过配置支持jsp的使用,但Spring Boot中推荐使用Thymeleaf作为模板引擎,因为Thymeleaf提供了完美的Spring MVC的支持。

1.Thymeleaf基础知识

Thymeleaf是一个java类库,它是一个xml/xhtml/html5的模板引擎,可以作为MVC的web应用的view层。Thymeleaf还提供了额外的模块与Spring MVC集成,所以我们可以使用Thymeleaf完全代替JSP。基本语法:

(1).引入Thymeleaf模板:xmlns:th=http://www.thymeleaf.org命名空间,将镜头页面转换为动态的视图。需要进行动态处理的元素将使用”:th”为前缀;
(2).通过"@{}"应用web静态资源,这在jsp下是极易出错的;
(3).通过"${}"访问model中的属性,这和jsp相似,比如: th:text="${xxx}"
(4).使用th:each来循环迭代,如:th:each=”a:${AA}”,a作为迭代元素来使用;
(5).数据判断:通过${not #lists.isEmpty(xxx)}表达式来判断xxx是否为空。Thymeleaf支持>,<,>=,<=,==,!=作为判断条件,同时也支持将SpringEL表达式语音用于条件中。
(6).通过th:inline=”javascript”,这样javascript代码即可访问model中的属性了,通过”[[${xxx}]]”格式就可以获得实际的值。

其他更多更完整的Thymeleaf语法,请查看http://www.thymeleaf.org的官网。

2.与Spring mvc集成

在Spring MVC中,若我们需要集成一个模板引擎的话,需要定义ViewResolver,view。庆幸的是,Thymeleaf为我们定义好了org.thymeleaf.spring4.view.ThymeleafView和org.thymeleaf.spring.view.ThymeleafViewResolver(默认使用Thymeleaf作为View)。Thymeleaf也给我们提供了一个SpringTemplateEngine类,用来驱动在Spring MVC下使用Thymeleaf模板引擎,另外还提供了一个TemplateResoler用来设置通用的模板引擎(包括前缀,后缀等),这使集成Thymeleaf引擎变得十分简单。

3.Spring Boot的Thymeleaf支持

Spring boot通过org.springframework.boot.autoconfigure.thymeleaf包对Thymeleaf进行了自动配置。如下图:
这里写图片描述
通过ThemeleafAutoConfiguration类对集成所需要的Bean进行自动配置,包括templateResolver、templateEngine和thymeleafViewResolver的配置。
通过ThymeleafProperties来配置Thymeleaf,在application.properties中,以spring.thymeleaf开头来配置,通过查看源码,我们可以看出如何设置属性以及默认值配置:

这里写图片描述

4.实战演示
(1).如果是在之前的spring boot项目上改进的话,直接引入thymeleaf的依赖,如下图:
这里写图片描述
如果是新建spring boot项目,直接选择spring-boot-starter-thymeleaf,它会自动包含spring-boot-starter-web。

(2).spring boot项目的脚本样式、图片等静态文件默认应放在src/main/resources/static,页面应放在src/main/resource/templates下,现在我们新建一个index.html,如下:

这里写图片描述

(3).执行类代码如下:
这里写图片描述

(4).执行效果如下:

这里写图片描述

原创粉丝点击