所需积分/C币:35 2018-04-12 15:02:19 1.55MB PDF
收藏 收藏

thymeleaf 模板引擎,英文版。学习thymeleaf 很好的一本书
13.1 Order list 55 13.2 Order details 14 More on configuration,………,……,μμμμμ…58 14.1 Template resolvers .58 14.2 Message resolvers l■面1面i1面面国1 59 14.3 Logging 60 15 Template Cache.………………………………………………………………………………………………,61 16 Appendix: Expression Utility 62 Page 3 or 69 1 NTRODUCING THYMELEAF 11 WHAT IS THYMELEAF? Thymeleaf is a Java library. It is an XML/XHTML/HTML5 template engine able to apply a set of transformations to template files in order to display data and/or text produced by your applications It is better suited for serving XHTML/HTML5 in web applications, but it can process any XML file, be it in web or in standalone applications The main goal of Thymeleaf is to provide an elegant and well-formed way of creating templates. In order to achieve this, it is based on XML tags and attributes that define the execution of predefined logic on the dOM(Document Object Model), instead of explicitly writing that logic as code inside the template Its architecture allows a fast processing of templates, relying on intelligent caching of parsed files in order to use the least possible amount of lyo operations during execution And last but not least, Thymeleaf has been designed from the beginning with XML and Web standards in mind, allowing you to create fully validating templates if that is a need for you 1.2 WHAT KIND OF TEMPLATES CAN THYMELEAF PROCESS? Out-of-the-box, Thy meleaf allows you to process six kinds of templates, each of which is called a Template Mode ⅩML Valid Xml XHTML Valid Xhtml HTML5 · Legacy HTML5 All of these modes refer to well-formed XML files except the Legacy HTML5 mode, which allows you to process HTmL5 files with features such as standalone (not closed)tags, tag attributes without a value or not written between commas. In order to process files in this specific mode, Thymeleaf will first perform a transformation that will convert your files to well-formed XML files which are still perfectly valid HTMl5 (and are in fact the recommended way to create HTML5 code).i 1 Given the fact that XHTML5 is just XML-formed HTML5 served with the application/xhtml+xml content type, we could also say that Thymeleaf supports XHTML5 PAGe 4 or 69 Also note that validation is only available for XMl and XHTMl templates Nevertheless, these are not the only types of template that Thymeleaf can process, and the user is always able to define his/her own mode by specifying both a way to parse templates ir this mode and a way to write the results. This way, anything that can be modelled as a dOM tree(be it XML or not)could effectively be processed as a template by Thymeleaf 1.3 DIALECTS: THE STANDARD DIALECT Thymeleaf is an extremely extensible template engine (in fact it should be better called a template engine framework that allows you to completely define the dom nodes that will be processed in your templates and also how they will be processed An object that applies some logic to a DOM node is called a processor, and a set of these processors -plus some extra artifacts- is called a dialect, of which Thymeleaf's core library provides one out-of-the-box called the Standard Dialect, which should be enough for the needs of a big percent of users will learn about in the following pages is defined by this dialect, even if that isn't explic c The standard Dialect is the dialect this tutorial covers. Every attribute and syntax feature you mentioned to define their own processing logic while taking advantage of the library s advanced feature F Of course, users may create their own dialects (even extending the Standard one) if they war A Template Engine can be configured several dialects at a time The official thymeleaf-spring3 integration package defines a dialect called the Spring Standard Dialect mostly equivalent to the standard Dialect but with small adaptations to make better use of some features in Spring Framework(for example, by using Spring Expression Language instead of Thymeleaf's standard OGNL). So if you are a Spring MVC user you are not wasting your time, as al most everything you learn here will be of use in your Spring applications. The Thy meleaf Standard Dialect can process templates in any mode, but is especially suited for web-oriented template modes (XHTML and hTml5 ones). Besides HTML5, it specificall supports and validates the following XHTML specifications: XHTML 1.0 Transitional, XHTML 1.0 Strict, XHTML 1.0 Frameset, and XHTMl 1.1 Also, the Standard Dialect does not include any processors to be applied on tags -called elements in DOM terminology- it is an attribute-only dialect. this allows browsers to correctly display XHTML/HTML5 template files even before being processed, because they will simply ignore the additional attributes. For example, while a Sp using tag libraries could include a fragment of code not directly displayable by a browser like: <form: inputText name="userName"value="$luser. nameI"/> the Thymeleaf standard Dialect would allow us to achieve the same functionality with cinput type="text" name="use rName"value="James Carrot" th: value="$user name]"/> Which not only will be correctly displayed by browsers, but also allow us to(optionally ) speci a value attribute in it(James Carrot", in this case) that will be displayed when the prototype is statically opened in a browser, and that will be substituted by the value resulting from the evaluation of user name during thymeleaf processing of the template If needed, this will allow your designer and developer to work on the very same template file and reduce the effort required to transform a static prototype into a working template file. the Page 5 or 69 ability to do this is a feature usually called Natural Templating 1.4 OVERALL ARCHITECTURE Thymeleaf's core is a DOM processing engine. Specifically, it uses its own high-performance DOM implementation -not the standard dOM API-for building in- memory tree representations of your templates, on which it later operates by traversing their nodes and executing processors on them that modify the dom according to the current configuration and the set of data that is passed to the template for its representation-known as the context. The use of a dOM template representation makes it very well suited for web applications because web documents are very often represented as object trees (in fact dOM trees are the way browsers represent web pages in memory). Also, building on the idea that most web applications use only a few dozen templates, that these are not big files and that they don't normally change while the application is running, thymeleaf's usage of an in-memory cache of parsed template doM trees allows it to be fast in production environments, because very little 1/0 is needed (if any) for most template processing operations If you want more detail, later in this tutorial there is an entire chapter dedicated to caching and to the way Thymeleaf optim izes memory and resource usage for faster operation. Nevertheless, there is a restriction this architecture also requires the use of bigger amounts of memory space for each template execution than other template parsing/processing approaches, which means that you should not use the library for creating big data XML documents(as opposed to web documents). As a general rule of thumb(and always depending on the memory size of your JVM), if you are generating XML files with sizes around the tens of megabytes in a single template execution, you probably should not be using Thymeleaf The reason we consider this restriction only applies to data XML files and not we XHTML/HTML5 is that you should never generate web documents so big that your users'browsers ablaze and/or explode remember that these browsers will also have to create dom trees for your pages 1. 5 BEFORE GOING ANY FURTHER, YOU SHOULD READ, Thymeleaf is especially suited for working in web applications. And web applications are based on a series of standards that everyone should know very well but few do-even if they have been working with them for years With the advent of HTML5, the state of the art in web standards today is more confusing than ever.are we going back from XHTML to HTML? Will we abandon XML syntax? Why is nobody talking about XHTML 2.0 anymore? So before going any further in this tutorial, you are strongly advised to read an article on Thymeleaf's web site called "From HTMl to HTML (via HTML)", which you can find at this addresshttp://www.thymeleaforg/fromhtmltohtmlviahtml.html Page 6 or 69 2 THE GOOD THYMES VIRTUAL GROCERY 2 1 A WEBSITE FOR A GROCERY In order to better explain the concepts involved in processing templates with Thymeleaf, this tutorial will use a demo application you can download from the project web site This application represents the web site of an imaginary virtual grocery, and will provide us with the adequate scenarios to exemplify diverse Thymeleaf features We will need a quite simple set of model entities for our application Products which are sold to Customers by creating Orders. We will also be managing Comments about those products Customer Order customer id: Integer id: Integer name: String date: Calendar customersince Calendar customer: Customer orderLines: Set<OrderLine> orderlines Product Ordering id: Integer name: String product product: Product amount: Integer price: BigDecimal purchasePrice: BigDecimal linStock: boolean comments: List<Comment> comments 0. Comment d: Integer text: String Our small application will also have a very simple service layer, composed by service objects containing methods like Page 7 or 69 public class productservice public List<Product> findAll([ return ProductRepository, getInstance(). findALl( public Product findById(Integer id)t return ProductRepository. getInstance(). findById(id) Finally, at the web layer our application will have a filter that will delegate execution to Thymeleaf-enabled commands depending on the request URL: privatebooleanprocess(httpservletrequestrequestHttpservletResponseresponse) try t Query controller/URL mapping and obtain the controller s that will process the request. If no controller is available s return false and let other filters/servlets process the request IGTVGController cont roller GTVGApplication. resolveControlLer ForRequest( request return false: s Obtain the Temp lateEngine instance TemplateEngine templateEngine =GTVGApplication getTemplate Engine() t write the response headers response set ContentType("text/html; charset=UTF-8") response. setHeader ("Pragma","no-cache ") response. setHeader Cache-Control ,no- cache ") response. setDateHeader("Expires",0)i s Execute the controller and process view temp late s writing the results to the response writer ntroller, proces request, response, request. get Session(true).getServletContext(), templateEngine) eturn true catch (Exception e)t throw new ServletException (e) This is our IgtvgController interface: public interface IGTVGCont roller i public string process( Httpservletrequest request Httpservletresponse response Servlet Context servletContext, TemplateEngine templatcEngine); All we have to do now is create implementations of the Igtvgcontroller interface, retrieving data from the services and processing templates using the TemplateEngine object In the end, it will look like this Page 8 or 69 Good Thymes Virtual grocery Welcome to o r fantastic grocery stare. John Apricot Ic day Is: AprIl 0/,2011 1. Produc List List 3. Subser ibe lu our Newslellel 1. see User -roti e Now you are looking at a working web applicaticn e 2oll The Gocd Thymes vrtual Grocery But first let's see how that template engine is initialized 2.2 CREATING AND CONFIGURING THE TEMPLATE ENGINE The process(.)method in our filter contained this sentence: Template Engine templateEngine= GTVGApplication getTemplateEngine() Which means that the GTVGApplication class is in charge of creating and configuring one of the most important objects in a thymeleaf-enabled application The Templateengine instance Our org. thyme leaf Temp lateEngine object is initialized like this public class GTVGApplication t private static TemplateEngine templateEngine static i initializeTemplateEnginc()i private static void initializetemplateengine o)t Servlet ContextTemplateResolver temp lateResolver new ServletContextTemplateResolver() / XHTM templateResolver. setTemplateMode("XHTML"); ert"home to/WEB-INF/temp lates/ home. html templateResolver. setPrefix("/WEB-INF/templates/); templateResolver set suffix(". html") f not set, entries would live in cache until expel led by LRU templateResolver. set CacheTTLMs(3600000L templateEngine new TemplateEngine() templateEngine. setTemplateResolver(templateResolver); Page 9 or 69 Of course there are many ways of configuring a TemplateEngine object, but for now these few lines of code will teach us enough about the steps needed. The Template Resolver Let's start with the Template resolver ServletContextTemplateResolver templateResolver new ServLet ContextTemplateResolver() Template Resolvers are objects that implement an interface from the thymeleaf APl called org. thymeleaf. templateresolver ITemplateResolver public interface ITemplateResolver i Temp Lates are resolved by String name (temp lateProcessingParameters getTemp lateName()) k WiLl return null if template cannot be handled by this template resolver. public TemplateResolution resolveTemplate(TemplateProcessingParameters templateProcessing Parameters); These objects are in charge of determining how our templates will be accessed and in this GTVG application, the org. thymeleaf. templateresolver. Servlet ContextTemplateResolver mplementation that we are using specifies that we are going to retrieve our template files as resources from th le Servlet Context: an application-wide javax. servlet ServletContext object that exists in every Java web application, and that resolves resources considering the web application root as the root for resource paths configuration parameters on it. First, the template mode, one of the standard one set some But that's not all we can say about the template resolver because we can set some temp lateResolver. sctTemplateMode("XHTML") XHTML is the default template mode for servletContextTemplateResolver, but it is good practice to esta blish it anyway so that our code documents clearly what is going on temp lateResolver setPrefix("/WEB-INF/tempLates/") emplateResolver. setSuffix(".html"); These prefix and suffix do exactly what it looks like: modify the template names that we will be passing to the engine for obtaining the real resource names to be used Using this configuration, the template name "product/list"would correspond to servletContext. getResourccAs Strcam ("/WEB-INF/templates/product/list. html") Optionally, the amount of time that a parsed template living in cache will be considered valid can be configured at the Template resolver by means of the cacheTtLMs property: USING THYMELEAF- PAGr 10 or 69

试读 69P Thymeleaf使用手册.pdf
立即下载 低至0.43元/次 身份认证VIP会员低至7折
关注 私信 TA的资源
Thymeleaf使用手册.pdf 35积分/C币 立即下载

试读结束, 可继续读6页

35积分/C币 立即下载 >