spring boot 中springboot thymeleaff和jsp可以共存吗

转:/blog/2301387,http://-qq-/blog/2292402
整体步骤:
(1)&&&&&&&&&&& 在pom.xml中引入
(2)&&&&&&&&&&& 如何关闭thymeleaf缓存
(3)&&&&&&&&&&& 编写模板文件.html
&Boot默认就是使用thymeleaf模板引擎的,所以只需要在pom.xml加入依赖即可:
Thymeleaf缓存在开发过程中,肯定是不行的,那么就要在开发的时候把缓存关闭,只需要在application.properties进行配置即可:
编写模板文件src/main/resouces/templates/helloHtml.html
编写访问路径(com.kfit.test.web.TemplateController):
启动应用,输入地址:http://127.0.0.1:8080/helloHtml 会输出:
from TemplateController.helloHtml
使用freemarker
使用freemarker也很简单,
在pom.xml加入freemarker的依赖:
剩下的编码部分都是一样的,说下application.properties文件:
com.kfit.test.web.TemplateController:
访问地址:
from TemplateController.helloFtl
thymeleaf和freemarker是可以共存的。
------------------------------------------------------------------------------------------------------------------------------------------------
本文记录一下几点:&
一、资源文件的约定目录结构&
二、Maven配置&
三、开发时修改thymeleaf模板自动重新加载配置&
四、thymeleaf常用基础知识点
一、资源文件的约定目录结构&
Maven的资源文件目录:/src//resources&
spring-boot项目静态文件目录:/src/java/resources/static&
spring-boot项目模板文件目录:/src/java/resources/templates&
spring-boot静态首页的支持,即index.html放在以下目录结构会直接映射到应用的根目录下:
由于使用thymeleaf的模板,所以我将index.html模板文件直接放到了/src/java/resources/templates目录下。然而这个目录并不是首页文件的默认目录,所以我们需要手动将应用根路径映射到/src/java/resources/templates/index.html下。这个在spring-mvc的Controller下映射一下就可以了。
在spring-boot下,默认约定了Controller试图跳转中thymeleaf模板文件的的前缀prefix是”classpath:/templates/”,后缀suffix是”.html”&
这个在application.properties配置文件中是可以修改的。&
如下配置可以修改试图跳转的前缀和后缀
更过有关thymeleaf中的默认这是可以查看org.springframework.boot.autoconfigure.thymeleaf.ThymeleafProperties这个类的属性&
二、Maven配置&
在pom.xml中加入如下依赖&
原来关于spring-boot-starter-web等的依赖就可以去掉了,因为spring-boot-starter-thymeleaf是包含这些依赖的。而关于jsp的依赖也可以去掉了,因为我们已经完全抛弃jsp了。&
三、开发时修改thymeleaf模板自动重新加载配置&
Spring-boot使用thymeleaf时默认是有缓存的,即你把一个页面代码改了不会刷新页面的效果,你必须重新运行spring-boot的main()方法才能看到页面更改的效果。我们可以把thymeleaf的缓存关掉,用于支持页面修改后重新发布到spring-boot内嵌的tomcat中去。在application.properties配置文件中加入以下配置。
四、thymeleaf常用基础知识点&
1、在html页面中引入thymeleaf命名空间,即&html xmlns:th=http://www.thymeleaf.org&&/html&,此时在html模板文件中动态的属性使用th:命名空间修饰&
2、引用静态资源文件,比如CSS和JS文件,语法格式为“@{}”,如@{/js/blog/blog.js}会引入/static目录下的/js/blog/blog.js文件&
3、访问spring-mvc中model的属性,语法格式为“${}”,如${user.id}可以获取model里的user对象的id属性&
4、循环,在html的标签中,加入th:each=“value:${list}”形式的属性,如&span th:each=”user:${users}”&&/span&可以迭代users的数据&
5、判断,在html标签中,加入th:if=”表达式”可以根据条件显示html元素&
&span th:if=&${not #lists.isEmpty(blog.publishTime)}&&&
&span id=&publishtime& th:text=&${#dates.format(blog.publishTime, 'yyyy-MM-dd HH:mm:ss')}&&&/span&&
以上代码表示若blog.publishTime时间不为空,则显示时间&
6、时间的格式化,&
${#dates.format(blog.publishTime,'yyyy-MM-dd HH:mm:ss')}&
表示将时间格式化为”yyyy-MM-dd HH:mm:ss”格式化写法与Java格式化Date的写法是一致的。&
7、字符串拼接,有两种形式&
比如拼接这样一个URL:/blog/delete/{blogId}&
第一种:th:href=&'/blog/delete/' + ${blog.id }&&
第二种:th:href=&${'/blog/delete/' + blog.id }&&
&&相关文章推荐
参考知识库
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
访问:92214次
积分:1543
积分:1543
排名:千里之外
原创:60篇
转载:10篇
评论:15条
(4)(1)(4)(7)(4)(3)(1)(1)(1)(3)(1)(1)(1)(2)(1)(1)(1)(1)(2)(1)(2)(2)(3)(1)(3)(4)(3)(4)(5)(1)(1)(2)点击阅读原文
Spring Boot干货系列:(四)开发Web应用之Thymeleaf篇 | 嘟嘟独立博客
3月13日 发布,来源:
Web开发是我们平时开发中至关重要的,这里就来介绍一下Spring Boot对Web开发的支持。
Spring Boot提供了spring-boot-starter-web为Web开发予以支持,spring-boot-starter-web为我们提供了嵌入的Tomcat以及Spring MVC的依赖。
项目结构推荐
一个好的项目结构会让你开发少一些问题,特别是Spring Boot中启动类要放在root package下面,我的web工程项目结构如下:
root package结构:com.dudu
应用启动类Application.java置于root package下,这样使用@ComponentScan注解的时候默认就扫描当前所在类的package
实体(Entity)置于com.dudu.domain包下
逻辑层(Service)置于com.dudu.service包下
controller层(web)置于com.dudu.controller层包下
static可以用来存放静态资源
templates用来存放默认的模板配置路径
Spring Web MVC框架介绍
Spring Web MVC框架(通常简称为”Spring MVC”)是一个富”模型,视图,控制器”的web框架。Spring MVC允许你创建特定的或 beans来处理传入的HTTP请求。示例:
12345678910111213141516
@RestController@RequestMapping(value="/users")public class MyRestController { @RequestMapping(value="/", method=RequestMethod.GET) public User getUser(@PathVariable Long user) { // ... } @RequestMapping(value="//customers", method=RequestMethod.GET) List&Customer& getUserCustomers(@PathVariable Long user) { // ... } @RequestMapping(value="/", method=RequestMethod.DELETE) public User deleteUser(@PathVariable Long user) { // ... }}
Spring MVC自动配置
Spring Boot为Spring MVC提供适用于多数应用的自动配置功能。在Spring默认基础上,自动配置添加了以下特性:
引入ContentNegotiatingViewResolver和BeanNameViewResolver beans。
对静态资源的支持,包括对WebJars的支持。
自动注册Converter,GenericConverter,Formatter beans。
对HttpMessageConverters的支持。
自动注册MessageCodeResolver。
对静态index.html的支持。
对自定义Favicon的支持。
如果想全面控制Spring MVC,你可以添加自己的@Configuration,并使用@EnableWebMvc对其注解。如果想保留Spring Boot MVC的特性,并只是添加其他的MVC配置(拦截器,formatters,视图控制器等),你可以添加自己的WebMvcConfigurerAdapter类型的@Bean(不使用@EnableWebMvc注解),具体拦截器等配置后续文章会解析。
默认情况下,Spring Boot从classpath下一个叫/static(/public,/resources或/META-INF/resources)的文件夹或从ServletContext根目录提供静态内容。这使用了Spring MVC的ResourceHttpRequestHandler,所以你可以通过添加自己的WebMvcConfigurerAdapter并覆写addResourceHandlers方法来改变这个行为(加载静态文件)。
在一个单独的web应用中,容器默认的servlet是开启的,如果Spring决定不处理某些请求,默认的servlet作为一个回退(降级)将从ServletContext根目录加载内容。大多数时候,这不会发生(除非你修改默认的MVC配置),因为Spring总能够通过DispatcherServlet处理请求。
此外,上述标准的静态资源位置有个例外情况是。任何在/webjars/**路径下的资源都将从jar文件中提供,只要它们以Webjars的格式打包。
注:如果你的应用将被打包成jar,那就不要使用src/main/webapp文件夹。尽管该文件夹是一个共同的标准,但它仅在打包成war的情况下起作用,并且如果产生一个jar,多数构建工具都会静悄悄的忽略它
Spring Boot支持多种模版引擎包括:
FreeMarker
Thymeleaf(官方推荐)
JSP技术Spring Boot官方是不推荐的,原因有三:
tomcat只支持war的打包方式,不支持可执行的jar。
Jetty 嵌套的容器不支持jsp
创建自定义error.jsp页面不会覆盖错误处理的默认视图,而应该使用自定义错误页面
当你使用上述模板引擎中的任何一个,它们默认的模板配置路径为:src/main/resources/templates。当然也可以修改这个路径,具体如何修改,可在后续各模板引擎的配置属性中查询并修改。
Thymeleaf模板引擎
Thymeleaf是一款用于渲染XML/XHTML/HTML5内容的模板引擎。类似JSP,Velocity,FreeMaker等,它也可以轻易的与Spring MVC等Web框架进行集成作为Web应用的模板引擎。与其它模板引擎相比,Thymeleaf最大的特点是能够直接在浏览器中打开并正确显示模板页面,而不需要启动整个Web应用。它的功能特性如下:
Spring MVC中@Controller中的方法可以直接返回模板名称,接下来Thymeleaf模板引擎会自动进行渲染
模板中的表达式支持Spring表达式语言(Spring EL)
表单支持,并兼容Spring MVC的数据绑定与验证机制
国际化支持
Spring官方也推荐使用Thymeleaf,所以本篇代码整合就使用Thymeleaf来整合。
&dependency& &groupId&org.springframework.boot&/groupId& &artifactId&spring-boot-starter-thymeleaf&/artifactId&&/dependency&
如图所示,spring-boot-starter-thymeleaf会自动包含spring-boot-starter-web,所以我们就不需要单独引入web依赖了。
编写controller
12345678910111213141516171819202122232425262728293031
@Controller@RequestMapping("/learn")public class LearnResourceController { @RequestMapping("/") public ModelAndView index(){ List&LearnResouce& learnList =new ArrayList&LearnResouce&(); LearnResouce bean =new LearnResouce("官方参考文档","Spring Boot Reference Guide","http://docs.spring.io/spring-boot/docs/1.5.1.RELEASE/reference/htmlsingle/#getting-started-first-application"); learnList.add(bean); bean =new LearnResouce("官方SpriongBoot例子","官方SpriongBoot例子","/spring-projects/spring-boot/tree/master/spring-boot-samples"); learnList.add(bean); bean =new LearnResouce("龙国学院","Spring Boot 教程系列学习","/article/detail/125488"); learnList.add(bean); bean =new LearnResouce("嘟嘟MD独立博客","Spring Boot干货系列 ","http://tengj.top/"); learnList.add(bean); bean =new LearnResouce("后端编程嘟","Spring Boot教程和视频 ","/m3553/"); learnList.add(bean); bean =new LearnResouce("程序猿DD","Spring Boot系列","/article/detail/125488"); learnList.add(bean); bean =new LearnResouce("纯洁的微笑","Sping Boot系列文章","/spring-boot"); learnList.add(bean); bean =new LearnResouce("CSDN——小当博客专栏","Sping Boot学习","http://blog.csdn.net/column/details/spring-boot.html"); learnList.add(bean); bean =new LearnResouce("梁桂钊的博客","Spring Boot 揭秘与实战","http://blog.csdn.net/column/details/spring-boot.html"); learnList.add(bean); bean =new LearnResouce("林祥纤博客系列","从零开始学Spring Boot ","http://-qq-/category/356333"); learnList.add(bean); ModelAndView modelAndView = new ModelAndView("/index"); modelAndView.addObject("learnList", learnList); return modelAndV }}
引入依赖后就在默认的模板路径src/main/resources/templates下编写模板文件即可完成。这里我们新建一个index.html:
1234567891011121314151617181920212223242526
&!DOCTYPE html&&html xmlns:th="http://www.thymeleaf.org"&&head& &title&learn Resources&/title& &meta http-equiv="Content-Type" content="text/ " /&&/head&&body&&div style="text-align:margin:0width: 1000 "&&h1&学习资源大奉送,爱我就关注嘟嘟公众号:嘟爷java超神学堂(javaLearn)&/h1&&table width="100%" border="1" cellspacing="1" cellpadding="0"& &tr& &td&作者&/td& &td&教程名称&/td& &td&地址&/td& &/tr& &!--/*@thymesVar id="learnList" type=""*/--& &tr th:each="learn : $"& &td th:text="$"&嘟嘟MD&/td& &td th:text="$"&SPringBoot干货系列&/td& &td&&a th:href="$" target="_blank"&点我&/a&&/td& &/tr&&/table&&/div&&/body&&/html&
注:通过xmlns:th=”“ 命令空间,将静态页面转换为动态的视图,需要进行动态处理的元素将使用“th:”前缀。
ok,代码都写好了,让我们看对比下直接打开index.html和启动工程后访问 看到的效果,Thymeleaf做到了不破坏HTML自身内容的数据逻辑分离。
Thymeleaf的默认参数配置
在application.properties中可以配置thymeleaf模板解析器属性
12345678910111213141516171819202122232425
# THYMELEAF (ThymeleafAutoConfiguration)#开启模板缓存(默认值:true)spring.thymeleaf.cache=true #Check that the template exists before rendering it.spring.thymeleaf.check-template=true #检查模板位置是否正确(默认值:true)spring.thymeleaf.check-template-location=true#Content-Type的值(默认值:text/html)spring.thymeleaf.content-type=text/html#开启MVC Thymeleaf视图解析(默认值:true)spring.thymeleaf.enabled=true#模板编码spring.thymeleaf.encoding=UTF-8#要被排除在解析之外的视图名称列表,用逗号分隔spring.thymeleaf.excluded-view-names=#要运用于模板之上的模板模式。另见StandardTemplate-ModeHandlers(默认值:HTML5)spring.thymeleaf.mode=HTML5#在构建URL时添加到视图名称前的前缀(默认值:classpath:/templates/)spring.thymeleaf.prefix=classpath:/templates/#在构建URL时添加到视图名称后的后缀(默认值:.html)spring.thymeleaf.suffix=.html#Thymeleaf模板解析器在解析器链中的顺序。默认情况下,它排第一位。顺序从1开始,只有在定义了额外的TemplateResolver Bean时才需要设置这个属性。spring.thymeleaf.template-resolver-order=#可解析的视图名称列表,用逗号分隔spring.thymeleaf.view-names=
整合一个bootstrap框架给大家
大家可以直接打开vanilla-cream-css下面的index.html来查看静态效果,如下:
动态效果的话可以查看template.html这里把上面的资源例子重新用bootstrap写了下,效果不错哦,如下:
本章到此就结束了,下一篇准备介绍下如何整合jsp,毕竟现在绝大多数的企业还是用jsp来作为模板引擎的。
( ̄︶ ̄)↗[]
博主有几本Spring Boot的中文电子书资料,有需要的可以关注博主微信公众号(嘟爷java超神学堂),自行前往下载【开发工具-&java电子书籍】
明天提醒我
我要该,理由是:
关闭理由:
删除理由:
忽略理由:
推广(招聘、广告、SEO 等)方面的内容
与已有问题重复(请编辑该提问指向已有相同问题)
答非所问,不符合答题要求
宜作评论而非答案
带有人身攻击、辱骂、仇恨等违反条款的内容
无法获得确切结果的问题
非开发直接相关的问题
非技术提问的讨论型问题
其他原因(请补充说明)
扫扫下载 AppSpring MVC: from JSP and Tiles to Thymeleaf
Engineering
News and Events
Spring MVC: from JSP and Tiles to Thymeleaf
When it comes to the view layer, Spring @MVC gives you a variety of choices. In this article, we will first discuss the way you have most likely used the view layer in the past few years: JSP. We will see the bad and better ways to work with them (plain JSP, JSP with custom tags, Apache Tiles).We will then discuss a new project called Thymeleaf, which you can use as an alternate approach to JSP.As usual, you can find all the code samples discussed in the . Plain JSPLet us get started with the below code sample:
&html …& &body&
&div style=&padding-top: 50&&
&jsp:include page=&../menu.jspx&/&
&c:choose&
&c:when test=&${empty users}&&
Table is empty.
&c:otherwise&
&th& First Name &/th&
&th& Last name &/th&
&c:forEach var=&user& items=&${users}&&
&td& &c:out value=&${user.firstName}&/& &/td&
&td& &c:out value=&${user.lastName}&/& &/td&
&/c:forEach&
&/c:otherwise&
&/c:choose&
&jsp:include page=&../footer.jspx&/&
This code sample is not exactly “state of the art” in the sense that it could have been written 8 years ago in the exact same way. Does it mean that it is outdated? Let’s discuss some possible limitations.1) The layoutWe’ve used &jsp:include /& in order to include JSP fragments (header and footer). Obviously it’s good to have &jsp:include /& because it prevents you from doing a lot of copy/pasting. However, if you have hundreds of JSP files, you’ll find yourself copy/pasting those &jsp:include /& tags into all your JSPs. It would be better to externalize all layout information into a dedicated file.2) VerbosityOur users page is fairly small because it simply displays a list of elements. We already have 50 lines of code (the above code sample has been slightly reduced). You can imagine how big it would be if we had to display a lot of content.3) HTML/CSS complianceThis page is not HTML/CSS compliant. Suppose a Web Designer has prototyped it, you would have to rewrite it completely in order to use intrusive JSP syntax. We’ll come back to that point when talking about ThymeLeaf. JSP custom tagsCustom tags are part of Java EE. They allow you to externalize repetitive pieces of JSP without having to write a single line of Java. You instead create a dedicated .tagx file.Here is an example:
&jsp:directive.attribute name=&title& required=&true& rtexprvalue=&true& /&
&div style=&padding-top: 50&&
&jsp:include page=&/WEB-INF/view/jsp/menu.jspx&/&
&jsp:doBody /&
&jsp:include page=&/WEB-INF/view/jsp/footer.jspx&/&
In the sample application, this file is called mainLayout.tagx. It is there on my filesystem:The most important instruction in the above sample is &jsp:doBody /&. When the template is processed, &jsp:doBody /& is replaced with content from the “main” JSP.Inside each JSP, I can invoke the previously created tag.As you can see below, we are associating the custom namespace to our tags folder. We can then use the tag called mainLayout.
&div xmlns:c=&/jsp/jstl/core& xmlns:jsp=&/JSP/Page&
xmlns:custom=&urn:jsptagdir:/WEB-INF/tags&&
&custom:mainLayout title=&${title}/&&
&c:choose&
&/c:choose&
&/custom:mainLayout&
Note: as you can see in the above code sample, each JSP should specify the layout that it uses. If I have several layouts and I want to migrate several JSPs from mainLayout to customLayout, I would need to edit each of those JSP files and change the layout manually. We will come back to that point later when talking about Tiles.Custom tags can do much more for you than just externalizing the layout part. To illustrate this point, I’ve created a simpleTable tag so I do not have to deal with &thead& and &tbody& tags. It also displays a message when the table is empty. My JSP file now looks like this:
&custom:mainLayout title=&${title}/&&
&custom:simpleTable collection=&${users}& headerLabels=&First Name, Last Name&&
&c:forEach var=&user& items=&${users}&&
&td& &c:out value=&${user.firstName}&/& &/td&
&td& &c:out value=&${user.lastName}&/& &/td&
&/c:forEach&
&/custom:simpleTable&
&/custom:mainLayout&
You can browse
for a complete example.&Note: I should also mention a new project called
created by Thibault Duchateau. It provides a set of tags on top of jquery-datatables and therefore allows to create AJAX-style datatables without having to write Javascript yourself. Documentation is pretty good and this project is actively worked on.&Pros and ConsStandard Tags have many benefits: I can use them to do much more than just externalizing layout information. In the end, they can easily make your JSPs 5 times smaller than they would be otherwise. Eclipse/STS works well with custom tags so you’re able to use CTRL+space for auto-completion.On the down side: Documentation is not the best. Even though custom tags are pretty neat already, I can’t recall any improvement to them in the past few years. Using Custom tags implies that you’re using a JSP Engine inside your web container. You can then expect some minor differences depending on the web container you’re using (Apache Tomcat, IBM Websphere, Oracle Weblogic…). It is also harder to Unit Test your view layer. You can see
if you’re interested in this topic.Externalizing your JSPs’ layout using Apache TilesApache Tiles was already famous a decade ago for being the layout plugin that came with Struts 1. It now is an independent framework and integrates well with Spring MVC.First of all, you should declare the appropriate Spring configuration:
&bean id=&tilesViewResolver& class=&org.springframework.web.servlet.view.tiles3.TilesViewResolver&/&
&bean id=&tilesConfigurer& class=&org.springframework.web.servlet.view.tiles3.TilesConfigurer&&
&property name=&definitions&&
&value&/WEB-INF/view/jsp/tiles.xml&/value&
&/property&
In the below example, we are going to create 3 files as follows:Layout fileAs with JSP custom tags, the layout is described in a dedicated file. The syntax is quite similar, except that we are using the tiles tag library.
&html xmlns:tiles=&http://tiles.apache.org/tags-tiles& …&
&head& … &/head&
&jsp:include page=&/WEB-INF/view/jsp/menu.jspx&/&
&tiles:insertAttribute name=&main& /&
&jsp:include page=&/WEB-INF/view/jsp/footer.jspx&/&
layout.jspx
The most important instruction in the above sample is &tiles:insertAttribute /&. When the template is processed, &tiles:insertAttribute /& is replaced with content from the “main” JSP. We will then use a dedicated file (typically called tiles.xml) which contains all the tiles definitions as follows:
&tiles-definitions&
&definition name=&tiles/*& template=&/WEB-INF/view/jsp/03-tiles/layout.jspx&&
&put-attribute name=&main& value=&/WEB-INF/view/jsp/03-tiles/{1}.jspx& /&
&/definition&
&/tiles-definitions&
Wildcard usage
In the past, Apache Tiles did not handle wildcards and we had to copy/paste a new definition inside tiles.xml every time a new JSP was created.
Based on the above example, the view “tiles/users” will be resolved as /WEB-INF/view/jsp/users.jspx using the template layout.jspx.Inside the JSP, there is no mention of the layout it uses:
&div xmlns:c=&/jsp/jstl/core& xmlns:jsp=&/JSP/Page&&
&th& First Name &/th&
&th& Last name &/th&
&c:forEach var=&user& items=&${users}&&
&td& &c:out value=&${user.firstName}&/& &/td&
&td& &c:out value=&${user.lastName}&/& &/td&
&/c:forEach&
The Apache Tiles approach is similar to custom tags and therefore has same pros and cons. There is some activity on the Apache Tiles project but it is definitely not as vibrant as ThymeLeaf which we will discuss in the next section.Thymeleaf defines itself as an
XML / XHTML / HTML5 template engine.It is not based on JSPs but rather on some plain HTML files with a little bit of namespace magic.First step: we should integrate ThymeLeaf with Spring. As usual, we need to declare the appropriate view resolver.
&bean id=&templateResolver& class=&org.thymeleaf.templateresolver.ServletContextTemplateResolver&&
&property name=&prefix& value=&/WEB-INF/view/& /&
&property name=&suffix& value=&.html& /&
&property name=&templateMode& value=&HTML5& /&
&property name=&cacheable& value=&false& /&
&bean id=&templateEngine& class=&org.thymeleaf.spring3.SpringTemplateEngine&&
&property name=&templateResolver& ref=&templateResolver& /&
&bean class=&org.thymeleaf.spring3.view.ThymeleafViewResolver&&
&property name=&templateEngine& ref=&templateEngine& /&
&property name=&order& value=&1& /&
&property name=&viewNames& value=&thymeleaf/*& /&
Let us now consider a simple view page.
&html xmlns:th=&http://www.thymeleaf.org&&
&link th:src=&@{/style/app.css}& rel=&stylesheet&/&
&div th:if=&${not #lists.isEmpty(users)}&&
&thead& … &/thead&
&tr th:each=&user : ${users}&&
&td th:text=&${user.firstName}&&John&/td&
&td th:text=&${user.lastName}&&Smith&/td&
&/div&&/body&&/html&
users.htmlThere are a few things that we can notice:-This is an html file! You can actually preview it as a static file in your web browser. This feature is great for prototyping [1].
We are using a
dedicated namespace in order to turn static html pages into dynamic views. All parts that require dynamic processing are prefixed with “th:”.
It’s simple to refer to the context path using ‘@{…}’.
This is very easy to get wrong in plain JSPs [2].
${users} is resolved using Spring Expression Language. If I had a form, I would have used expressions such as *{user.name} to refer to form elements.
[1] We will not discuss prototyping any further in this article. However you can read this tutorial () if you would like to know more about it.[2] In the first part of this article, when using &jsp:include /&, I had to use a relative path
“../menu.jspx”. This will lead to a broken link on the day I’ll move my JSP file to a different folder.Layout fileLet us now discuss how to externalize the layout into a dedicated file.As we did with JSP custom tags and with Tiles, you need to declare your layout file. In the code sample below, you will find 2 fragments:
headerFragment contains all header information
menuFragment contains my menu bar
Those names are not mandatory and I can have as many fragments as I wish.In each view file, I can refer to fragments using th:include as follows:
&html xmlns:th=&http://www.thymeleaf.org&&
&head th:include=&thymeleaf/layout :: headerFragment&&
&!-- replaced with fragment content --&
&!—- 'thymeleaf/layout' refers to /thymeleaf/layout.html on the filesystem --&
&div th:include=&thymeleaf/layout :: menuFragment&&
&div th:if=&${not #lists.isEmpty(users)}&&
&tr th:each=&user : ${users}&&
&td th:text=&${user.firstName}&&John&/td&
&td th:text=&${user.lastName}&&Smith&/td&
On the filesystem we have:Pros and ConsOn the bright side: ThymeLeaf is a healthy open source project: new features coming up each month, good documentation, responsive user forums… It is the ideal template engine if you want your web designer to be able to read your view files The Expression Language used (actually called Standard Dialect) is much more powerful than JSP Expression Language. Unlike JSPs, Thymeleaf works well for Rich HTML emails (see On the down side: Thymeleaf does not have an equivalent to custom tags (.tagx files) yet. At this stage, ThymeLeaf is not compatible with JSP tag libraries.ConclusionWe’ve seen the JSP and Thymeleaf approaches side by side. If your application uses hundreds of JSPs, we are not saying that you should ditch them all and start over again using Thymeleaf. However you might consider Thymeleaf for HTML pages outside of the web container such as for Rich HTML emails.If you are starting on a new project, we strongly encourage you to compare both Thymeleaf and JSPs in order to figure out which one is more suitable to your needs.Also, my colleague Rob Winch did a great presentation about . Besides JSP and Thymeleaf, it also discusses Mustache templates.The sample app used for this blog entry is .
Please enable JavaScript to view the

我要回帖

更多关于 thymeleaf jsp 共存 的文章

 

随机推荐