《精通Spring MVC 4》——2.4 使用Thymeleaf

    xiaoxiao2024-06-06  103

    本节书摘来自异步社区《精通Spring MVC 4》一书中的第2章,第2.4节,作者:【美】Geoffroy Warin著,更多章节内容可以访问云栖社区“异步社区”公众号查看

    2.4 使用Thymeleaf

    Thymeleaf是一个模板引擎,在Spring社区中,它备受关注。

    它的成功在很大程度上要归因于对用户友好的语法(它几乎就是HTML)以及扩展的便利性。

    如表2-1所示,现在有各种可用的扩展,并且能够与Spring Boot进行集成。

    闲言少叙,现在我们将spring-boot-starter-thymeleaf依赖添加进来,这样就能启动Thymeleaf模板引擎了:

    buildscript { ext { springBootVersion = '1.2.5.RELEASE' } repositories { mavenCentral() } dependencies { classpath("org.springframework.boot:spring-boot-gradle- plugin:${springBootVersion}") classpath("io.spring.gradle:dependency-management- plugin:0.5.1.RELEASE") } } apply plugin: 'java' apply plugin: 'eclipse' apply plugin: 'idea' apply plugin: 'spring-boot' apply plugin: 'io.spring.dependency-management' jar { baseName = 'masterSpringMvc' version = '0.0.1-SNAPSHOT' } sourceCompatibility = 1.8 targetCompatibility = 1.8 repositories { mavenCentral() } dependencies { compile 'org.springframework.boot:spring-boot-starter-web' compile 'org.springframework.boot:spring-boot-starter-thymeleaf' testCompile 'org.springframework.boot:spring-boot-starter-test' } eclipse { classpath { containers.remove('org.eclipse.jdt.launching.JRE_CONTAINER') containers 'org.eclipse.jdt.launching.JRE_CONTAINER/org. eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8' } } task wrapper(type: Wrapper) { gradleVersion = '2.3' }

    第一个页面现在,我们将第一个页面添加到应用之中,我们将其放到src/main/resources/templates中,并将其命名为resultPage.html:

    <!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head lang="en"> <meta charset="UTF-8"/> <title>Hello thymeleaf</title> </head> <body> <span th:text="|Hello thymeleaf|">Hello html</span> </body> </html>

    我们首先能够看到Thymeleaf与HTML结合得非常好,它的语法看上去也非常自然。

    th:text的值放在两个竖线中间,这意味着文本中所有的值都会连接在一起。

    看上去,这可能有点怪异,但实际上,我们很少在页面中进行硬编码,因此,Thymeleaf在这里采用了具有一定倾向性的设计。

    对于Web设计人员来说,Thymeleaf有一项很大的优势,那就是在服务器没有运行的时候,模板中所有的动态内容都可以采用一个默认值。资源URL可以采用相对的路径来指定,每个标签都可以包含占位符。在前面的样例里面,如果是在应用的上下文中,那么文本“Hello html”将不会显示,但是如果直接在Web浏览器中打开这个文件的话,那么它就会显示了。

    为了加快开发速度,在application.properties文件中添加该属性:

    spring.thymeleaf.cache=false这将会禁止启用视图缓存,每次访问的时候都会重新加载模板。

    当然,在部署到生产环境时,该项配置需要禁用。在第8章时,我们会再进行设置。

    如果禁用了缓存,在修改视图之后,只需在Eclipse中进行保存或者在IntelliJ中使用Build > Make Project操作就可以刷新视图。最后,需要修改HelloController类,它必须要导航至我们新建的视图,而不是展现简单的文本。为了完成该功能,需要移除@ResponseBody注解。这样做完之后,如果再次返回字符串的话,就会告诉Spring MVC要将这个字符串映射为视图名,而不是在响应中直接展现特定的模型。

    我们的控制器将会变为如下所示:

    @Controller public class HelloController { @RequestMapping("/") public String hello() { return "resultPage"; } }

    在本例中,控制器会将用户转移到名为resultPage的视图中,ViewResolver接口会将这个名字与我们的视图进行关联。

    再次启动应用并转至http://localhost:8080。

    你将会看到如图2-2所示的页面。

    图2-2

    相关资源:敏捷开发V1.0.pptx
    最新回复(0)