1. 首页
  2. 编程语言
  3. Java
  4. thmeleaf文档

thmeleaf文档

上传者: 2020-07-29 13:27:47上传 PDF文件 655.57KB 热度 11次
thmeleaf 官方文档resources in HTML format could be included into application templates, safely knowing that any Thymeleaf code thatthese resources might include will not be executed1. 3 Dialects. The standard dialectThymeleaf is an extremely extensible template engine(in fact it could be called a template engine framework) thatallows you to de fine and customize the way your templates will be processed to a fine level of detaiL.An object that applies some logic to a markup artifact (a tag some text, a comment, or a mere placeholder if templatesare not markup) is called a processor, and a set of these processors-plus perhaps some extra artifacts- is what adialect is normally comprised of Out of the box, Thymeleaf s core library provides a dialect called the standardDialect, which should be enough for most users.Note that dialects can actually have no processors and be entirely comprised of other kinds of artifacts butprocessors are definitely the most common use case.This tutorial covers the Standard Dialect. Every attribute and syntax feature you will learn about in the following pagesis defined by this dialect, even if that isn't explicitly mentioned.Of course, users can create their own dialects(even extending the Standard one) if they want to define their ownprocessing logic while taking advantage of the library' s advanced features. thymeleaf can also be configured to useseveral dialects at a timeThe official thymeleaf-spring3 and thymeleaf-spring4 integration packages both define a dialect called theSpringStandard Dialect", which is mostly the same as the Standard Dialect, but with small adaptations to makebetter use of some features in the spring Framework( for example by using Spring Expression Language orSpringel instead of OGNL). So if you are a spring mvc user you are not wasting your time, as almost everythingyou learn here will be of use in your Spring applicationsMost of the processors of the Standard dialect are attribute processors. This allows browsers to correctly display htmltemplate files even before being processed because they will simply ignore the additional attributes. For example,while a JSP using tag libraries could include a fragment of code not directly displayable by a browser likethe thymeleaf standard dialect would allow us to achieve the same functionalithNot only will this be correctly displayed by browsers, but this also allow us to(optionally) specify a value attribute in itJames Carrot in this case) that will be displayed when the prototype is statically opened in a browser, and that willbe substituted by the value resulting from the evaluation of fuser name] during processing of the templateThis helps your designer and developer to work on the very same template file and reduce the effort required totransform a static prototype into a working template file the ability to do this is a feature called Natural Templating.Page 3 oF 1042 The Good Thymes Virtual GroceryThe source code for the examples shown in this, and future chapters of this guide, can be found in the Good ThymesVirtual Grocery GitHub repository2. 1 A website for a groceryTo better explain the concepts involved in processing templates with Thymeleaf, this tutorial will use a demoapplication which you can download from the project's web siteThis application is the web site of an imaginary virtual grocery, and will provide us with many scenarios to showcaseThymeleaf s many FeaturesTo start, we need a simple set of model entities for our application: Products which are sold to Customers by creatingOrders. we will also be managing Comments about those productsCustomerOrdercustomerd: Integeid: Integername: Stringdate: Calendarcustomersince Calendarcustomer: CustomerorderLines: SetorderlinesProductOrderlineid: Integerproduct: Productname: Stringproductamount: Integerprice: BigDecimalpurchasePrice: BigDecimalin stock booleancomments: Listcomments0.Commentd: Integertext: StringExample application modelOur application will also have a very simple service layer, composed by Service objects containing methods like:Page 4 of 104ublic class Productservice Iublic List findALlo ireturn ProductRepository. getInstance (. findALlO;ublic Product findById(Integer id)ireturn ProductRepository. getInstance (. findById(id);At the web layer our application will have a filter that will delegate execution to Thymeleaf-enabled commandsdepending on the request URL:Page 5 oF 104ivatebooleanprocess(httpservletrequestrequestHttpservletresPonseresponsethrows ServletException// This prevents triggering engine executions for resource URLSif (request. getRequestURIO, startswith("/css")request. getRequestURI(. startswith("/images")2 request. getRequestURI(. startswith("/favicon "))IQuery controller /URL maand obtain the controllerthat will process the request. If no controller is availablereturn false and let other filters/servlets process the requestIGTVGController controLler this, application, resolveControLler For Request(request)if (controller = null)[return false;Obtain the Template Engine instanceITemp late Engine templateEngine this application. getTemp late Engine();Write the response headersresponse. setContentType( text/html; charset=UTF-8)response. setHeader( Pragma",no-cache");response. setHeader(Cache-ControL,no-cache")response. setDateHeader("Expires", 0)Execute the controller and process view temp latex writing the results to the response writercontroller process(request, response, this servletContext, temp Late Engine)return true0 catch(Exception e)[try iresponsesendError(httpServletresponse.Sc_internaLSerVerErrOr);I catch(final IOException ignored)[Just ignore thisthrow new ServletException(e);This is our IgtvgController inter facePage 6 of 104ublic inter face IGTVGControllerpublic void process(HttpservletrequeSt request htTpservletresponsE responseServletcontext servletContext, ITemplate Engine templateEngine):All we have to do now is create implementations of the IGTVGController interface, retrieving data from the servicesand processing templates using the ITemplate Engine objectIn the end, it will look like this:Good ThymesVirtualwelcome to our fantastic grocery store, John Apricot!Today is: April 07, 2011Please select an option1. Product List2. order List3. Subscribe to our Newsletter4. see User ProfNow you are looking at a working web applicatione 2011 The Good Thymes virtual GroceryExample application home pageBut first let's see how that template engine is initialized.2.2 Creating and configuring the Template EngineThe process(. method in our filter contained this lineITemp lateEngine temp LateEngine this application. getTemp lateEngine (:Which means that the GTVGApplication class is in charge of creating and con figuring one of the most important objectsin a Thymeleaf application: the TemplateEngine instance(implementation of the ITemplateEngine interface)Our org. thymeleaf Template Engine object is initialized like this:Page 7 oF 104ublic cLass GTVGApplication iprivate final Temp lateEngine templateEnginoublic GTVGApplication(final Servlet Context servletContext)[Servlet ContextTemplate Resolver templateResolvernew ServletCon textTemp lateResolver(servletcontext);/ HTML is the default mode, but we set it anyway for better under standing of codetemp lateResolver setTemp lateMode(Temp lateMode. HTML)// This will convert " home" to"/WEB-INF/templates/home. htmL"templateResolver. setPrefix("/WEB-INF /templates/")templateResoLver. setSuffix(".htmL")// Temp Late cache TTL=1h. If not set, entries would be cached until expelled by LRUtemplateResoLver. setCacheTTLMs(Long, valueOf(3600000L))/ Cache is set to true by default. Set to false if you want templates tobe automatically updated when modifiedtemplateResolver. setCacheable(truethis temp lateEngine new Temp late Engine()this templateEngine setTemp lateResolver(temp LateResolverThere are many ways of configuring a Temp LateEngine object, but for now these few lines of code will teach us enougabout the steps neededThe Template ResolverLet' s start with the Template ResolverServletContextTemplateResolver temp lateResolvernew Servlet ContextTemp lateResolver(servletContext);Template Resolvers are objects that implement an interface from the ThymeleaF APl calledorg. thyme leaf. tempLateresolver ITemplateReso lver:Page 8 oF 104ublic inter face ITemplateResolverTemplates are reso Lved by their name (or content) and also (optionally) theirowner template in case we are trying to resolve a fragment for another temp latewill return null if template cannot be handled by this template resolverpublic Temp lateResolution resolveTemplate(final IEngine Configuration configurationfinal String owner Template, final String templatefinal Map temp lateResolutionAttributes)These objects are in charge of determining how our templates will be accessed, and in this gTVg application, theorg. thyme leaf. templateresolver ServletContextTemp lateResolver means that we are going to retrieve our templatefiles as resources from the Servlet Context: an application-wide javax. servlet Servletcontext object that exists inevery Java web application, and that resolves resources from the web application root.But that's not all we can say about the template resolver, because we can set some con figuration parameters on it.First, the template modetemplateResolver. setTemplateMode(TemplateMode. HTML)HTML is the default template mode for ServletContextTempLateResolver but it is good practice to establish it anywayso that our code documents clearly what is going ontemplateResolver. setPrefix("/WEB-INF/templates/")templateReso lver set Suffix("html")The prefix and suffix modify the template names that we will be passing to the engine for obtaining the real resourcenames to be usedUsing this configuration, the template name "product/ist"would correspond toervlet Context getRe sourceAsStream("/WEB-INF/templates/product/list. html")Optionally, the amount of time that a parsed template can live in the cache is con figured at the Template Resolver bymeans of the cache TTLMs property:templateReso lver set CacheTTLMs(3600000L);A template can still be expelled from cache before that ttl is reached if the max cache size is reached and it is theoldest entry currently cachedCache behaviour and sizes can be defined by the user by implementing the ICacheManager interface or bymodifying the StandardCacheManager object to manage the default cache.There is much more to learn about template resolvers, but for now let's have a look at the creation of our TemplateEngine object.The Template EngineTemplate Engine objects are implementations of the org. thyme leaf ITemplate Engine interface. One of theseimplementations is offered by the thymeleaf core: org. thymeleaf Temp LateEngine, and we create an instance of ittemplate Engine new Temp LateEngine ()template Engine. setTemplateResoLver (templateResolver)Rather simple, isnt it? All we need is to create an instance and set the template resolver to itA template resolver is the only required parameter a TemplateEngine needs, although there are many others that willbe covered later(message resolvers, cache sizes, etc). For now, this is all we needOur Template Engine is now ready and we can start creating our pages using thymeleafPage 10 oF 104
下载地址
用户评论
码姐姐匿名网友 2020-07-29 13:27:47

英文的文档