Error processing snippet: content_id=main
Reason: Method Not Found
XML causing this error:
          <body xmlns="http://www.w3.org/1999/xhtml">    <div id="globalWrapper">      <h1 class="title">
Simply Lift
</h1>
<h2 class="author">
David Pollak
</h2>
<h2 class="Date">
September 8, 2011
</h2>
<div class="Standard">
Copyright © 2010-2011 by David Pollak<br/>
This document is licensed Creative Commons Attribution, Non Commercial, No Derivatives: <a href="http://creativecommons.org/licenses/by-nc-nd/3.0/" class="FlexURL">http://creativecommons.org/licenses/by-nc-nd/3.0/</a> 
</div>
<div class="fulltoc">
<div class="tocheader">
Table of Contents
</div>
<div class="toc">
<a href="#toc-Part-I" class="Link">Part I: The Lift Web Framework</a>
</div>
<div class="tocindent">
<div class="toc">
<a href="#toc-Chapter-1" class="Link">Chapter 1: Introduction</a>
</div>
<div class="toc">
<a href="#toc-Chapter-2" class="Link">Chapter 2: The ubiquitous Chat app</a>
</div>
<div class="tocindent">
<div class="toc">
<a href="#toc-Section-2.1" class="Link">Section 2.1: The View</a>
</div>
<div class="toc">
<a href="#toc-Section-2.2" class="Link">Section 2.2: The Chat Comet component</a>
</div>
<div class="toc">
<a href="#toc-Section-2.3" class="Link">Section 2.3: The <tt>ChatServer</tt></a>
</div>
<div class="toc">
<a href="#toc-Section-2.4" class="Link">Section 2.4: User Input</a>
</div>
<div class="toc">
<a href="#toc-Section-2.5" class="Link">Section 2.5: Chat In</a>
</div>
<div class="toc">
<a href="#toc-Section-2.6" class="Link">Section 2.6: Running it</a>
</div>
<div class="toc">
<a href="#toc-Section-2.7" class="Link">Section 2.7: What you don’t see</a>
</div>
</div>
<div class="toc">
<a href="#toc-Chapter-3" class="Link">Chapter 3: Snippets and SiteMap</a>
</div>
<div class="tocindent">
<div class="toc">
<a href="#toc-Section-3.1" class="Link">Section 3.1: Starting at the beginning: <tt>Boot.scala</tt></a>
</div>
<div class="tocindent">
<div class="toc">
<a href="#toc-Subsection-3.1.1" class="Link">Subsection 3.1.1: <tt>LiftRules</tt> rules</a>
</div>
<div class="toc">
<a href="#toc-Subsection-3.1.2" class="Link">Subsection 3.1.2: Properties and Run modes</a>
</div>
<div class="toc">
<a href="#toc-Subsection-3.1.3" class="Link">Subsection 3.1.3: By convention</a>
</div>
<div class="toc">
<a href="#toc-Subsection-3.1.4" class="Link">Subsection 3.1.4: Misc Rules</a>
</div>
<div class="toc">
<a href="#toc-Subsection-3.1.5" class="Link">Subsection 3.1.5: Html5</a>
</div>
</div>
<div class="toc">
<a href="#toc-Section-3.2" class="Link">Section 3.2: <tt>SiteMap</tt></a>
</div>
<div class="tocindent">
<div class="toc">
<a href="#toc-Subsection-3.2.1" class="Link">Subsection 3.2.1: Defining the <tt>SiteMap</tt></a>
</div>
<div class="toc">
<a href="#toc-Subsection-3.2.2" class="Link">Subsection 3.2.2: Simplest <tt>SiteMap</tt></a>
</div>
<div class="toc">
<a href="#toc-Subsection-3.2.3" class="Link">Subsection 3.2.3: <tt>Menu</tt> and <tt>Loc[_]</tt></a>
</div>
<div class="toc">
<a href="#toc-Subsection-3.2.4" class="Link">Subsection 3.2.4: Access Control</a>
</div>
<div class="toc">
<a href="#toc-Subsection-3.2.5" class="Link">Subsection 3.2.5: <tt>Hidden</tt> and <tt>Group</tt></a>
</div>
<div class="toc">
<a href="#toc-Subsection-3.2.6" class="Link">Subsection 3.2.6: Submenus</a>
</div>
<div class="toc">
<a href="#toc-Subsection-3.2.7" class="Link">Subsection 3.2.7: Parameters</a>
</div>
<div class="toc">
<a href="#toc-Subsection-3.2.8" class="Link">Subsection 3.2.8: Wildcards</a>
</div>
<div class="toc">
<a href="#toc-Subsection-3.2.9" class="Link">Subsection 3.2.9: Summary</a>
</div>
</div>
<div class="toc">
<a href="#toc-Section-3.3" class="Link">Section 3.3: View First</a>
</div>
<div class="tocindent">
<div class="toc">
<a href="#toc-Subsection-3.3.1" class="Link">Subsection 3.3.1: Page source</a>
</div>
<div class="toc">
<a href="#toc-Subsection-3.3.2" class="Link">Subsection 3.3.2: Dynamic content</a>
</div>
<div class="toc">
<a href="#toc-Subsection-3.3.3" class="Link">Subsection 3.3.3: Surround and page chrome</a>
</div>
<div class="toc">
<a href="#toc-Subsection-3.3.4" class="Link">Subsection 3.3.4: Embed</a>
</div>
<div class="toc">
<a href="#toc-Subsection-3.3.5" class="Link">Subsection 3.3.5: Results</a>
</div>
</div>
<div class="toc">
<a href="#toc-Section-3.4" class="Link">Section 3.4: Snippets and Dynamic content</a>
</div>
<div class="tocindent">
<div class="toc">
<a href="#toc-Subsection-3.4.1" class="Link">Subsection 3.4.1: Snippets in markup</a>
</div>
<div class="toc">
<a href="#toc-Subsection-3.4.2" class="Link">Subsection 3.4.2: Snippet resolution</a>
</div>
<div class="toc">
<a href="#toc-Subsection-3.4.3" class="Link">Subsection 3.4.3: Dynamic Example</a>
</div>
<div class="toc">
<a href="#toc-Subsection-3.4.4" class="Link">Subsection 3.4.4: Embedded Example</a>
</div>
<div class="toc">
<a href="#toc-Subsection-3.4.5" class="Link">Subsection 3.4.5: Param Example</a>
</div>
<div class="toc">
<a href="#toc-Subsection-3.4.6" class="Link">Subsection 3.4.6: Recursive</a>
</div>
<div class="toc">
<a href="#toc-Subsection-3.4.7" class="Link">Subsection 3.4.7: Summary</a>
</div>
</div>
<div class="toc">
<a href="#toc-Section-3.5" class="Link">Section 3.5: Wrap up</a>
</div>
</div>
<div class="toc">
<a href="#toc-Chapter-4" class="Link">Chapter 4: Forms</a>
</div>
<div class="tocindent">
<div class="toc">
<a href="#toc-Section-4.1" class="Link">Section 4.1: Old Fashioned Dumb Forms</a>
</div>
<div class="toc">
<a href="#toc-Section-4.2" class="Link">Section 4.2: OnSubmit</a>
</div>
<div class="toc">
<a href="#toc-Section-4.3" class="Link">Section 4.3: Stateful Snippets</a>
</div>
<div class="toc">
<a href="#toc-Section-4.4" class="Link">Section 4.4: <tt>RequestVar</tt>s</a>
</div>
<div class="toc">
<a href="#toc-Section-4.5" class="Link">Section 4.5: Field Errors</a>
</div>
<div class="toc">
<a href="#toc-Section-4.6" class="Link">Section 4.6: <tt>LiftScreen</tt></a>
</div>
<div class="toc">
<a href="#toc-Section-4.7" class="Link">Section 4.7: <tt>Wizard</tt></a>
</div>
<div class="toc">
<a href="#toc-Section-4.8" class="Link">Section 4.8: Ajax</a>
</div>
<div class="toc">
<a href="#toc-Section-4.9" class="Link">Section 4.9: But sometimes Old Fashioned is good</a>
</div>
<div class="toc">
<a href="#toc-Section-4.10" class="Link">Section 4.10: Conclusion</a>
</div>
</div>
<div class="toc">
<a href="#toc-Chapter-5" class="Link">Chapter 5: HTTP and REST</a>
</div>
<div class="tocindent">
<div class="toc">
<a href="#toc-Section-5.1" class="Link">Section 5.1: Introduction</a>
</div>
<div class="toc">
<a href="#toc-Section-5.2" class="Link">Section 5.2: REST the hard way</a>
</div>
<div class="toc">
<a href="#toc-Section-5.3" class="Link">Section 5.3: Making it easier with <tt>RestHelper</tt></a>
</div>
<div class="toc">
<a href="#toc-Section-5.4" class="Link">Section 5.4: A complete REST example</a>
</div>
<div class="toc">
<a href="#toc-Section-5.5" class="Link">Section 5.5: Wrap Up</a>
</div>
</div>
<div class="toc">
<a href="#toc-Chapter-6" class="Link">Chapter 6: Wiring</a>
</div>
<div class="tocindent">
<div class="toc">
<a href="#toc-Section-6.1" class="Link">Section 6.1: Cells</a>
</div>
<div class="toc">
<a href="#toc-Section-6.2" class="Link">Section 6.2: Hooking it up to the UI</a>
</div>
<div class="toc">
<a href="#toc-Section-6.3" class="Link">Section 6.3: Shared Shopping</a>
</div>
<div class="toc">
<a href="#toc-Section-6.4" class="Link">Section 6.4: Wrap up</a>
</div>
</div>
<div class="toc">
<a href="#toc-Chapter-7" class="Link">Chapter 7: Core Concepts</a>
</div>
<div class="tocindent">
<div class="toc">
<a href="#toc-Section-7.1" class="Link">Section 7.1: Snippets</a>
</div>
<div class="tocindent">
<div class="toc">
<a href="#toc-Subsection-7.1.1" class="Link">Subsection 7.1.1: Snippet <tt>NodeSeq =&gt; NodeSeq</tt></a>
</div>
<div class="toc">
<a href="#toc-Subsection-7.1.2" class="Link">Subsection 7.1.2: Snippet instances</a>
</div>
<div class="toc">
<a href="#toc-Subsection-7.1.3" class="Link">Subsection 7.1.3: Multiple methods on a snippet class</a>
</div>
<div class="toc">
<a href="#toc-Subsection-7.1.4" class="Link">Subsection 7.1.4: Inter-snippet communication</a>
</div>
<div class="toc">
<a href="#toc-Subsection-7.1.5" class="Link">Subsection 7.1.5: Recursive Snippets</a>
</div>
<div class="toc">
<a href="#toc-Subsection-7.1.6" class="Link">Subsection 7.1.6: Snippet parameters</a>
</div>
</div>
<div class="toc">
<a href="#toc-Section-7.2" class="Link">Section 7.2: Box/Option</a>
</div>
<div class="toc">
<a href="#toc-Section-7.3" class="Link">Section 7.3: S/SHtml</a>
</div>
<div class="toc">
<a href="#toc-Section-7.4" class="Link">Section 7.4: Boot</a>
</div>
<div class="toc">
<a href="#toc-Section-7.5" class="Link">Section 7.5: SiteMap</a>
</div>
<div class="toc">
<a href="#toc-Section-7.6" class="Link">Section 7.6: GUIDs</a>
</div>
<div class="tocindent">
<div class="toc">
<a href="#toc-Subsection-7.6.1" class="Link">Subsection 7.6.1: How GUIDs are generated</a>
</div>
<div class="toc">
<a href="#toc-Subsection-7.6.2" class="Link">Subsection 7.6.2: Where they are used </a>
</div>
</div>
<div class="toc">
<a href="#toc-Section-7.7" class="Link">Section 7.7: LiftRules</a>
</div>
<div class="toc">
<a href="#toc-Section-7.8" class="Link">Section 7.8: SessionVars and RequestVars</a>
</div>
<div class="toc">
<a href="#toc-Section-7.9" class="Link">Section 7.9: Helpers</a>
</div>
<div class="toc">
<a href="#toc-Section-7.10" class="Link">Section 7.10: CSS Selector Transforms</a>
</div>
<div class="toc">
<a href="#toc-Section-7.11" class="Link">Section 7.11: Client-side behavior invoking server-side functions</a>
</div>
<div class="toc">
<a href="#toc-Section-7.12" class="Link">Section 7.12: Ajax</a>
</div>
<div class="toc">
<a href="#toc-Section-7.13" class="Link">Section 7.13: Comet</a>
</div>
<div class="toc">
<a href="#toc-Section-7.14" class="Link">Section 7.14: LiftActor</a>
</div>
<div class="toc">
<a href="#toc-Section-7.15" class="Link">Section 7.15: Pattern Matching</a>
</div>
<div class="toc">
<a href="#toc-Section-7.16" class="Link">Section 7.16: Type safety</a>
</div>
<div class="toc">
<a href="#toc-Section-7.17" class="Link">Section 7.17: Page rewriting</a>
</div>
<div class="toc">
<a href="#toc-Section-7.18" class="Link">Section 7.18: Security</a>
</div>
</div>
<div class="toc">
<a href="#toc-Chapter-8" class="Link">Chapter 8: Common Patterns</a>
</div>
<div class="tocindent">
<div class="toc">
<a href="#toc-Section-8.1" class="Link">Section 8.1: Localization</a>
</div>
<div class="tocindent">
<div class="toc">
<a href="#toc-Subsection-8.1.1" class="Link">Subsection 8.1.1: Localizing Templates</a>
</div>
<div class="toc">
<a href="#toc-Subsection-8.1.2" class="Link">Subsection 8.1.2: Resource Lookup</a>
</div>
<div class="toc">
<a href="#toc-Subsection-8.1.3" class="Link">Subsection 8.1.3: Accessing Resources</a>
</div>
<div class="toc">
<a href="#toc-Subsection-8.1.4" class="Link">Subsection 8.1.4: Conclusion</a>
</div>
</div>
<div class="toc">
<a href="#toc-Section-8.2" class="Link">Section 8.2: Dependency Injection</a>
</div>
<div class="tocindent">
<div class="toc">
<a href="#toc-Subsection-8.2.1" class="Link">Subsection 8.2.1: Lift Libraries and Injector</a>
</div>
<div class="toc">
<a href="#toc-Subsection-8.2.2" class="Link">Subsection 8.2.2: Lift WebKit and enhanced injection scoping </a>
</div>
<div class="toc">
<a href="#toc-Subsection-8.2.3" class="Link">Subsection 8.2.3: Conclusion </a>
</div>
</div>
<div class="toc">
<a href="#toc-Section-8.3" class="Link">Section 8.3: Modules</a>
</div>
<div class="toc">
<a href="#toc-Section-8.4" class="Link">Section 8.4: HtmlProperties, XHTML and HTML5</a>
</div>
<div class="tocindent">
<div class="toc">
<a href="#toc-Subsection-8.4.1" class="Link">Subsection 8.4.1: XHTML via <tt>OldHtmlProperties</tt></a>
</div>
<div class="toc">
<a href="#toc-Subsection-8.4.2" class="Link">Subsection 8.4.2: HTML5 via <tt>Html5Properties</tt></a>
</div>
<div class="toc">
<a href="#toc-Subsection-8.4.3" class="Link">Subsection 8.4.3: Changing behavior mid-session or mid-request</a>
</div>
</div>
</div>
<div class="toc">
<a href="#toc-Chapter-9" class="Link">Chapter 9: Built-in Snippets</a>
</div>
<div class="tocindent">
<div class="toc">
<a href="#toc-Section-9.1" class="Link">Section 9.1: CSS</a>
</div>
<div class="toc">
<a href="#toc-Section-9.2" class="Link">Section 9.2: Msgs</a>
</div>
<div class="toc">
<a href="#toc-Section-9.3" class="Link">Section 9.3: Msg</a>
</div>
<div class="toc">
<a href="#toc-Section-9.4" class="Link">Section 9.4: Menu</a>
</div>
<div class="toc">
<a href="#toc-Section-9.5" class="Link">Section 9.5: A</a>
</div>
<div class="toc">
<a href="#toc-Section-9.6" class="Link">Section 9.6: Children</a>
</div>
<div class="toc">
<a href="#toc-Section-9.7" class="Link">Section 9.7: Comet</a>
</div>
<div class="toc">
<a href="#toc-Section-9.8" class="Link">Section 9.8: Form</a>
</div>
<div class="toc">
<a href="#toc-Section-9.9" class="Link">Section 9.9: Ignore</a>
</div>
<div class="toc">
<a href="#toc-Section-9.10" class="Link">Section 9.10: Loc</a>
</div>
<div class="toc">
<a href="#toc-Section-9.11" class="Link">Section 9.11: Surround</a>
</div>
<div class="toc">
<a href="#toc-Section-9.12" class="Link">Section 9.12: TestCond</a>
</div>
<div class="toc">
<a href="#toc-Section-9.13" class="Link">Section 9.13: Embed</a>
</div>
<div class="toc">
<a href="#toc-Section-9.14" class="Link">Section 9.14: Tail</a>
</div>
<div class="toc">
<a href="#toc-Section-9.15" class="Link">Section 9.15: WithParam</a>
</div>
<div class="toc">
<a href="#toc-Section-9.16" class="Link">Section 9.16: VersionInfo</a>
</div>
<div class="toc">
<a href="#toc-Section-9.17" class="Link">Section 9.17: SkipDocType</a>
</div>
<div class="toc">
<a href="#toc-Section-9.18" class="Link">Section 9.18: XmlGroup</a>
</div>
<div class="toc">
<a href="#toc-Section-9.19" class="Link">Section 9.19: LazyLoad</a>
</div>
<div class="toc">
<a href="#toc-Section-9.20" class="Link">Section 9.20: WithResourceId</a>
</div>
</div>
<div class="toc">
<a href="#toc-Chapter-10" class="Link">Chapter 10: SiteMap</a>
</div>
<div class="toc">
<a href="#toc-Chapter-11" class="Link">Chapter 11: REST</a>
</div>
<div class="toc">
<a href="#toc-Chapter-12" class="Link">Chapter 12: MVC (If you really want it)</a>
</div>
<div class="toc">
<a href="#toc-Chapter-13" class="Link">Chapter 13: From MVC</a>
</div>
<div class="tocindent">
<div class="toc">
<a href="#toc-Section-13.1" class="Link">Section 13.1: First things first</a>
</div>
<div class="toc">
<a href="#toc-Section-13.2" class="Link">Section 13.2: Making a <tt>SiteMap</tt> entry</a>
</div>
<div class="toc">
<a href="#toc-Section-13.3" class="Link">Section 13.3: Creating the view</a>
</div>
<div class="toc">
<a href="#toc-Section-13.4" class="Link">Section 13.4: Creating the Snippet</a>
</div>
<div class="toc">
<a href="#toc-Section-13.5" class="Link">Section 13.5: Getting Ajaxy</a>
</div>
<div class="toc">
<a href="#toc-Section-13.6" class="Link">Section 13.6: Next Steps</a>
</div>
</div>
</div>
<div class="toc">
<a href="#toc-Part-II" class="Link">Part II: Recipes</a>
</div>
<div class="tocindent">
<div class="toc">
<a href="#toc-Chapter-14" class="Link">Chapter 14: Dynamic html tables created from <tt>DB.runQuery()</tt></a>
</div>
<div class="tocindent">
<div class="toc">
<a href="#toc-Section-14.1" class="Link">Section 14.1: Problem</a>
</div>
<div class="toc">
<a href="#toc-Section-14.2" class="Link">Section 14.2: Solution</a>
</div>
</div>
<div class="toc">
<a href="#toc-Chapter-15" class="Link">Chapter 15: Dynamically choosing content</a>
</div>
<div class="tocindent">
<div class="toc">
<a href="#toc-Section-15.1" class="Link">Section 15.1: Problem</a>
</div>
<div class="toc">
<a href="#toc-Section-15.2" class="Link">Section 15.2: Solution</a>
</div>
</div>
<div class="toc">
<a href="#toc-Chapter-16" class="Link">Chapter 16: Ajax Forms</a>
</div>
<div class="toc">
<a href="#toc-Chapter-17" class="Link">Chapter 17: Protecting REST APIs</a>
</div>
<div class="tocindent">
<div class="toc">
<a href="#toc-Section-17.1" class="Link">Section 17.1: Problem</a>
</div>
<div class="toc">
<a href="#toc-Section-17.2" class="Link">Section 17.2: Solution</a>
</div>
</div>
<div class="toc">
<a href="#toc-Chapter-18" class="Link">Chapter 18: URI-based locale selection</a>
</div>
<div class="tocindent">
<div class="toc">
<a href="#toc-Section-18.1" class="Link">Section 18.1: Problem</a>
</div>
<div class="toc">
<a href="#toc-Section-18.2" class="Link">Section 18.2: Solution</a>
</div>
</div>
<div class="toc">
<a href="#toc-Chapter-19" class="Link">Chapter 19: Embedding JavaScript in an HTML page</a>
</div>
<div class="tocindent">
<div class="toc">
<a href="#toc-Section-19.1" class="Link">Section 19.1: Problem</a>
</div>
<div class="toc">
<a href="#toc-Section-19.2" class="Link">Section 19.2: Solution</a>
</div>
</div>
</div>
<div class="toc">
<a href="#toc-Part-III" class="Link">Part III: Questions and Answers</a>
</div>
<div class="tocindent">
<div class="toc">
<a href="#toc-Chapter-20" class="Link">Chapter 20: Scaling</a>
</div>
<div class="toc">
<a href="#toc-Chapter-21" class="Link">Chapter 21: How Lift does function/GUID mapping</a>
</div>
<div class="toc">
<a href="#toc-Chapter-22" class="Link">Chapter 22: How Lift does Comet</a>
</div>
<div class="toc">
<a href="#toc-Chapter-23" class="Link">Chapter 23: Advanced Concepts</a>
</div>
<div class="tocindent">
<div class="toc">
<a href="#toc-Section-23.1" class="Link">Section 23.1: Snippet Resolution</a>
</div>
<div class="tocindent">
<div class="toc">
<a href="#toc-Subsection-23.1.1" class="Link">Subsection 23.1.1: <tt>LiftSession.liftTagProcessing</tt></a>
</div>
<div class="toc">
<a href="#toc-Subsection-23.1.2" class="Link">Subsection 23.1.2: <tt>LiftRules.liftTagProcessing</tt></a>
</div>
<div class="toc">
<a href="#toc-Subsection-23.1.3" class="Link">Subsection 23.1.3: Snippet name resolution</a>
</div>
<div class="toc">
<a href="#toc-Subsection-23.1.4" class="Link">Subsection 23.1.4: Post-processing of results</a>
</div>
</div>
<div class="toc">
<a href="#toc-Section-23.2" class="Link">Section 23.2: The Merging Phase</a>
</div>
</div>
</div>
<div class="toc">
<a href="#toc-Part-IV" class="Link">Part IV: Misc</a>
</div>
<div class="tocindent">
<div class="toc">
<a href="#toc-Chapter-24" class="Link">Chapter 24: Releases</a>
</div>
<div class="tocindent">
<div class="toc">
<a href="#toc-Section-24.1" class="Link">Section 24.1: Lift 2.2-RC1</a>
</div>
<div class="tocindent">
<div class="toc">
<a href="#toc-Subsection--1" class="Link">Subsection: Lift features include:</a>
</div>
<div class="toc">
<a href="#toc-Subsection--2" class="Link">Subsection: Lift 2.2-RC1 improvements include:</a>
</div>
<div class="toc">
<a href="#toc-Subsection--3" class="Link">Subsection: Lift-powered sites include:</a>
</div>
</div>
<div class="toc">
<a href="#toc-Section-24.2" class="Link">Section 24.2: Lift 2.2</a>
</div>
<div class="tocindent">
<div class="toc">
<a href="#toc-Subsection--4" class="Link">Subsection: Lift features include:</a>
</div>
<div class="toc">
<a href="#toc-Subsection--5" class="Link">Subsection: Lift 2.2 improvements include:</a>
</div>
<div class="toc">
<a href="#toc-Subsection--6" class="Link">Subsection: Lift-powered sites include:</a>
</div>
</div>
</div>
</div>
<div class="toc">
<a href="#Index" class="Link">Index</a>
</div>

</div>
<div class="fulltoc">
<div class="tocheader">
List of Figures
</div>

</div>
<h1 class="Part">
<a name="toc-Part-I" class="toc">Part I.</a> The Lift Web Framework
</h1>
<h1 class="Chapter">
<a name="toc-Chapter-1" class="toc">1</a> Introduction
</h1>
<div class="Standard">
The Lift Web Framework provides web application developers tools to make writing security, interacting, scalable web applications easier than with any other web framework. After reading Part I of this book, you should understand Lift’s core concepts and be able to write Lift applications. But with anything, practice is important. I have been writing Lift and Scala for 4 years, and even I learn new things about the language and the framework on a weekly basis. Please consider Lift an path and an exploration, rather than an end point.
</div>
<div class="Standard">
“Yo, David, stop yer yappin’. I’m coming from Rails|Spring|Struts|Django and I want to get started super fast with Lift.” See From MVC (<a href="#cha:From-MVC" class="Reference">13 on page 1↓</a>).
</div>
<div class="Standard">
Lift is built on top of the <a href="http://scala-lang.org" class="URL">Scala</a> programming language. Scala runs on the <a href="http://www.oracle.com/technetwork/java/index.html" class="URL">Java Virtual Machine</a>. Lift applications are typically packaged as <a href="http://en.wikipedia.org/wiki/WAR_(Sun_file_format)" class="URL">WAR</a> files and run as a <a href="http://www.oracle.com/technetwork/java/index-jsp-135475.html" class="URL">J/EE Servlets</a> or Servlet Filters. This book will provide you with the core concepts you need to successfully write Lift web applications. The book assumes knowledge of Servlets and Servlet containers, the Scala Language (Chapters 1-6 of <i><a href="http://apress.com/book/view/9781430219897" class="URL">Beginning Scala</a></i> gives you a good grounding in the language), build tools, program editors, web development including HTML and JavaScript, etc. Further, this book will not explore persistence. Lift has additional modules for persisting to relational and non-relational data stores. Lift doesn’t distinguish as to how an object is materialized into the address space... Lift can treat any object any old way you want. There are many resources (including <a href="http://exploring.liftweb.net/" class="URL">Exploring Lift</a>) that cover ways to persist data from a JVM.
</div>
<div class="Standard">
Lift is different from most web frameworks and it’s likely that Lift’s differences will present a challenge and a friction if you are familiar with the MVC<a href="#index-MVC" name="entry-MVC-0" class="IndexReference">↓</a> school of web frameworks<span class="FootOuter"><span class="SupFootMarker"> [A] </span><span class="HoverFoot"><span class="SupFootMarker"> [A] </span>This includes Ruby on Rails, Struts, Java Server Faces, Django, TurboGears, etc.</span></span>. But Lift is different and Lift’s differences give you more power to create interactive applications. Lift’s differences lead to more concise web applications. Lift’s differences result in more secure and scalable applications. Lift’s differences let you be more productive and make maintaining applications easier for the future you or whoever is writing your applications. Please relax and work to understand Lift’s differences... and see how you can make best use of Lift’s features to build your web applications.
</div>
<div class="Standard">
Lift creates abstractions that allow easier expression of business logic and then maps those abstractions to HTTP and HTML. This approach differs from traditional web frameworks which build abstractions on top of HTTP and HTML and require the developer to bridge between common business logic patterns and the underlying protocol. The difference means that you spend more time thinking about your application and less time thinking about the plumbing.
</div>
<div class="Standard">
I am a “concept learner.” I learn concepts and then apply them over and over again as situations come up. This book focuses a lot on the concepts. If you’re a concept learner and like my stream on conciousness style, this book will likely suit you well. On the other hand, it may not.
</div>
<div class="Standard">
Up to date versions of this book are available in PDF form at <a href="http://simply.liftweb.net/Simply_Lift.pdf" class="FlexURL">http://simply.liftweb.net/Simply_Lift.pdf</a>. The source code for this book is available at <a href="https://github.com/dpp/simply_lift" class="URL">https://github.com/dpp/simply_lift</a>.
</div>
<div class="Standard">
If you’ve got questions, feedback, or improvements to this document, please join the conversation on the <a href="http://groups.google.com/group/liftweb" class="URL">Lift Google Group</a>.
</div>
<div class="Standard">
I’m a “roll up your sleaves and get your hands dirty with code” kinda guy... so let’s build a simple Chat application in Lift. This application will allow us to demonstrate some of Lift’s core features as well as giving a “smack in the face” demonstration of how Lift is different.
</div>
<h1 class="Chapter">
<a name="toc-Chapter-2" class="toc">2</a> <a name="cha:The-ubiquitous-Chat" class="Label"> </a>The ubiquitous Chat app
</h1>
<div class="Standard">
Writing a multi-user chat application in Lift is super-simple and illustrates many of Lift’s core concepts.
</div>
<div class="Standard">
The Source Code can be found at <a href="https://github.com/dpp/simply_lift/tree/master/chat" class="URL">https://github.com/dpp/simply_lift/tree/master/chat</a>.
</div>
<h2 class="Section">
<a name="toc-Section-2.1" class="toc">2.1</a> The View
</h2>
<div class="Standard">
When writing a Lift app, it’s often best to start off with the user interface... build what the user will see and then add behavior to the HTML page. So, let’s look at the Lift template that will make up our chat application.
</div>
<div class="Standard">

</div>
<div class="listing">
<div class="caption">
index.html
</div>
<pre class="listing brush: xml">&lt;!DOCTYPE html PUBLIC &quot;-//W3C//DTD XHTML 1.0 Transitional//EN&quot; 
          &quot;http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd&quot;&gt;
&lt;html xmlns=&quot;http://www.w3.org/1999/xhtml&quot;&gt;
  &lt;head&gt;&lt;title&gt;Home&lt;/title&gt;&lt;/head&gt;
  &lt;body class=&quot;lift:content_id=main&quot;&gt;
    &lt;div id=&quot;main&quot; class=&quot;lift:surround?with=default;at=content&quot;&gt;
      &lt;!-- the behavior of the div --&gt;
      &lt;div class=&quot;lift:comet?type=Chat&quot;&gt; 
        Some chat messages
        &lt;ul&gt;
          &lt;li&gt;A message&lt;/li&gt;
          &lt;li class=&quot;clearable&quot;&gt;Another message&lt;/li&gt;
          &lt;li class=&quot;clearable&quot;&gt;A third message&lt;/li&gt;
        &lt;/ul&gt;
      &lt;/div&gt;
      
      &lt;div&gt;
        &lt;form class=&quot;lift:form.ajax&quot;&gt;
          &lt;input class=&quot;lift:ChatIn&quot; id=&quot;chat_in&quot;/&gt;
          &lt;input type=&quot;submit&quot; value=&quot;Say Something&quot;/&gt;
        &lt;/form&gt;
      &lt;/div&gt;
    &lt;/div&gt;
  &lt;/body&gt;
&lt;/html&gt;
​
</pre>
</div>
<div class="Standard">
It’s a valid HTML page, but there are some hinky looking class attributes. The first one is <tt>&lt;body class=&quot;lift:content_id=main&quot;&gt;</tt>. The class in this case says “the actual page content is contained by the element with id=’main’.” This allows you to have valid HTML pages for each of your templates, but dynamically add “chrome” around the content based on one or more chrome templates.
</div>
<div class="Standard">
Let’s look at the <tt>&lt;div id=&quot;main&quot;&gt;</tt>. It’s got a funky class as well: <tt>lift:surround?with=default;at=content</tt>. This class invokes a snippet which surrounds the <tt>&lt;div&gt;</tt> with the default template and inserts the <tt>&lt;div&gt;</tt> and its children at the element with id “content” in the default template. Or, it wraps the default chrome around the <tt>&lt;div&gt;</tt>. For more on snippets, see <a href="#sec:Snippets" class="Reference">7.1 on page 1↓</a>.
</div>
<div class="Standard">
Next, we define how we associate dynamic behavior with the list of chat elements: <tt>&lt;div class=&quot;lift:comet?type=Chat&quot;&gt;</tt>. The “comet” snippet looks for a class named <tt>Chat</tt> that extends <tt>CometActor</tt> and enables the mechanics of pushing content from the <tt>CometActor</tt> to the browser when the state of the <tt>CometActor</tt> changes. 
</div>
<h2 class="Section">
<a name="toc-Section-2.2" class="toc">2.2</a> The Chat Comet component
</h2>
<div class="Standard">
The <a href="http://en.wikipedia.org/wiki/Actor_model" class="URL">Actor Model</a> provides state in functional languages include Erlang. Lift has an Actor library and LiftActors (see <a href="#sec:LiftActor" class="Reference">7.14↓</a>) provides a powerful state and concurrency model. This may all seem abstract, so let’s look at the <tt>Chat</tt> class.
</div>
<div class="Standard">

</div>
<div class="listing">
<div class="caption">
Chat.scala
</div>
<pre class="listing brush: scala">package code
package comet
​
import net.liftweb._
import http._
import util._
import Helpers._
​
/**
 * The screen real estate on the browser will be represented
 * by this component.  When the component changes on the server
 * the changes are automatically reflected in the browser.
 */
class Chat extends CometActor with CometListener {
  private var msgs: Vector[String] = Vector() // private state
​
  /**
   * When the component is instantiated, register as
   * a listener with the ChatServer
   */
  def registerWith = ChatServer
​
  /**
   * The CometActor is an Actor, so it processes messages.
   * In this case, we're listening for Vector[String],
   * and when we get one, update our private state
   * and reRender() the component.  reRender() will
   * cause changes to be sent to the browser.
   */
  override def lowPriority = {
    case v: Vector[String] =&gt; msgs = v; reRender()
  }
​
  /**
   * Put the messages in the li elements and clear
   * any elements that have the clearable class.
   */
  def render = &quot;li *&quot; #&gt; msgs &amp; ClearClearable
}
</pre>
</div>
<div class="Standard">
The <tt>Chat</tt> component has private state, registers with the <tt>ChatServer</tt>, handles incoming messages and can render itself. Let’s look at each of those pieces.
</div>
<div class="Standard">
The private state, like any private state in prototypical object oriented code, is the state that defines the object’s behavior.
</div>
<div class="Standard">
registerWith is a method that defines what component to register the Chat component with. Registration is a part of the Listener (or <a href="http://en.wikipedia.org/wiki/Observer_pattern" class="URL">Observer</a>) pattern. We’ll look at the definition of the <tt>ChatServer</tt> in a minute.
</div>
<div class="Standard">
The <tt>lowPriority</tt> method defines how to process incoming messages. In this case, we’re Pattern Matching (see <a href="#sec:Pattern-Matching" class="Reference">↓</a>) the incoming message and if it’s a <tt>Vector[String]</tt>, then we perform the action of setting our local state to the <tt>Vector</tt> and re-rendering the component. The re-rendering will force the changes out to any browser that is displaying the component.
</div>
<div class="Standard">
We define how to <tt>render</tt> the component by defining the CSS to match and the replacement (See <a href="#sec:CSS-Selector-Transforms" class="Reference">↓</a>). We match all the <tt>&lt;li&gt;</tt> tags of the template and for each message, create an <tt>&lt;li&gt;</tt> tag with the child nodes set to the message. Additionally, we clear all the elements that have the <tt>clearable</tt> in the <tt>class</tt> attribute.
</div>
<div class="Standard">
That’s it for the Chat CometActor component.
</div>
<h2 class="Section">
<a name="toc-Section-2.3" class="toc">2.3</a> The <tt>ChatServer</tt>
</h2>
<div class="Standard">
The ChatServer code is:
</div>
<div class="Standard">

</div>
<div class="listing">
<div class="caption">
ChatServer.scala
</div>
<pre class="listing brush: scala">package code
package comet
​
import net.liftweb._
import http._
import actor._
​
/**
 * A singleton that provides chat features to all clients.
 * It's an Actor so it's thread-safe because only one
 * message will be processed at once.
 */
object ChatServer extends LiftActor with ListenerManager {
  private var msgs = Vector(&quot;Welcome&quot;) // private state
​
  /**
   * When we update the listeners, what message do we send?
   * We send the msgs, which is an immutable data structure,
   * so it can be shared with lots of threads without any
   * danger or locking.
   */
  def createUpdate = msgs
​
  /**
   * process messages that are sent to the Actor.  In
   * this case, we're looking for Strings that are sent
   * to the ChatServer.  We append them to our Vector of
   * messages, and then update all the listeners.
   */
  override def lowPriority = {
    case s: String =&gt; msgs :+= s; updateListeners()
  }
}
</pre>
</div>
<div class="Standard">
The <tt>ChatServer</tt> is defined as an <tt>object</tt> rather than a <tt>class</tt>. This makes it a singleton which can be referenced by the name <tt>ChatServer</tt> anywhere in the application. Scala’s singletons differ from Java’s <tt>static</tt> in that the singleton is an instance of an object and that instance can be passed around like any other instance. This is why we can return the <tt>ChatServer</tt> instance from the <tt>registerWith</tt> method in that <tt>Chat</tt> component.
</div>
<div class="Standard">
The ChatServer has private state, a <tt>Vector[String]</tt> representing the list of chat messages. Note that Scala’s type inferencer infers the type of <tt>msgs</tt> so you do not have to explicitly define it.
</div>
<div class="Standard">
The <tt>createUpdate</tt> method generates an update to send to listeners. This update is sent when a listener registers with the <tt>ChatServer</tt> or when the <tt>updateListeners()</tt> method is invoked.
</div>
<div class="Standard">
Finally, the <tt>lowPriority</tt> method defines the messages that this component can handle. If the <tt>ChatServer</tt> receives a <tt>String</tt> as a message, it appends the <tt>String</tt> to the <tt>Vector</tt> of messages and updates listeners.
</div>
<h2 class="Section">
<a name="toc-Section-2.4" class="toc">2.4</a> User Input
</h2>
<div class="Standard">
Let’s go back to the view and see how the behavior is defined for adding lines to the chat.
</div>
<div class="Standard">
<tt>&lt;form class=&quot;lift:form.ajax&quot;&gt;</tt> defines an input form and the <tt>form.ajax</tt> snippet turns a form into an Ajax (see <a href="#sec:Ajax" class="Reference">↓</a>) form that will be submitted back to the server without causing a full page load.
</div>
<div class="Standard">
Next, we define the input form element: <tt>&lt;input class=&quot;lift:ChatIn&quot; id=&quot;chat_in&quot;/&gt;</tt>. It’s a plain old input form, but we’ve told Lift to modify the <tt>&lt;input&gt;</tt>’s behavior by calling the <tt>ChatIn</tt> snippet.
</div>
<h2 class="Section">
<a name="toc-Section-2.5" class="toc">2.5</a> Chat In
</h2>
<div class="Standard">
The <tt>ChatIn</tt> snippet (See <a href="#sec:Snippets" class="Reference">↓</a>) is defined as:
</div>
<div class="Standard">

</div>
<div class="listing">
<div class="caption">
ChatIn.scala
</div>
<pre class="listing brush: scala">package code
package snippet
​
import net.liftweb._
import http._
import js._
import JsCmds._
import JE._
​
import comet.ChatServer
​
/**
 * A snippet transforms input to output... it transforms
 * templates to dynamic content.  Lift's templates can invoke
 * snippets and the snippets are resolved in many different
 * ways including &quot;by convention&quot;.  The snippet package
 * has named snippets and those snippets can be classes
 * that are instantiated when invoked or they can be
 * objects, singletons.  Singletons are useful if there's
 * no explicit state managed in the snippet.
 */
object ChatIn {
​
  /**
   * The render method in this case returns a function
   * that transforms NodeSeq =&gt; NodeSeq.  In this case,
   * the function transforms a form input element by attaching
   * behavior to the input.  The behavior is to send a message
   * to the ChatServer and then returns JavaScript which
   * clears the input.
   */
  def render = SHtml.onSubmit(s =&gt; {
    ChatServer ! s
    SetValById(&quot;chat_in&quot;, &quot;&quot;)
  })
}
</pre>
</div>
<div class="Standard">
The code is very simple. The snippet is defined as a method that associates a function with form element submission, <tt>onSubmit</tt>. When the element is submitted, be that normal form submission, Ajax, or whatever, the function is applied to the value of the form. In English, when the user submits the form, the function is called with the user’s input.
</div>
<div class="Standard">
The function sends the input as a message to the <tt>ChatServer</tt> and returns JavaScript that sets the value of the input box to a blank string.
</div>
<h2 class="Section">
<a name="toc-Section-2.6" class="toc">2.6</a> Running it
</h2>
<div class="Standard">
Running the application is easy. Make sure you’ve got Java 1.6 or better installed on your machine. Change directories into the <tt>chat</tt> directory and type <tt>sbt update ~jetty-run</tt>. The Simple Build Tool will download all necessary dependencies, compile the program and run it.
</div>
<div class="Standard">
You can point a couple of browsers to <a href="http://localhost:8080" class="FlexURL">http://localhost:8080</a> and start chatting.
</div>
<div class="Standard">
Oh, and for fun, try entering <tt>&lt;script&gt;alert(’I ownz your browser’);&lt;script&gt;</tt> and see what happens. You’ll note it’s what you want to happen.
</div>
<h2 class="Section">
<a name="toc-Section-2.7" class="toc">2.7</a> What you don’t see
</h2>
<div class="Standard">
Excluding imports and comments, there are about 20 lines of Scala code to implement a multi-threaded, multi-user chat application. That’s not a lot.
</div>
<div class="Standard">
The first thing that’s missing is synchronization or other explicit forms of thread locking. The application takes advantage of Actors and immutable data structures, thus the developer can focus on the business logic rather than the threading and locking primatives.
</div>
<div class="Standard">
The next thing that’s missing is routing and controllers and other stuff that you might have to do to wire up Ajax calls and polling for server-side changes (long or otherwise). In our application, we associated behavior with display and Lift took care of the rest (see <a href="#sec:Page-rewriting" class="Reference">↓</a>).
</div>
<div class="Standard">
We didn’t do anything to explicitly to avoid cross-site scripting in our application. Because Lift takes advantage of Scala’s strong typing and type safety (see <a href="#sec:Type-safety" class="Reference">↓</a>), Lift knows the difference between a String that must be HTML encoded and an HTML element that’s already properly encoded. By default, Lift applications are resistant to many of the OWASP top 10 security vulnerabilities (see <a href="#sec:Security" class="Reference">↓</a>).
</div>
<div class="Standard">
This example shows many of Lift’s strengths. Let’s expand the application and see how Lift’s strengths continue to support the development of the application.
</div>
<div class="Standard">

</div>
<h1 class="Chapter">
<a name="toc-Chapter-3" class="toc">3</a> <a name="cha:Snippets-and-SiteMap" class="Label"> </a>Snippets and SiteMap
</h1>
<div class="Standard">
Lift services HTTP request in three ways: generating HTML pages, low level HTTP responses (e.g., REST), and responding to Ajax/Comet requests. Lift treats each type of request differently to make the semantics for responding to each type of request most natural. Put another way, it’s different to build a complex HTML page with lots of different components than to send back some JSON data that corresponds to a database record.
</div>
<div class="Standard">
In this chapter, we’re going to explore how Lift does dynamic HTML page generation based on the incoming HTTP request and URL including putting “chrome” around the HTML page (menus, etc.), placing dynamic content on each page, and site navigation including access control.
</div>
<div class="Standard">
The code for this chapter can be found in the <tt>samples/snippet_and_sitemap</tt> directory of the <i>Simply Lift</i> <a href="https://github.com/dpp/simply_lift/tarball/master" class="URL">distribution</a>.
</div>
<h2 class="Section">
<a name="toc-Section-3.1" class="toc">3.1</a> Starting at the beginning: <tt>Boot.scala</tt>
</h2>
<div class="Standard">
When your Lift application first starts up, it executes the code in Boot.scala:
</div>
<div class="listing">
<div class="caption">
Boot.scala
</div>
<pre class="listing brush: scala">package bootstrap.liftweb
​
import net.liftweb._
import util._
import Helpers._
​
import common._
import http._
import sitemap._
import Loc._
​
import code.snippet._
​
/**
 * A class that's instantiated early and run.  It allows the application
 * to modify lift's environment
 */
class Boot {
  /**
   * Calculate if the page should be displayed.
   * In this case, it will be visible every other minute
   */
  def displaySometimes_? : Boolean = 
    (millis / 1000L / 60L) % 2 == 0
​
  def boot {
    // where to search snippet
    LiftRules.addToPackages(&quot;code&quot;)
​
    // Build SiteMap
    def sitemap(): SiteMap = SiteMap(
      Menu.i(&quot;Home&quot;) / &quot;index&quot;, // the simple way to declare a menu
​
      Menu.i(&quot;Sometimes&quot;) / &quot;sometimes&quot; &gt;&gt; If(displaySometimes_? _,
                                            S ? &quot;Can't view now&quot;), 
​
      // A menu with submenus
      Menu.i(&quot;Info&quot;) / &quot;info&quot; submenus(
        Menu.i(&quot;About&quot;) / &quot;about&quot; &gt;&gt; Hidden &gt;&gt; LocGroup(&quot;bottom&quot;),
        Menu.i(&quot;Contact&quot;) / &quot;contact&quot;,
        Menu.i(&quot;Feedback&quot;) / &quot;feedback&quot; &gt;&gt; LocGroup(&quot;bottom&quot;)
      ),
      
​
      Menu.i(&quot;Sitemap&quot;) / &quot;sitemap&quot; &gt;&gt; Hidden &gt;&gt; LocGroup(&quot;bottom&quot;),
​
      Menu.i(&quot;Dynamic&quot;) / &quot;dynamic&quot;, // a page with dynamic content
​
      Param.menu,
​
      Menu.param[Which](&quot;Recurse&quot;, &quot;Recurse&quot;,
                        {case &quot;one&quot; =&gt; Full(First())
                         case &quot;two&quot; =&gt; Full(Second())
                         case &quot;both&quot; =&gt; Full(Both())
                         case _ =&gt; Empty},
                        w =&gt; w.toString) / &quot;recurse&quot;,
      
      // more complex because this menu allows anything in the
      // /static path to be visible
      Menu.i(&quot;Static&quot;) / &quot;static&quot; / **)
​
    // set the sitemap.  Note if you don't want access control for
    // each page, just comment this line out.
    LiftRules.setSiteMapFunc(() =&gt; sitemap())
​
    //Show the spinny image when an Ajax call starts
    LiftRules.ajaxStart =
      Full(() =&gt; LiftRules.jsArtifacts.show(&quot;ajax-loader&quot;).cmd)
    
    // Make the spinny image go away when it ends
    LiftRules.ajaxEnd =
      Full(() =&gt; LiftRules.jsArtifacts.hide(&quot;ajax-loader&quot;).cmd)
​
    // Force the request to be UTF-8
    LiftRules.early.append(_.setCharacterEncoding(&quot;UTF-8&quot;))
​
    // Use HTML5 for rendering
    LiftRules.htmlProperties.default.set((r: Req) =&gt;
      new Html5Properties(r.userAgent))    
  }
}
</pre>
</div>
<div class="Standard">
Rather than keeping configuration parameters in XML files, Lift keeps configuration parameters in code in <tt>Boot</tt>. Boot is executed once when the servlet container loads the Lift application. You can change many of Lift’s execution rules in the <tt>LiftRules</tt> singleton during boot, but after boot, these parameters are frozen.
</div>
<h3 class="Subsection">
<a name="toc-Subsection-3.1.1" class="toc">3.1.1</a> <tt>LiftRules</tt> rules
</h3>
<div class="Standard">
Most of the configuration parameters that define how Lift will convert an HTTP request into a response are contained in the <tt>LiftRules</tt> singleton. Some of the parameters for <tt>LiftRules</tt> are used commonly and some are very infrequently changed from their default. LiftRules can be changed during boot, but not at other times. So, set all your configuration in boot (or in methods that are called from boot).
</div>
<h3 class="Subsection">
<a name="toc-Subsection-3.1.2" class="toc">3.1.2</a> Properties and Run modes
</h3>
<div class="Standard">
While many properties for your running application can be defined in <tt>Boot.scala</tt>, there are some properties that are best defined in a text file. Lift supports multiple properties files per project. The properties files are loaded based on the user, machine and run mode.
</div>
<div class="Standard">
If you want to provide a configuration file for a subset of your application or for a specific environment, Lift expects configuration files to be named in a manner relating to the context in which they are being used. The standard name format is:
</div>
<div class="Standard">
<tt>modeName.userName.hostName.props</tt>
</div>
<div class="Standard">
examples:<tt><br/>
dpp.yak.props<br/>
test.dpp.yak.props<br/>
production.moose.props<br/>
staging.dpp.props<br/>
test.default.props<br/>
default.props</tt>
</div>
<div class="Standard">
with hostName and userName being optional, and modeName being one of &quot;test&quot;, &quot;staging&quot;, &quot;production&quot;, &quot;pilot&quot;, &quot;profile&quot;, or blank (for development mode). The standard Lift properties file extension is &quot;props&quot;.
</div>
<div class="Standard">
Place properties files in the <tt>src/main/resources/props</tt> directory in your project and they will be packaged up as part of the build process.
</div>
<div class="Standard">
When you’re developing your Lift application, the run mode (see <tt>net.liftweb.util.Props.mode</tt>) will be <tt>Development</tt>. When you deploy your application, pass <tt>-Drun.mode=production</tt> to your web container. In production mode, Lift aggressively caches templates, snippet classes, etc.
</div>
<h3 class="Subsection">
<a name="toc-Subsection-3.1.3" class="toc">3.1.3</a> By convention
</h3>
<div class="Standard">
Lift, like Rails, will look for items in certain locations by convention. For example, Lift will look for classes that implement snippets in the <tt>xxx.snippet</tt> package where the xxx part is the main package for your application. You define one or more packages for Lift to look in with:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: scala">    // where to search snippet
    LiftRules.addToPackages(&quot;code&quot;)
</pre>
</div>

</div>
<div class="Standard">
Here, we’ve added the <tt>code</tt> package to the list of packages that Lift will search through. You can also do <tt>LiftRules.addToPackages(&quot;com.fruitbat.mydivision.myapplication&quot;)</tt>.
</div>
<h3 class="Subsection">
<a name="toc-Subsection-3.1.4" class="toc">3.1.4</a> Misc Rules
</h3>
<div class="Standard">
We’ll skip the sitemap definition until the next section. This rule defines how to show a spinning icon during Ajax calls (Lift will automatically show the spinning icon if this function is enabled):
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: scala">    //Show the spinny image when an Ajax call starts
    LiftRules.ajaxStart =
      Full(() =&gt; LiftRules.jsArtifacts.show(&quot;ajax-loader&quot;).cmd)
</pre>
</div>

</div>
<div class="Standard">
And this rule sets the default character encoding to UTF-8 rather than the default platform encoding:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: scala">    // Force the request to be UTF-8
    LiftRules.early.append(_.setCharacterEncoding(&quot;UTF-8&quot;))
</pre>
</div>

</div>
<div class="Standard">
Okay... you get the idea... there are plenty of parameters to tune during boot.
</div>
<h3 class="Subsection">
<a name="toc-Subsection-3.1.5" class="toc">3.1.5</a> Html5
</h3>
<div class="Standard">
Prior to Lift 2.2, Lift treated all templates as XHTML and emitted XHTML to the browser. When the Lift project started in early 2007, this seemed like a Really Good Idea™. Turns out the world has not adopted XHTML and some JavaScript libraries, e.g. Google Maps, doesn’t work on XHTML pages. Lift 2.2 introduced optional Html5 support both in the parser (so it could read Html5 templates rather than requiring well formed XML in templates) and emits Html5 to the browser. Lift still processes pages as Scala <tt>NodeSeq</tt> elements, so no changes are required to the application.
</div>
<div class="Standard">
In order to keep Lift 2.2 apps backward compatible with Lift’s XHTML support, by default the XHTML parser/serializer are used. However, it’s recommended to use the Html5 support which can be turned on in boot with:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: scala">    // Use HTML5 for rendering
    LiftRules.htmlProperties.default.set((r: Req) =&gt;
      new Html5Properties(r.userAgent))  
</pre>
</div>

</div>
<h2 class="Section">
<a name="toc-Section-3.2" class="toc">3.2</a> <a name="sec:SiteMap-1" class="Label"> </a><tt>SiteMap</tt>
</h2>
<div class="Standard">
Lift has an optional feature called SiteMap. You don’t have to use it. But if you do set a sitemap in boot, then Lift will use the sitemap as a white list of HTML pages for your site (note that REST URLs do not need to be listed in the sitemap). SiteMap defines navigation and access control, allows you to create hierarchical menus, grouped menu items, display the entire sitemap, a relative sitemap, as well breadcrumbs. This section will discuss some of SiteMap’s capabilities.
</div>
<h3 class="Subsection">
<a name="toc-Subsection-3.2.1" class="toc">3.2.1</a> Defining the <tt>SiteMap</tt>
</h3>
<div class="Standard">
The SiteMap must be defined in boot and is only defined once<span class="FootOuter"><span class="SupFootMarker"> [B] </span><span class="HoverFoot"><span class="SupFootMarker"> [B] </span>In development mode, the sitemap can be changed dynamically to support changes to site content without having to re-start your application each time navigation changes. This is a development-time feature only. There are significant performance penalties associated with rebuilding the sitemap on each page load including forcing the serialization of serving pages. There are plenty of features in SiteMap that allow you to enable/disable menu items and have dynamically generated submenus. Don’t rely on Lift’s development-mode menu reloading for your application design.</span></span>. Typically, you will define a function that returns a SiteMap instance:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: scala">    // Build SiteMap
    def sitemap(): SiteMap = ...
</pre>
</div>

</div>
<div class="Standard">
And then define the <tt>SiteMap</tt> in <tt>LiftRules</tt>:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: scala">    // set the sitemap.  Note if you don’t want access control for
    // each page, just comment this line out.
    LiftRules.setSiteMapFunc(() =&gt; sitemap())
</pre>
</div>

</div>
<div class="Standard">
In development mode, the function will be called on each page load to rebuilt the SiteMap. In all other Lift run modes, the sitemap will be built once during boot.
</div>
<div class="Standard">
A <tt>SiteMap</tt> is a collection of <tt>Menu</tt> instances. Each <tt>Menu</tt> has one <tt>Loc[_]</tt> and a set of <tt>Menu</tt> instances as submenus (zero or more). Each <tt>Menu</tt> instance has a unique name.
</div>
<div class="Standard">
If an HTML page is not defined in the sitemap, Lift will not serve it. SiteMap is a white list of pages to serve. Further, the <tt>Loc[_]</tt> has parameters that can include multiple access control rules.
</div>
<h3 class="Subsection">
<a name="toc-Subsection-3.2.2" class="toc">3.2.2</a> Simplest <tt>SiteMap</tt>
</h3>
<div class="Standard">
The simplest sitemap defines a single page:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: scala">    def sitemap(): SiteMap = SiteMap(Menu.i(&quot;Home&quot;) / &quot;index&quot;)
</pre>
</div>

</div>
<div class="Standard">
This is a SiteMap with a single menu item. The Menu has the name “Home” and will be displayed as the localized (see <a href="#sec:Localization" class="Reference">8.1 on page 1↓</a>) string “Home”. The Menu.i method generates a <tt>Menu</tt> with a <tt>Loc[Unit]</tt>.
</div>
<h3 class="Subsection">
<a name="toc-Subsection-3.2.3" class="toc">3.2.3</a> <tt>Menu</tt> and <tt>Loc[_]</tt>
</h3>
<div class="Standard">
You may be wondering why a <tt>Menu</tt> and a <tt>Loc[_]</tt> (short for location, pronouned “Loke”) are separate and why the Loc takes a type parameter.
</div>
<div class="Standard">
A <tt>Menu</tt> contains a location and many submenus. The original thought was that you could have a single <tt>Loc[_]</tt> that might be placed in different places in the menu hierarchy. So, historically, they are separated, but there’s a one to one relation between them.
</div>
<div class="Standard">
The <tt>Loc[_]</tt> takes a type parameter which defines a current value type for the <tt>Loc</tt>. For example, if the <tt>Loc</tt> refers to a page that will display a wiki page, then the type parameter of the <tt>Loc</tt> would be <tt>WikiPage</tt>: <tt>Loc[WikiPage]</tt>.
</div>
<div class="Standard">
Each <tt>Loc</tt> can have many parameters (know as <tt>LocParam</tt>, “loke param”) that define behavior for the <tt>Loc[_]</tt>. These parameters include access control testing, template definition, title, group, etc.
</div>
<h3 class="Subsection">
<a name="toc-Subsection-3.2.4" class="toc">3.2.4</a> Access Control
</h3>
<div class="Standard">
You can control access to the URL/page represented by the <tt>Loc</tt> with the <tt>If()</tt> LocParam:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: scala">  /**
   * Calculate if the page should be displayed.
   * In this case, it will be visible every other minute
   */
  def displaySometimes_? : Boolean = 
    (millis / 1000L / 60L) % 2 == 0
​
      Menu.i(&quot;Sometimes&quot;) / &quot;sometimes&quot; &gt;&gt; If(displaySometimes_? _,
                                            S ? &quot;Can’t view now&quot;)
</pre>
</div>

</div>
<div class="Standard">
We define a method that returns <tt>true</tt> if access is allowed. Adding the <tt>If()</tt> <tt>LocParam</tt> will restrict access to the page unless the function returns true. Menu items will not be visible for pages that do not pass the access control rules and even if the user types the URL into the browser, the page will not be displayed (by default, the user will be redirected by to the home page and an error will be displayed.)
</div>
<h3 class="Subsection">
<a name="toc-Subsection-3.2.5" class="toc">3.2.5</a> <tt>Hidden</tt> and <tt>Group</tt>
</h3>
<div class="Standard">
Menu items can be hidden from the default menu hierarchy even if the page is accessible. The Hidden LocParam says “hide from default menu.”
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: scala"> Menu.i(&quot;About&quot;) / &quot;about&quot; &gt;&gt; Hidden &gt;&gt; LocGroup(&quot;bottom&quot;)
</pre>
</div>

</div>
<div class="Standard">
Menu items can also be grouped together in a named group and then displayed:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: xml"> &lt;span class=&quot;lift:Menu.group?group=bottom&quot;&gt;&lt;/span&gt;
</pre>
</div>

</div>
<div class="Standard">
Which results in:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: xml"> &lt;a href=&quot;/about&quot;&gt;About&lt;/a&gt; &lt;a href=&quot;/feedback&quot;&gt;Feedback&lt;/a&gt; &lt;a href=&quot;/sitemap&quot;&gt;Sitemap&lt;/a&gt; 
</pre>
</div>

</div>
<h3 class="Subsection">
<a name="toc-Subsection-3.2.6" class="toc">3.2.6</a> Submenus
</h3>
<div class="Standard">
You can nest menus:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: scala">      // A menu with submenus
      Menu.i(&quot;Info&quot;) / &quot;info&quot; submenus(
        Menu.i(&quot;About&quot;) / &quot;about&quot; &gt;&gt; Hidden &gt;&gt; LocGroup(&quot;bottom&quot;),
        Menu.i(&quot;Contact&quot;) / &quot;contact&quot;,
        Menu.i(&quot;Feedback&quot;) / &quot;feedback&quot; &gt;&gt; LocGroup(&quot;bottom&quot;))
</pre>
</div>

</div>
<div class="Standard">
The About, Contact and Feedback pages are nested under the Info page.
</div>
<h3 class="Subsection">
<a name="toc-Subsection-3.2.7" class="toc">3.2.7</a> Parameters
</h3>
<div class="Standard">
You can parse the incoming URL and extract parameters from it into type-safe variables:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: scala">// capture the page parameter information
case class ParamInfo(theParam: String)
​
  // Create a menu for /param/somedata
  val menu = Menu.param[ParamInfo](&quot;Param&quot;, &quot;Param&quot;, 
                                   s =&gt; Full(ParamInfo(s)), 
                                   pi =&gt; pi.theParam) / &quot;param&quot;
</pre>
</div>

</div>
<div class="Standard">
The above code creates a menu called “Param”. The menu is for the url <tt>/param/xxx</tt> where <tt>xxx</tt> can match anything.
</div>
<div class="Standard">
When the URL <tt>/param/dogfood</tt> or <tt>/param/fruitbat</tt> is presented, it matches the <tt>Loc</tt> and the function (<tt>s =&gt; Full(ParamInfo(s))</tt>) is invoked. If it returns a <tt>Full</tt> <tt>Box</tt>, the value is placed in the <tt>Loc</tt>’s <tt>currentValue</tt>.
</div>
<div class="Standard">
It’s possible to hand-write Loc implementation that will match many URL parameters.
</div>
<div class="Standard">
For information on accessing the captured parameters (in this case the <tt>ParamInfo</tt>), see <a href="#sub:Param-Example" class="Reference">3.4.5 on page 1↓</a>.
</div>
<h3 class="Subsection">
<a name="toc-Subsection-3.2.8" class="toc">3.2.8</a> Wildcards
</h3>
<div class="Standard">
You can create menus that match all the contents of a given path. In this case, all the html files in <tt>/static/</tt> will be served. That includes <tt>/static/index</tt>, <tt>/static/fruitbat</tt>, and <tt>/static/moose/frog/wombat/meow</tt>.
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: scala">      // more complex because this menu allows anything in the
      // /static path to be visible
      Menu.i(&quot;Static&quot;) / &quot;static&quot; / **
</pre>
</div>

</div>
<div class="Standard">
Note that Lift will not serve any files or directories that start with <tt>.</tt> (period) or <tt>_</tt> (underscore) or end with <tt>-hidden</tt>.
</div>
<h3 class="Subsection">
<a name="toc-Subsection-3.2.9" class="toc">3.2.9</a> Summary
</h3>
<div class="Standard">
We’ve demonstrated how to create a <tt>SiteMap</tt> with many different kinds of menu items. Next, let’s look at the views.
</div>
<h2 class="Section">
<a name="toc-Section-3.3" class="toc">3.3</a> View First
</h2>
<div class="Standard">
Once the access control is granted by SiteMap, Lift loads the view related to the URL. There are many mechanisms that Lift uses to resolve a path to a view, but the simplest is a one to one mapping between the URL path and the files in <tt>/src/main/webapp</tt>. If the URL is <tt>/index</tt>, then Lift will look for the localized (see <a href="#sec:Localization" class="Reference">8.1 on page 1↓</a>) version of <tt>/src/main/webapp/index.html</tt>. Once Lift loads the template, Lift processes it to transform it into the dynamic content you want to return in response to the URL input.
</div>
<h3 class="Subsection">
<a name="toc-Subsection-3.3.1" class="toc">3.3.1</a> Page source
</h3>
<div class="Standard">
Let’s look at the page source:
</div>
<div class="listing">
<div class="caption">
index.html
</div>
<pre class="listing brush: xml">&lt;!DOCTYPE html&gt;
&lt;html&gt;
  &lt;head&gt;
    &lt;meta content=&quot;text/html; charset=UTF-8&quot; http-equiv=&quot;content-type&quot; /&gt;
    &lt;title&gt;Home&lt;/title&gt;
  &lt;/head&gt;
  &lt;body class=&quot;lift:content_id=main&quot;&gt;
    &lt;div id=&quot;main&quot; class=&quot;lift:surround?with=default&amp;at=content&quot;&gt;
      &lt;div&gt;Hello World.  Welcome to your Lift application.&lt;/div&gt;
      &lt;div&gt;Check out a page with &lt;a href=&quot;/param/foo&quot;&gt;query parameters&lt;/a&gt;.&lt;/div&gt;
​
      &lt;span class=&quot;lift:embed?what=_embedme&quot;&gt;
        replaced with embedded content
      &lt;/span&gt;
​
      &lt;div&gt;
	&lt;ul&gt;
	  &lt;li&gt;Recursive: &lt;a href=&quot;/recurse/one&quot;&gt;First snippet&lt;/a&gt;&lt;/li&gt;
	  &lt;li&gt;Recursive: &lt;a href=&quot;/recurse/two&quot;&gt;Second snippet&lt;/a&gt;&lt;/li&gt;
	  &lt;li&gt;Recursive: &lt;a href=&quot;/recurse/both&quot;&gt;Both snippets&lt;/a&gt;&lt;/li&gt;
	&lt;/ul&gt;
      &lt;/div&gt;
    &lt;/div&gt;
  &lt;/body&gt;
&lt;/html&gt;
​
</pre>
</div>
<div class="Standard">
We can open the page in our browser:
</div>
<div class="Standard">
<img style="max-width: 411px; max-height: 75px;" alt="figure raw.png" src="raw.png" class="embedded"/>

</div>
<h3 class="Subsection">
<a name="toc-Subsection-3.3.2" class="toc">3.3.2</a> Dynamic content
</h3>
<div class="Standard">
The template is a legal HTML page. But there are marker in the page to tell Lift how to interpret the HTML.
</div>
<div class="Standard">
If the <tt>&lt;body&gt;</tt> tag contains a <tt>class</tt> attribute <tt>lift:content_id=xxxx</tt>, then Lift will find the element with the matching <tt>id</tt> and use that as the starting point for rendering the page. This allows your designers to edit and maintain the pages in the same hierarchy that you use for your application.
</div>
<h3 class="Subsection">
<a name="toc-Subsection-3.3.3" class="toc">3.3.3</a> Surround and page chrome
</h3>
<div class="Standard">
The template processing starts with:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: xml"> &lt;div id=&quot;main&quot; class=&quot;lift:surround?with=default&amp;at=content&quot;&gt;
</pre>
</div>

</div>
<div class="Standard">
The <tt>class</tt> attribute <tt>lift:surround?with=default;at=content</tt> instructs Lift to surround the current Element with the template named default.html (typically located in the <tt>/templates-hidden/</tt> directory), and place the current page’s content at the element with the “content” <tt>id</tt>.
</div>
<div class="Standard">
This pattern allows us to wrap a common chrome around every page on our site. You can also specify different template to use for surrounding. Further, the template itself can choose different templates to use for surrounding.
</div>
<h3 class="Subsection">
<a name="toc-Subsection-3.3.4" class="toc">3.3.4</a> Embed
</h3>
<div class="Standard">
In addition to surrounding the page with chrome, you can also embed another file. For example, you could have a shopping cart component that is embedded in certain pages. We embed with:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: xml">&lt;span class=&quot;lift:embed?what=_embedme&quot;&gt;
  replaced with embedded content
&lt;/span&gt;
</pre>
</div>

</div>
<div class="Standard">
Once again, the command is signalled with a <tt>class</tt> attribute that starts with <tt>lift:</tt>. In this case, we embed a template from the file <tt>_embedme.html</tt>.
</div>
<h3 class="Subsection">
<a name="toc-Subsection-3.3.5" class="toc">3.3.5</a> Results
</h3>
<div class="Standard">
The resulting dynamically generated page looks like:
</div>
<div class="Standard">
<img style="width: 100%; max-width: 1028px; height: auto; max-height: 368px;" alt="figure browser.png" src="browser.png" class="embedded"/>

</div>
<h2 class="Section">
<a name="toc-Section-3.4" class="toc">3.4</a> Snippets and Dynamic content
</h2>
<div class="Standard">
Lift templates contain no executable code. They are pure, raw, valid HTML.
</div>
<div class="Standard">
Lift uses snippets to transform sections of the HTML page from static to dynamic. The key word is transform.
</div>
<div class="Standard">
Lift’s snippets are Scala functions: <tt>NodeSeq =&gt; NodeSeq</tt>. A <tt>NodeSeq</tt> is a collection of XML nodes. An snippet can only transform input <tt>NodeSeq</tt> to output <tt>NodeSeq</tt>. Well, not exactly... a snippet may also have side effects including setting cookies, doing database transactions, etc. But the core transformation concept is important. First, it isolates snippet functionality to discrete parts of the page. This means that each snippet, each <tt>NodeSeq =&gt; NodeSeq</tt>, is a component. Second, it means that pages are recursively built, but remain as valid HTML at all times. This means that the developer has to work hard to introduce a cross site scripting vulnerability. Third, the designers don’t have to worry about learning to program anything in order to design HTML pages because the program execution is abstracted away from the HTML rather than embedded in the HTML.
</div>
<h3 class="Subsection">
<a name="toc-Subsection-3.4.1" class="toc">3.4.1</a> Snippets in markup
</h3>
<div class="Standard">
In order to indicate that content is dynamic, the markup contains a snippet invocation. That typically takes the form <tt>class=&quot;someclass someothercss lift:mysnippet&quot;</tt>. If a class attribute contains <tt>lift:xxx</tt>, the <tt>xxx</tt> will be resolved to a snippet. The snippet may take attributes. Attributes are encoded like URL parameters... offset by a <tt>?</tt> (question mark), then <tt>name=value</tt>, separted by <tt>?</tt> (question mark), <tt>;</tt> (semicolon) or <tt>&amp;</tt> (ampersand). <tt>name</tt> and <tt>value</tt> are URL encoded.
</div>
<div class="Standard">
You may also invoke snippets with XML tags:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: xml">&lt;lift:my_snippet cat=&quot;foo&quot;&gt;
  &lt;div&gt;xxxx&lt;/div&gt;
&lt;/lift:my_snippet&gt;
</pre>
</div>

</div>
<div class="Standard">
Note that the Html5 parser will force all tags to lower case so <tt>&lt;lift:MySnipet&gt;</tt> will become <tt>&lt;lift:mysnippet&gt;</tt>.
</div>
<div class="Standard">
Lift 2.3 will also allow snippet invocation in the form <tt>&lt;div l=&quot;mysnippet?param=value&quot;&gt;xxx&lt;/div&gt;</tt>.
</div>
<div class="Standard">
The latter two mechanisms for invoking snippets will not result in valid Html5 templates.
</div>
<h3 class="Subsection">
<a name="toc-Subsection-3.4.2" class="toc">3.4.2</a> Snippet resolution
</h3>
<div class="Standard">
Lift has a very complex set of rules to resolve from snippet name to NodeSeq =&gt; NodeSeq (see <a href="#sec:Snippet-Resolution" class="Reference">23.1 on page 1↓</a>). For now, the simplest mechanism is to have a <tt>class</tt> or <tt>object</tt> in the <tt>snippet</tt> package that matches the snippet name.
</div>
<div class="Standard">
So <tt>lift:HelloWorld</tt> will look for the <tt>code.snippet.HelloWorld</tt> class and invoke the <tt>render</tt> method.
</div>
<div class="Standard">
<tt>lift:CatFood.fruitbat</tt> will look for the <tt>code.snippet.CatFood</tt> class and invoke the <tt>fruitbat</tt> method.
</div>
<h3 class="Subsection">
<a name="toc-Subsection-3.4.3" class="toc">3.4.3</a> Dynamic Example
</h3>
<div class="Standard">
Let’s look at the <tt>dynamic.html</tt> page:
</div>
<div class="listing">
<div class="caption">
dynamic.html
</div>
<pre class="listing brush: xml">&lt;!DOCTYPE html&gt;
&lt;html&gt;
  &lt;head&gt;
    &lt;meta content=&quot;text/html; charset=UTF-8&quot; http-equiv=&quot;content-type&quot; /&gt;
    &lt;title&gt;Dynamic&lt;/title&gt;
  &lt;/head&gt;
  &lt;body class=&quot;lift:content_id=main&quot;&gt;
    &lt;div id=&quot;main&quot; class=&quot;lift:surround?with=default;at=content&quot;&gt;
      This page has dynamic content.
      The current time is &lt;span class=&quot;lift:HelloWorld&quot;&gt;now&lt;/span&gt;.
    &lt;/div&gt;
  &lt;/body&gt;
&lt;/html&gt;
​
</pre>
</div>
<div class="Standard">
This template invokes the <tt>HelloWorld</tt> snippet defined in <tt>HelloWorld.scala</tt>:
</div>
<div class="listing">
<div class="caption">
HelloWorld.scala
</div>
<pre class="listing brush: scala">package code
package snippet
​
import lib._
​
import net.liftweb._
import util.Helpers._
import common._
import java.util.Date
​
class HelloWorld {
  lazy val date: Box[Date] = DependencyFactory.inject[Date] // inject the date
​
  def render = &quot;* *&quot; #&gt; date.map(_.toString)
}
​
</pre>
</div>
<div class="Standard">
And the dynamic content becomes:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: xml">&lt;span&gt;Thu Dec 30 16:31:13 PST 2010&lt;/span&gt;
</pre>
</div>

</div>
<div class="Standard">
The <tt>HelloWorld</tt> snippet code is simple.
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: scala">lazy val date: Box[Date] = DependencyFactory.inject[Date]
</pre>
</div>

</div>
<div class="Standard">
Uses dependency injection (see <a href="#sec:Dependency-Injection" class="Reference">8.2 on page 1↓</a>) to get a <tt>Date</tt> instance.
</div>
<div class="Standard">
Then:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: scala">def render = &quot;* *&quot; #&gt; date.map(_.toString)
</pre>
</div>

</div>
<div class="Standard">
Creates a CSS Selector Transform (see <a href="#sec:CSS-Selector-Transforms" class="Reference">7.10 on page 1↓</a>) that inserts the <tt>String</tt> value of the injected <tt>Date</tt> into the markup, in this case the <tt>&lt;span&gt;</tt> that invoked the snippet.
</div>
<h3 class="Subsection">
<a name="toc-Subsection-3.4.4" class="toc">3.4.4</a> Embedded Example
</h3>
<div class="Standard">
We’ve seen how we can embed a template using: <tt>&lt;div class=&quot;lift:embed?what=_embedme&quot;&gt;xxx&lt;/div&gt;</tt>.
</div>
<div class="Standard">
Let’s look at the <tt>_embedme.html</tt> template:
</div>
<div class="listing">
<pre class="listing brush: xml">&lt;!DOCTYPE html&gt;
&lt;html&gt;
  &lt;head&gt;
    &lt;meta content=&quot;text/html; charset=UTF-8&quot; http-equiv=&quot;content-type&quot; /&gt;
    &lt;title&gt;I'm embeded&lt;/title&gt;
  &lt;/head&gt;
  &lt;body class=&quot;lift:content_id=main&quot;&gt;
    &lt;div id=&quot;main&quot;&gt;
      Howdy.  I'm a bit of embedded content.  I was 
      embedded from &lt;span class=&quot;lift:Embedded.from&quot;&gt;???&lt;/span&gt;.
    &lt;/div&gt;
  &lt;/body&gt;
&lt;/html&gt;
​
</pre>
</div>
<div class="Standard">
And the invoked <tt>Embedded.scala</tt> program:
</div>
<div class="listing">
<div class="caption">
Embedded.scala
</div>
<pre class="listing brush: scala">package code
package snippet
​
import lib._
​
import net.liftweb._
import http._
import util.Helpers._
import common._
import java.util.Date
​
/**
 * A snippet that lists the name of the current page
 */
object Embedded {
  def from = &quot;*&quot; #&gt; S.location.map(_.name)
}
​
</pre>
</div>
<div class="Standard">
The template invokes the <tt>from</tt> method on the <tt>Embedded</tt> snippet. In this case, the snippet is an <tt>object</tt> singleton because it does not take any constructor parameters and has no instance variabled.
</div>
<div class="Standard">
The <tt>from</tt> method:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: scala">  def from = &quot;*&quot; #&gt; S.location.map(_.name)
</pre>
</div>

</div>
<div class="Standard">
Creates a CSS Selector Transform that replaces the contents with the <tt>name</tt> of the current <tt>location</tt>.
</div>
<h3 class="Subsection">
<a name="toc-Subsection-3.4.5" class="toc">3.4.5</a> <a name="sub:Param-Example" class="Label"> </a>Param Example
</h3>
<div class="Standard">
Above, we saw how to create a <tt>Loc[ParamInfo]</tt> to capture URL parameters. Let’s look at the <tt>/param/xxx</tt> page and see how we can access the parameters:
</div>
<div class="listing">
<div class="caption">
param.html
</div>
<pre class="listing brush: xml">&lt;!DOCTYPE html&gt;
&lt;html&gt;
  &lt;head&gt;
    &lt;meta content=&quot;text/html; charset=UTF-8&quot; http-equiv=&quot;content-type&quot; /&gt;
    &lt;title&gt;Param&lt;/title&gt;
  &lt;/head&gt;
  &lt;body class=&quot;lift:content_id=main&quot;&gt;
    &lt;div id=&quot;main&quot; class=&quot;lift:surround?with=default;at=content&quot;&gt;
      &lt;div&gt;
        Thanks for visiting this page.  The parameter is
        &lt;span class=&quot;lift:ShowParam&quot;&gt;???&lt;/span&gt;.
      &lt;/div&gt;
      
      &lt;div&gt;
        Another way to get the param: &lt;span class=&quot;lift:Param&quot;&gt;???&lt;/span&gt;.
      &lt;/div&gt;
      
    &lt;/div&gt;
  &lt;/body&gt;
&lt;/html&gt;
​
</pre>
</div>
<div class="Standard">
And let’s look at two different snippets that can access the <tt>ParamInfo</tt> for the page:
</div>
<div class="listing">
<div class="caption">
Param.scala
</div>
<pre class="listing brush: scala">package code
package snippet
​
import lib._
​
import net.liftweb._
import util.Helpers._
import common._
import http._
import sitemap._
import java.util.Date
​
// capture the page parameter information
case class ParamInfo(theParam: String)
​
// a snippet that takes the page parameter information
class ShowParam(pi: ParamInfo)  {
  def render = &quot;*&quot; #&gt; pi.theParam
}
​
object Param {
  // Create a menu for /param/somedata
  val menu = Menu.param[ParamInfo](&quot;Param&quot;, &quot;Param&quot;, 
                                   s =&gt; Full(ParamInfo(s)), 
                                   pi =&gt; pi.theParam) / &quot;param&quot;
  lazy val loc = menu.toLoc
​
  def render = &quot;*&quot; #&gt; loc.currentValue.map(_.theParam)
}
</pre>
</div>
<div class="Standard">
Each snippet has a <tt>render</tt> method. However, the <tt>ShowParam</tt> class takes a constructor parameter which contains the <tt>ParamInfo</tt> from the current <tt>Loc[_]</tt>. If the current <tt>Loc</tt> does not have the type parameter <tt>ParamInfo</tt>, no instance of <tt>ShowParam</tt> would be created and the snippet could not be resolved. But we do have a Loc[ParamInfo], so Lift constructs a <tt>ShowParam</tt> with the <tt>Loc</tt>’s <tt>currentValue</tt> and then the <tt>render</tt> method is invoked and it returns a CSS Selector Transform which is a <tt>NodeSeq =&gt; NodeSeq</tt>.
</div>
<div class="Standard">
The <tt>object Param</tt>’s <tt>render</tt> method accesses the <tt>Loc[ParamInfo]</tt> directly. The <tt>render</tt> method gets the <tt>Loc</tt>’s <tt>currentValue</tt> and uses that to calculate the return value, the CSS Selector Transform.
</div>
<h3 class="Subsection">
<a name="toc-Subsection-3.4.6" class="toc">3.4.6</a> Recursive
</h3>
<div class="Standard">
Lift’s snippets are evaluated lazily. This means that the body of the snippet is not executed until the outer snippet is executed which allows you to return markup from a snippet that itself contains a snippet or alternatively, choose part of the snippet body that itself contains a snippet invocation. For example, in this markup:
</div>
<div class="listing">
<div class="caption">
recurse.html
</div>
<pre class="listing brush: xml">&lt;div id=&quot;main&quot; class=&quot;lift:surround?with=default&amp;at=content&quot;&gt;
  &lt;div&gt;
    This demonstrates Lift's recursive snippets
  &lt;/div&gt;
​
  &lt;div class=&quot;lift:Recurse&quot;&gt;
    &lt;div id=&quot;first&quot; class=&quot;lift:FirstTemplate&quot;&gt;
      The first template.
    &lt;/div&gt;
​
    &lt;div id=&quot;second&quot; class=&quot;lift:SecondTemplate&quot;&gt;
      The second template.
    &lt;/div&gt;
  &lt;/div&gt;
  
  &lt;div&gt;
    &lt;ul&gt;
      &lt;li&gt;Recursive: &lt;a href=&quot;/recurse/one&quot;&gt;First snippet&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;Recursive: &lt;a href=&quot;/recurse/two&quot;&gt;Second snippet&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;Recursive: &lt;a href=&quot;/recurse/both&quot;&gt;Both snippets&lt;/a&gt;&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/div&gt;
&lt;/div&gt;
​
​
</pre>
</div>
<div class="Standard">
The <tt>Recurse</tt> snippet chooses one of both of the <tt>&lt;div&gt;</tt>’s, each of which invokes a snippet themselves. Here’s the Scala:
</div>
<div class="listing">
<div class="caption">
Recurse.scala
</div>
<pre class="listing brush: scala">package code
package snippet
​
import lib._
​
import net.liftweb._
import util._
import Helpers._
import http._
import scala.xml.NodeSeq
​
/**
 * The choices
 */
sealed trait Which
final case class First() extends Which
final case class Second() extends Which
final case class Both() extends Which
​
/**
 * Choose one or both of the templates
 */
class Recurse(which: Which) {
  // choose the template
  def render = which match {
    case First() =&gt; &quot;#first ^^&quot; #&gt; &quot;*&quot; // choose only the first template
    case Second() =&gt; &quot;#second ^^&quot; #&gt; &quot;*&quot; // choose only the second template
    case Both() =&gt; ClearClearable // it's a passthru
  }
}
​
/**
 * The first template snippet
 */
object FirstTemplate {
  // it's a passthru, but has the notice side effect
  def render(in: NodeSeq) = {
    S.notice(&quot;First Template Snippet executed&quot;)
    in
  }
}
​
/**
 * The second template snippet
 */
object SecondTemplate {
  // it's a passthru, but has the notice side effect
  def render(in: NodeSeq) = {
    S.notice(&quot;Second Template Snippet executed&quot;)
    in
  }
}
</pre>
</div>
<div class="Standard">
Depending on the value of <tt>which</tt>, one or both parts of the markup will be chosen. And each part of the markup itself invokes a snippet which displays a notice and passes the markup through.
</div>
<div class="Standard">
Using this technique, you can have a snippet that chooses one or many different snippets or returns a <tt>lift:embed</tt> snippet, thus allowing for very dynamic markup generation.
</div>
<h3 class="Subsection">
<a name="toc-Subsection-3.4.7" class="toc">3.4.7</a> Summary
</h3>
<div class="Standard">
We’ve seen some simple examples of Lift’s snippet mechanism used to generate dynamic content. You can read more on snippets (see <a href="#sec:Snippets" class="Reference">7.1 on page 1↓</a>).
</div>
<h2 class="Section">
<a name="toc-Section-3.5" class="toc">3.5</a> Wrap up
</h2>
<div class="Standard">
In this chapter, we’ve seen how to define application behavior on <tt>Boot.scala</tt>. We’ve explored Lift’s <tt>SiteMap</tt> which is used to generate navigation and enforce access control. We’ve seen how Lift’s templating system works (well, there are actually a bunch of different ways to template in Lift, but we’ve explored to most common mechanism.) We’ve seen how snippets work.
</div>
<div class="Standard">
In the next chapter, we’ll take a dive into Lift’s form handling.
</div>
<div class="Standard">

</div>
<h1 class="Chapter">
<a name="toc-Chapter-4" class="toc">4</a> <a name="cha:Forms" class="Label"> </a>Forms
</h1>
<div class="Standard">
In this chapter, we’ll see how Lift processes templates. We’ll start with form processing the old fashioned way (where the designer names the inputs and the application maps those names to variables) through multi-page input forms and Ajax form support.
</div>
<h2 class="Section">
<a name="toc-Section-4.1" class="toc">4.1</a> Old Fashioned Dumb Forms
</h2>
<div class="Standard">
Let’s take a look at the HTML for a form:
</div>
<div class="listing">
<div class="caption">
dumb.html
</div>
<pre class="listing brush: xml">&lt;div id=&quot;main&quot; class=&quot;lift:surround?with=default&amp;at=content&quot;&gt;
  &lt;div&gt;
    This is the simplest type of form processing... plain old
    mechanism of naming form elements and processing the form elements
    in a post-back.
  &lt;/div&gt;
  
  &lt;div&gt;
    &lt;form action=&quot;/dumb&quot; method=&quot;post&quot; class=&quot;lift:DumbForm&quot;&gt;
      Name: &lt;input name=&quot;name&quot;&gt;&lt;br&gt;
      Age: &lt;input name=&quot;age&quot;&gt;&lt;br&gt;
      &lt;input type=&quot;submit&quot; value=&quot;Submit&quot;&gt;
    &lt;/form&gt;
  &lt;/div&gt;
&lt;/div&gt;
​
​
</pre>
</div>
<div class="Standard">
Okay... looks pretty normal... we define a form. The only thing we do is associate the behavior with the form with the <tt>class=&quot;lift:DumbForm&quot;</tt> attribute on the <tt>&lt;form&gt;</tt> tag. The page is a post-back which means that the form is posted to the same URL that served the original content.
</div>
<div class="Standard">
Let’s see the code to process the form:
</div>
<div class="listing">
<div class="caption">
DumbForm.scala
</div>
<pre class="listing brush: scala">package code
package snippet
​
import net.liftweb._
import http._
import scala.xml.NodeSeq
​
/**
 * A snippet that grabs the query parameters
 * from the form POST and processes them
 */
object DumbForm {
  def render(in: NodeSeq): NodeSeq = {
​
    // use a Scala for-comprehension to evaluate each parameter
    for {
      r &lt;- S.request if r.post_? // make sure it's a post
      name &lt;- S.param(&quot;name&quot;) // get the name field
      age &lt;- S.param(&quot;age&quot;) // get the age field
    } {
      // if everything goes as expected,
      // display a notice and send the user
      // back to the home page
      S.notice(&quot;Name: &quot;+name)
      S.notice(&quot;Age: &quot;+age)
      S.redirectTo(&quot;/&quot;)
    }
​
    // pass through the HTML if we don't get a post and
    // all the parameters
    in
  }
}
</pre>
</div>
<div class="Standard">
It’s pretty simple. If the request is a post and the query parameters exist, then display notices with the name and age and redirect back the application’s home page.
</div>
<div class="Standard">
There are plenty of reasons not to do things this way.
</div>
<div class="Standard">
First, if there’s a naming mis-match between the HTML and the Scala code, you might miss a form field... and keeping the naming aligned is not always easy.
</div>
<div class="Standard">
Second, forms with predictable names lead to replay attacks. If an attacker can capture the form submits you’ve made and substitute new values for import fields, they can more easily hack your application.
</div>
<div class="Standard">
Third, keeping state around becomes very difficult with manual forms. You have to resort to hidden fields that contain primary keys or other information that can be tampered with.
</div>
<div class="Standard">
Lift provides you with much more powereful and secure mechanisms for dealing with HTML forms.
</div>
<h2 class="Section">
<a name="toc-Section-4.2" class="toc">4.2</a> OnSubmit
</h2>
<div class="Standard">
Some of Lift’s design reflects VisualBasic... associating user behavior with a user interface element. It’s a simple, yet very powerful concept. Each form element is associated with a function on the server<span class="FootOuter"><span class="SupFootMarker"> [C] </span><span class="HoverFoot"><span class="SupFootMarker"> [C] </span>Before you get all upset about statefulness and such, please read about Lift and State (see <a href="#cha:Scaling" class="Reference">20 on page 1↓</a>).</span></span>. Further, because functions in Scala close over scope (capture the variables currently in scope), it’s both easy and secure to keep state around without exposing that state to the web client.
</div>
<div class="Standard">
So, let’s see how it works. First, the HTML:
</div>
<div class="listing">
<div class="caption">
onsubmit.html
</div>
<pre class="listing brush: xml">&lt;div id=&quot;main&quot; class=&quot;lift:surround?with=default&amp;at=content&quot;&gt;
  &lt;div&gt;
    Using Lift's SHtml.onSubmit, we've got better control
    over the form processing.
  &lt;/div&gt;
  
  &lt;div&gt;
    &lt;form class=&quot;lift:OnSubmit?form=post&quot;&gt;
      Name: &lt;input name=&quot;name&quot;&gt;&lt;br&gt;
      Age: &lt;input name=&quot;age&quot; value=&quot;0&quot;&gt;&lt;br&gt;
      &lt;input type=&quot;submit&quot; value=&quot;Submit&quot;&gt;
    &lt;/form&gt;
  &lt;/div&gt;
&lt;/div&gt;
​
​
</pre>
</div>
<div class="Standard">
The only different thing in this HTML is <tt>&lt;form class=&quot;lift:OnSubmit?form=post&quot;&gt;</tt>. The snippet, behavior, of the form is to invoke <tt>OnSubmit.render</tt>. The <tt>form=post</tt> attribute makes the form into a post-back. It sets the <tt>method</tt> and <tt>action</tt> attributes on the <tt>&lt;form&gt;</tt> tag: <tt>&lt;form method=&quot;post&quot; action=&quot;/onsubmit&quot;&gt;</tt>.
</div>
<div class="Standard">
Let’s look at the snippet:
</div>
<div class="listing">
<div class="caption">
OnSubmit.scala
</div>
<pre class="listing brush: scala">package code
package snippet
​
import net.liftweb._
import http._
import util.Helpers._
import scala.xml.NodeSeq
​
/**
 * A snippet that binds behavior, functions,
 * to HTML elements
 */
object OnSubmit {
  def render = {
    // define some variables to put our values into
    var name = &quot;&quot;
    var age = 0
​
    // process the form
    def process() {
      // if the age is &lt; 13, display an error
      if (age &lt; 13) S.error(&quot;Too young!&quot;)
      else {
        // otherwise give the user feedback and
        // redirect to the home page
        S.notice(&quot;Name: &quot;+name)
        S.notice(&quot;Age: &quot;+age)
        S.redirectTo(&quot;/&quot;)
      }
    }
​
    // associate each of the form elements
    // with a function... behavior to perform when the
    // for element is submitted
    &quot;name=name&quot; #&gt; SHtml.onSubmit(name = _) &amp; // set the name
    // set the age variable if we can convert to an Int
    &quot;name=age&quot; #&gt; SHtml.onSubmit(s =&gt; asInt(s).foreach(age = _)) &amp;
    // when the form is submitted, process the variable
    &quot;type=submit&quot; #&gt; SHtml.onSubmitUnit(process)
  }
}
</pre>
</div>
<div class="Standard">
Like <tt>DumbForm.scala</tt>, the snippet is implemented as a singleton. The render method declares two variables: <tt>name</tt> and <tt>age</tt>. Let’s skip the <tt>process()</tt> method and look at the was we’re associating behavior with the form elements.
</div>
<div class="Standard">
<tt>&quot;name=name&quot; #&gt; SHtml.onSubmit(name = _)</tt> takes the incoming HTML elements with the <tt>name</tt> attribute equal to “name” and, via the <tt>SHtml.onSubmit</tt> method, associating a function with the form element. The function takes a <tt>String</tt> parameter and sets the value of the <tt>name</tt> variable to the <tt>String</tt>. The resulting HTML is <tt>&lt;input name=&quot;F10714412223674KM&quot;&gt;</tt>. The new <tt>name</tt> attribute is a GUID (globally unique identifier) that associates the function (set the name to the input) with the form element. When the form is submitted, via normal HTTP post or via Ajax, the function will be executed with the value of the form element. On form submit, perform this function.
</div>
<div class="Standard">
Let’s see about the age form field: <tt>&quot;name=age&quot; #&gt; SHtml.onSubmit(s =&gt; asInt(s).foreach(age = _))</tt>. The function that’s executed uses <tt>Helpers.asInt</tt> to try to parse the <tt>String</tt> to an <tt>Int</tt>. If the parsing is successful, the <tt>age</tt> variable is set to the parsed <tt>Int</tt>.
</div>
<div class="Standard">
Finally, we associate a function with the submit button: <tt>&quot;type=submit&quot; #&gt; SHtml.onSubmitUnit(process)</tt>. <tt>SHtml.onSubmitUnit</tt> method takes a function that takes no parameters (rather than a function that takes a single <tt>String</tt> as a parameter) and applies that function when the form is submitted.
</div>
<div class="Standard">
The <tt>process()</tt> method closes over the scope of the <tt>name</tt> and <tt>age</tt> variables and when that method is lifted to a function, it still closes over the variables... that means that when the function is applied, it refers to the same instances of the <tt>name</tt> and <tt>age</tt> variables as the other functions in this method. However, if we had 85 copies of the form open in 85 browsers, each would be closing over different instances of the <tt>name</tt> and <tt>age</tt> variables. In this way, Lift allows your application to contain complex state without exposing that complex state to the browser.
</div>
<div class="Standard">
The problem with this form example is that if you type an incorrect age, the whole form is reset. Let’s see how we can do better error handling.
</div>
<h2 class="Section">
<a name="toc-Section-4.3" class="toc">4.3</a> Stateful Snippets
</h2>
<div class="Standard">
In order for us to give the user a better experience, we need to capture the state of the name and age variables across the multiple form submissions. The mechanism that Lift has for doing this is the Stateful Snippet<span class="FootOuter"><span class="SupFootMarker"> [D] </span><span class="HoverFoot"><span class="SupFootMarker"> [D] </span>There are no stateless snippets. A Stateful Snippet doesn’t consume any more server-side resources than does a form composed via <tt>SHtml.onSubmit()</tt>. Oh, and state is not a barier to scalaing. See <a href="#cha:Scaling" class="Reference">↓</a>.</span></span>. A snippet that subclasses <tt>StatefulSnippet</tt> has an extra hidden parameter automatically inserted into the form which ensures that during processing of that form, the same instance of the StatefulSnippet will be used<span class="FootOuter"><span class="SupFootMarker"> [E] </span><span class="HoverFoot"><span class="SupFootMarker"> [E] </span>Earlier I talked about the security implications of hidden form parameters. The hidden parameter mechanism is not vulnerable to the same issues because the hidden parameter itself is just a GUID that causes a function to be invoked on the server. No state is exposed to the client, so there’s nothing for a hacker to capture or mutate that would allow for the exploitation of a vulnerability.</span></span>.
</div>
<div class="Standard">
Let’s look at the HTML template:
</div>
<div class="listing">
<div class="caption">
stateful.html
</div>
<pre class="listing brush: xml">&lt;div id=&quot;main&quot; class=&quot;lift:surround?with=default&amp;at=content&quot;&gt;
  &lt;div&gt;
    Using stateful snippets for a better
    user experience
  &lt;/div&gt;
      
  &lt;div&gt;
    &lt;div class=&quot;lift:Stateful?form=post&quot;&gt;
      Name: &lt;input name=&quot;name&quot;&gt;&lt;br&gt;
      Age: &lt;input name=&quot;age&quot; value=&quot;0&quot;&gt;&lt;br&gt;
      &lt;input type=&quot;submit&quot; value=&quot;Submit&quot;&gt;
    &lt;/div&gt;
  &lt;/div&gt;
&lt;/div&gt;
​
</pre>
</div>
<div class="Standard">
The template looks pretty much like the template in <tt>onsubmit.html</tt>. Let’s look at the snippet itself:
</div>
<div class="listing">
<div class="caption">
Stateful.scala
</div>
<pre class="listing brush: scala">package code
package snippet
​
import net.liftweb._
import http._
import common._
import util.Helpers._
import scala.xml.NodeSeq
​
/**
 * A stateful snippet. The state associated with this
 * snippet is in instance variables 
 */
class Stateful extends StatefulSnippet {
  // state unique to this instance of the stateful snippet
  private var name = &quot;&quot;
  private var age = &quot;0&quot;
​
  // capture from whence the user came so we
  // can send them back
  private val whence = S.referer openOr &quot;/&quot;
​
  // StatefulSnippet requires an explicit dispatch
  // to the method.
  def dispatch = {case &quot;render&quot; =&gt; render}
​
  // associate behavior with each HTML element
  def render = 
    &quot;name=name&quot; #&gt; SHtml.text(name, name = _, &quot;id&quot; -&gt; &quot;the_name&quot;) &amp;
    &quot;name=age&quot; #&gt; SHtml.text(age, age = _) &amp;
    &quot;type=submit&quot; #&gt; SHtml.onSubmitUnit(process)
​
  // process the form
  private def process() =
    asInt(age) match {
      case Full(a) if a &lt; 13 =&gt; S.error(&quot;Too young!&quot;)
      case Full(a) =&gt; {
        S.notice(&quot;Name: &quot;+name)
        S.notice(&quot;Age: &quot;+a)
        S.redirectTo(whence)
      }
      
      case _ =&gt; S.error(&quot;Age doesn't parse as a number&quot;)
    }
}
</pre>
</div>
<div class="Standard">
There’s a fair amount different here. First, the class definition: <tt>class Stateful extends StatefulSnippet</tt>. Because the snippet instance itself contains state, it can’t be an object singleton. It must be declared as a class so there are multiple instances.
</div>
<div class="Standard">
We capture state (<tt>name</tt>, <tt>age</tt> and <tt>from</tt> whence the user came), in instance variables.
</div>
<div class="Standard">
<tt>StatefulSnippet</tt>s require a <tt>dispatch</tt> method which does method dispatching explicitly rather than “by-convention.”
</div>
<div class="Standard">
The render method uses familiar CSS Selector Transforms to associate markup with behavior. However, rather than using <tt>SHtml.onSubmit</tt>, we’re using <tt>SHtml.text</tt> to explicitly generate an HTML <tt>&lt;input&gt;</tt> element with both the <tt>name</tt> and <tt>value</tt> attributes set. In the case of the first input, we’re also explicitly setting the <tt>id</tt> attribute. We’re not using it in the application, but it’s a way to demonstrate how to add extra attributes.
</div>
<div class="Standard">
Finally, the <tt>process()</tt> method attempts to covert the age <tt>String</tt> into an <tt>Int</tt>. If it’s an <tt>Int</tt>, but less than 13, we present an error. If the <tt>String</tt> cannot be parsed to an <tt>Int</tt>, we present an error, otherwise we do notify the user and go back to the page the user came from.
</div>
<div class="Standard">
Note in this example, we preserve the form values, so if you type something wrong in the <tt>name</tt> or <tt>age</tt> fields, what you typed is presented to you again.
</div>
<div class="Standard">
The big difference between the resulting HTML for <tt>StatefulSnippet</tt>s and other snippets is the insertion of <tt>&lt;input name=&quot;F1071441222401LO3&quot; type=&quot;hidden&quot; value=&quot;true&quot;&gt;</tt> in the form. This hidden field associates the snippet named “Stateful” with the instance of <tt>Stateful</tt> that was used to initially generate the form.
</div>
<div class="Standard">
Let’s look at an alternative mechanism for creating a nice user experience.
</div>
<h2 class="Section">
<a name="toc-Section-4.4" class="toc">4.4</a> <tt>RequestVar</tt>s
</h2>
<div class="Standard">
In this example, we’re going to preserve state during the request by placing state in <tt>RequestVar</tt>s (see <a href="#sec:SessionVars-and-RequestVars" class="Reference">7.8 on page 1↓</a>).
</div>
<div class="Standard">
Lift has type-safe containers for state called <tt>XXXVar</tt>s. There are <tt>SessionVar</tt>s that have session scope, <tt>WizardVar</tt>s that are scoped to a Wizard and <tt>RequestVar</tt>s that are scoped to the current request<span class="FootOuter"><span class="SupFootMarker"> [F] </span><span class="HoverFoot"><span class="SupFootMarker"> [F] </span>In this case, “request” means full HTML page load and all subsquent Ajax operations on that page. There’s also a <tt>TransientRequestVar</tt> that has the scope of the current HTTP request.</span></span>. <tt>Var</tt>s are defined as singletons: <tt>private object name extends RequestVar(&quot;&quot;)</tt>. They are typed (in this case, the type is <tt>String</tt>) and they have a default value.
</div>
<div class="Standard">
So, let’s look at the HTML which looks shockingly like the HTML in the last two examples:
</div>
<div class="listing">
<div class="caption">
requestvar.html
</div>
<pre class="listing brush: xml">&lt;div id=&quot;main&quot; class=&quot;lift:surround?with=default&amp;at=content&quot;&gt;
  &lt;div&gt;
    Using RequestVars to store state
  &lt;/div&gt;
      
  &lt;div&gt;
    &lt;form class=&quot;lift:ReqVar?form=post&quot;&gt;
      Name: &lt;input name=&quot;name&quot;&gt;&lt;br&gt;
      Age: &lt;input name=&quot;age&quot; id=&quot;the_age&quot; value=&quot;0&quot;&gt;&lt;br&gt;
      &lt;input type=&quot;submit&quot; value=&quot;Submit&quot;&gt;
    &lt;/form&gt;
  &lt;/div&gt;
&lt;/div&gt;
​
</pre>
</div>
<div class="Standard">
Now, let’s look at the snippet code:
</div>
<div class="listing">
<div class="caption">
ReqVar.scala
</div>
<pre class="listing brush: scala">package code
package snippet
​
import net.liftweb._
import http._
import common._
import util.Helpers._
import scala.xml.NodeSeq
​
/**
 * A RequestVar-based snippet
 */
object ReqVar {
  // define RequestVar holders for name, age, and whence
  private object name extends RequestVar(&quot;&quot;)
  private object age extends RequestVar(&quot;0&quot;)
  private object whence extends RequestVar(S.referer openOr &quot;/&quot;)
​
  def render = {
    // capture the whence... which forces evaluation of
    // the whence RequestVar unless it's already been set
    val w = whence.is
​
    // we don't need an explicit function because RequestVar
    // extends Settable{type=String}, so Lift knows how to
    // get/set the RequestVar for text element creation
    &quot;name=name&quot; #&gt; SHtml.textElem(name) &amp;
    // add a hidden field that sets whence so we
    // know where to go
    &quot;name=age&quot; #&gt; (SHtml.textElem(age) ++ 
                   SHtml.hidden(() =&gt; whence.set(w))) &amp;
    &quot;type=submit&quot; #&gt; SHtml.onSubmitUnit(process)
  }
​
  // process the same way as
  // in Stateful
  private def process() =
    asInt(age.is) match {
      case Full(a) if a &lt; 13 =&gt; S.error(&quot;Too young!&quot;)
      case Full(a) =&gt; {
        S.notice(&quot;Name: &quot;+name)
        S.notice(&quot;Age: &quot;+a)
        S.redirectTo(whence)
      }
      
      case _ =&gt; S.error(&quot;Age doesn't parse as a number&quot;)
    }
}
</pre>
</div>
<div class="Standard">
The snippet is a singleton because the state is kept in the <tt>RequestVar</tt>s.
</div>
<div class="Standard">
We use <tt>SHtml.textElem()</tt> to generate the <tt>&lt;input&gt;</tt> tag. We can pass the <tt>RequestVar</tt> into the method and the function that gets/sets the <tt>RequestVar</tt> is generated for us.
</div>
<div class="Standard">
The use of this mechanism for doing stateful forms versus the StatefulSnippet mechanism is one of personal choice. Neither one is better, they are just different.
</div>
<div class="Standard">
Next, let’s look at how to get more granular with error messages.
</div>
<h2 class="Section">
<a name="toc-Section-4.5" class="toc">4.5</a> Field Errors
</h2>
<div class="Standard">
In the prior examples, we displayed an error to the user. However, we didn’t tell the user what field resulted in the error. Let’s be a little more granular about error reporting.
</div>
<div class="Standard">
First, let’s look at the HTML:
</div>
<div class="listing">
<div class="caption">
fielderror.html
</div>
<pre class="listing brush: xml">&lt;div id=&quot;main&quot; class=&quot;lift:surround?with=default&amp;at=content&quot;&gt;
  &lt;div&gt;
    Let's get granular about error messages
  &lt;/div&gt;
  
  &lt;div&gt;
    &lt;div class=&quot;lift:FieldErrorExample?form=post&quot;&gt;
      Name: &lt;input name=&quot;name&quot;&gt;&lt;br&gt;
      Age: &lt;span class=&quot;lift:Msg?id=age&amp;errorClass=error&quot;&gt;error&lt;/span&gt;
      &lt;input name=&quot;age&quot; id=&quot;the_age&quot; value=&quot;0&quot;&gt;&lt;br&gt;
      &lt;input type=&quot;submit&quot; value=&quot;Submit&quot;&gt;
    &lt;/div&gt;
  &lt;/div&gt;
&lt;/div&gt;
​
</pre>
</div>
<div class="Standard">
This HTML is different. Note: <tt>Age: &lt;span class=&quot;lift:Msg?id=age&amp;errorClass=error&quot;&gt;error&lt;/span&gt;</tt>. We mark an area in the markup to put the error message.
</div>
<div class="Standard">
Let’s look at our snippet code which is very similar to <tt>Stateful.scala</tt> with a small, but important difference:
</div>
<div class="listing">
<div class="caption">
FieldErrorExample.scala
</div>
<pre class="listing brush: scala">package code
package snippet
​
import net.liftweb._
import http._
import common._
import util.Helpers._
import scala.xml.NodeSeq
​
/**
 * A StatefulSnippet like Stateful.scala
 */
class FieldErrorExample extends StatefulSnippet {
  private var name = &quot;&quot;
  private var age = &quot;0&quot;
  private val whence = S.referer openOr &quot;/&quot;
​
  def dispatch = {case _ =&gt; render}
​
  def render =
    &quot;name=name&quot; #&gt; SHtml.text(name, name = _) &amp;
    &quot;name=age&quot; #&gt; SHtml.text(age, age = _) &amp;
    &quot;type=submit&quot; #&gt; SHtml.onSubmitUnit(process)
  
  // like Stateful
  private def process() =
    asInt(age) match {
      // notice the parameter for error corresponds to
      // the id in the Msg span
      case Full(a) if a &lt; 13 =&gt; S.error(&quot;age&quot;, &quot;Too young!&quot;)
      case Full(a) =&gt; {
        S.notice(&quot;Name: &quot;+name)
        S.notice(&quot;Age: &quot;+a)
        S.redirectTo(whence)
      }
      
      // notice the parameter for error corresponds to
      // the id in the Msg span
      case _ =&gt; S.error(&quot;age&quot;, &quot;Age doesn't parse as a number&quot;)
    }
}
</pre>
</div>
<div class="Standard">
The key difference is: <tt>case Full(a) if a &lt; 13 =&gt; S.error(<b>&quot;age&quot;</b>, &quot;Too young!&quot;)</tt>. Note that we pass &quot;age&quot; to <tt>S.error</tt> and this corresponds to the <tt>id</tt> in the <tt>Msg</tt> snippet in markup. This tells Lift how to associate the error message and the markup.
</div>
<div class="Standard">
But there’s a better way to do complex forms in Lift: <tt>LiftScreen</tt>.
</div>
<h2 class="Section">
<a name="toc-Section-4.6" class="toc">4.6</a> <tt>LiftScreen</tt>
</h2>
<div class="Standard">
Much of what we do to build web applications is generating screens that associate input with dynamic content. Lift provides Screen and Wizard for building single page and multi-page input forms with validation, back-button support, etc.
</div>
<div class="Standard">
So, let’s look at the HTML for a screen:
</div>
<div class="listing">
<div class="caption">
screen.html
</div>
<pre class="listing brush: xml">&lt;div id=&quot;main&quot; class=&quot;lift:surround?with=default&amp;at=content&quot;&gt;
  &lt;div&gt;
    Let's use Lift's LiftScreen to build complex
    simple screen input forms.
  &lt;/div&gt;
      
  &lt;div class=&quot;lift:ScreenExample&quot;&gt;
    Put your form here
  &lt;/div&gt;
&lt;/div&gt;
​
</pre>
</div>
<div class="Standard">
We don’t explicitly declare the form elements. We just point to the snippet which looks like:
</div>
<div class="listing">
<div class="caption">
ScreenExample.scala
</div>
<pre class="listing brush: scala">package code
package snippet
​
import net.liftweb._
import http._
​
/**
 * Declare the fields on the screen
 */
object ScreenExample extends LiftScreen {
  // here are the fields and default values
  val name = field(&quot;Name&quot;, &quot;&quot;)
​
  // the age has validation rules
  val age = field(&quot;Age&quot;, 0, minVal(13, &quot;Too Young&quot;))
​
  def finish() {
    S.notice(&quot;Name: &quot;+name)
    S.notice(&quot;Age: &quot;+age)
  }
}
</pre>
</div>
<div class="Standard">
In the screen, we define the fields and their validation rules and then what to do when the screen is finished. Lift takes care of the rest.
</div>
<div class="Standard">
The markup for generating the form, by default, is found in <tt>/templates-hidden/wizard-all.html</tt>. You can also select templates on a screen-by-screen basis.
</div>
<h2 class="Section">
<a name="toc-Section-4.7" class="toc">4.7</a> <tt>Wizard</tt>
</h2>
<div class="Standard">
<tt>LiftScreen</tt> is great for single screen applications. If you’ve got input and validation that requires multiple screens, Wizard is what you want. We’ll skip the markup ’cause it’s just a snippet invocation. Here’s the wizard code:
</div>
<div class="listing">
<div class="caption">
WizardExample.scala
</div>
<pre class="listing brush: scala">package code
package snippet
​
import net.liftweb._
import http._
import wizard._
import util._
​
/**
 * Define the multi-page input screen
 */
object WizardExample extends Wizard {
​
  // define the first screen
  val screen1 = new Screen {
    val name = field(&quot;Name&quot;, &quot;&quot;)
    val age = field(&quot;Age&quot;, 0, minVal(13, &quot;Too Young&quot;))
  }
​
  // define the second screen
  val screen2 = new Screen {
​
    // a radio button
    val rad = radio(&quot;Radio&quot;, &quot;Red&quot;, List(&quot;Red&quot;, &quot;Green&quot;, &quot;Blue&quot;))
​
    // a select
    val sel = select(&quot;Select&quot;, &quot;Archer&quot;, List(&quot;Elwood&quot;, &quot;Archer&quot;, &quot;Madeline&quot;))
​
    // want a text area... yeah, we got that
    val ta = textarea(&quot;Text Area&quot;, &quot;&quot;)
​
    // here are password inputs with minimum lenght
    val pwd1 = password(&quot;Password&quot;, &quot;&quot;, valMinLen(6, &quot;Password too short&quot;))
​
    // and a custom validator
    val pwd2 = password(&quot;Password (re-enter)&quot;, &quot;&quot;, mustMatch _)
​
    // return a List[FieldError]... there's an implicit conversion
    // from String to List[FieldError] that inserts the field's ID
    def mustMatch(s: String): List[FieldError] = 
      if (s != pwd1.is) &quot;Passwords do not match&quot; else Nil
      
  }
​
  def finish() {
    S.notice(&quot;Name: &quot;+screen1.name)
    S.notice(&quot;Age: &quot;+screen1.age)
  }
}
</pre>
</div>
<div class="Standard">
It’s declarative just like the screen example above. The back button works. You can have multiple wizards active in multiple tabs in your browser and they don’t intefer with each other.
</div>
<h2 class="Section">
<a name="toc-Section-4.8" class="toc">4.8</a> Ajax
</h2>
<div class="Standard">
In addition to full-page HTML, Lift support Ajax forms. Because Lift’s forms are functions on the server-side associated with GUIDs in the browser, switching a form from full page load to Ajax is, well, pretty trivial. Let’s look at the markup:
</div>
<div class="listing">
<div class="caption">
ajax.html
</div>
<pre class="listing brush: xml">&lt;div id=&quot;main&quot; class=&quot;lift:surround?with=default&amp;at=content&quot;&gt;
  &lt;div&gt;
    An example of doing forms with Ajax.
  &lt;/div&gt;
  
  &lt;form class=&quot;lift:form.ajax&quot;&gt;
    &lt;div class=&quot;lift:AjaxExample&quot;&gt;
      Name: &lt;input name=&quot;name&quot;&gt;&lt;br&gt;
      Age: &lt;span class=&quot;lift:Msg?id=age&amp;errorClass=error&quot;&gt;error&lt;/span&gt;&lt;input name=&quot;age&quot; id=&quot;the_age&quot; value=&quot;0&quot;&gt;&lt;br&gt;
      &lt;input type=&quot;submit&quot; value=&quot;Submit&quot;&gt;
    &lt;/div&gt;
  &lt;/form&gt;
&lt;/div&gt;
​
</pre>
</div>
<div class="Standard">
The key difference is: <tt>&lt;form class=&quot;lift:form.ajax&quot;&gt;</tt>. This invokes Lift’s built-in <tt>form</tt> snippet and designates the current form as an Ajax form. Then the snippet does the following:
</div>
<div class="listing">
<div class="caption">
AjaxExample.scala
</div>
<pre class="listing brush: scala">package code
package snippet
​
import net.liftweb._
import http._
import common._
import util.Helpers._
import js._
import JsCmds._
import JE._
import scala.xml.NodeSeq
​
/**
 * Ajax for processing... it looks a lot like the Stateful example
 */
object AjaxExample {
  def render = {
    // state
    var name = &quot;&quot;
    var age = &quot;0&quot;
    val whence = S.referer openOr &quot;/&quot;
​
    // our process method returns a
    // JsCmd which will be sent back to the browser
    // as part of the response
    def process(): JsCmd= {
​
      // sleep for 400 millis to allow the user to
      // see the spinning icon
      Thread.sleep(400)
      
      // do the matching
      asInt(age) match {
        // display an error and otherwise do nothing
        case Full(a) if a &lt; 13 =&gt; S.error(&quot;age&quot;, &quot;Too young!&quot;); Noop
​
        // redirect to the page that the user came from
        // and display notices on that page
        case Full(a) =&gt; {
          RedirectTo(whence, () =&gt; {
            S.notice(&quot;Name: &quot;+name)
            S.notice(&quot;Age: &quot;+a)
          })
        }
        
        // more errors
        case _ =&gt; S.error(&quot;age&quot;, &quot;Age doesn't parse as a number&quot;); Noop
      }
    }
​
    // binding looks normal
    &quot;name=name&quot; #&gt; SHtml.text(name, name = _, &quot;id&quot; -&gt; &quot;the_name&quot;) &amp;
    &quot;name=age&quot; #&gt; (SHtml.text(age, age = _) ++ SHtml.hidden(process))
  }
}
</pre>
</div>
<div class="Standard">
The code looks a lot like the Stateful code. Except that we don’t bind to the submit button (the submit button is not serialized over Ajax), so we have to add a hidden field to the age field which does the processing.
</div>
<div class="Standard">
The <tt>process()</tt> method returns a <tt>JsCmd</tt> which is the JavaScript command to send back to the browser in response to the Ajax form submission. In this case, we’re either using <tt>S.error</tt> to display error notices followed by a <tt>Noop</tt> or we’re doing a redirect.
</div>
<div class="Standard">
We pause for 400 milliseconds in the <tt>process()</tt> method so that the user can see the spinner in the browser indicating that an Ajax operation is taking place.
</div>
<div class="Standard">
But the core take-away is that normal HTML processing and Ajax processing are almost identical and both are super-easy.
</div>
<h2 class="Section">
<a name="toc-Section-4.9" class="toc">4.9</a> But sometimes Old Fashioned is good
</h2>
<div class="Standard">
In this chapter, we’ve explored Lift’s form building and processing features and demonstrated the power and value of associating GUIDs on the client with functions on the server. However, sometimes it’s nice to have parameter processing via URL parameters... and that’s easy to do with Lift as well.
</div>
<div class="Standard">
Every page in the examples for this chapter contain:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: xml">	&lt;form action=&quot;/query&quot;&gt;
	  &lt;input name=&quot;q&quot;&gt;
	  &lt;input type=&quot;submit&quot; value=&quot;Search&quot;&gt;
	&lt;/form&gt;
</pre>
</div>

</div>
<div class="Standard">
This is a plain old form that generates a URL like: <tt>http://localhost:8080/query?q=catfood</tt> This URL can be copied, pasted, shared, etc.
</div>
<div class="Standard">
Processing this URL is easy:
</div>
<div class="listing">
<div class="caption">
Query.scala
</div>
<pre class="listing brush: scala">package code
package snippet
​
import net.liftweb._
import http._
import util._
import Helpers._
​
object Query {
  def results = ClearClearable andThen
  &quot;li *&quot; #&gt; S.param(&quot;q&quot;). // get the query parameter
  toList. // convert the Box to a List
  flatMap(q =&gt; {
    (&quot;You asked: &quot;+q) :: // prepend the query
    (1 to toInt(q)).toList.map(_.toString) // if it can be converted to an Int
    // convert it and return a sequence of Ints
  })
}
</pre>
</div>
<div class="Standard">
Using <tt>S.param(&quot;param_name&quot;)</tt> we can extract the query parameter and do something with it.
</div>
<h2 class="Section">
<a name="toc-Section-4.10" class="toc">4.10</a> Conclusion
</h2>
<div class="Standard">
Lift’s form generation and processing tools offer a wide variety of mechanisms to securely, simply and powerfully generate and process HTML forms either as part of full HTTP requests or via Ajax requests.
</div>
<div class="Standard">

</div>
<h1 class="Chapter">
<a name="toc-Chapter-5" class="toc">5</a> <a name="cha:HTTP-and-REST" class="Label"> </a>HTTP and REST
</h1>
<div class="Standard">
We explored Lift’s HTML generation features. Let’s dive down to a lower level and handle HTTP requests REST-style. The code for this chapter can be found at <a href="https://github.com/dpp/simply_lift/tree/master/samples/http_rest" class="URL">https://github.com/dpp/simply_lift/tree/master/samples/http_rest</a>
</div>
<h2 class="Section">
<a name="toc-Section-5.1" class="toc">5.1</a> Introduction
</h2>
<div class="Standard">
Lift gives you access to low level HTTP requests, either within the scope of an session or outside the scope of a session. In sessionless or stateless mode, Lift does not use the container’s session management machinery to add a cookie to the <tt>HTTP</tt> response and does not make <tt>SessionVar</tt> or <tt>ContainerVar</tt> available during the request. Stateless REST requests do not require session affinity. Authentication for stateless REST handling can be done via <a href="http://oauth.net/" class="URL">OAuth</a>. If the requests are handled statefully, a container session will be created if the <tt>JSESSIONID</tt> cookie is not supplied as part of the request and the <tt>JSESSIONID</tt> cookie will be included with the response.
</div>
<div class="Standard">
Lift makes use of Scala’s pattern matching to allow you match incoming HTTP requests, extract values as part of the pattern matching process and return the results. Scala’s pattern matching is very, very powerful. It allows both the declaration of a pattern that must be matched, wildcard values (a sub-expression may match any supplied value), wildcard values extracted into variables, and explicit extractors (imperative logic applied to a value to determine if it should match and if it does, extract it into a variable). Lift tests a Scala <tt>PartialFunction[Req, () =&gt; Box[LiftResponse]]</tt> to see if it is defined for a given <tt>Req</tt>, which represents an HTTP request. If there is a match, Lift will take the resulting function, apply it to get a <tt>Box[LiftResponse]</tt> and if the <tt>Box</tt> is full, the response will be sent back to the browser. That’s a mouth-full. Let’s look at examples.
</div>
<h2 class="Section">
<a name="toc-Section-5.2" class="toc">5.2</a> REST the hard way
</h2>
<div class="Standard">
Let’s take a look at the raw level of doing REST with Lift: taking an incoming HTTP request and transforming it into a function that returns a <tt>Box[LiftResponse]</tt> (and don’t worry, it gets easier, but we’re starting with the ugly verbose stuff so you get an idea of what’s happening under the covers):
</div>
<div class="listing">
<div class="caption">
BasicExample.scala
</div>
<pre class="listing brush: scala">package code
package lib
​
import model._
​
import net.liftweb._
import common._
import http._
​
/**
 * A simple example of a REST style interface
 * using the basic Lift tools
 */
object BasicExample {
  /*
   * Given a suffix and an item, make a LiftResponse
   */
  private def toResponse(suffix: String, item: Item) =
    suffix match {
      case &quot;xml&quot; =&gt; XmlResponse(item)
      case _ =&gt; JsonResponse(item)
    }
​
  /**
   * Find /simple/item/1234.json
   * Find /simple/item/1234.xml
   */
  lazy val findItem: LiftRules.DispatchPF = {
    case Req(&quot;simple&quot; :: &quot;item&quot; :: itemId :: Nil, //  path
             suffix, // suffix
             GetRequest) =&gt; 
               () =&gt; Item.find(itemId).map(toResponse(suffix, _))
  }
​
  /**
   * Find /simple2/item/1234.json
   */
  lazy val extractFindItem: LiftRules.DispatchPF = {
    // path with extractor
    case Req(&quot;simple2&quot; :: &quot;item&quot; :: Item(item) :: Nil, 
             suffix, GetRequest) =&gt;
               // a function that returns the response
               () =&gt; Full(toResponse(suffix, item))
  }
}
</pre>
</div>
<div class="Standard">
One additional piece of the puzzle is hooking up the handlers to Lift. This is done in <tt>Boot.scala</tt> with the following lines:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: scala">    // the stateless REST handlers
    LiftRules.statelessDispatchTable.append(BasicExample.findItem)
    LiftRules.statelessDispatchTable.append(BasicExample.extractFindItem)
​
    // stateful versions of the same
    // LiftRules.dispatch.append(BasicExample.findItem)
    // LiftRules.dispatch.append(BasicExample.extractFindItem)
</pre>
</div>

</div>
<div class="Standard">
Let’s break down the code. First, each handler is a <tt>PartialFunction[Req, () =&gt; Box[LiftResponse]]</tt>, but we can use a shorthand of <tt>LiftRules.dispatchPF</tt> which is a Scala type that aliases the partial function.
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: scala">lazy val findItem: LiftRules.DispatchPF =
</pre>
</div>

</div>
<div class="Standard">
defines <tt>findItem</tt> which has the type signature of a request dispatch handler.
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: scala">    case Req(&quot;simple&quot; :: &quot;item&quot; :: itemId :: Nil, //  path
             suffix, // suffix
             GetRequest) =&gt; 
</pre>
</div>

</div>
<div class="Standard">
Defines a pattern to match. In this case, any 3 part path that has the first two parts <tt>/simple/item</tt> will be matched. The third part of the path will be extracted to the variable <tt>itemId</tt>. The suffix of the last path item will be extracted to the variable <tt>suffix</tt> and the request must be a GET.
</div>
<div class="Standard">
If the above criteria is met, then the partial function is defined and Lift will apply the partial function to get the resulting <tt>() =&gt; Box[LiftResponse]</tt>.
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: scala">               () =&gt; Item.find(itemId).map(toResponse(suffix, _))
</pre>
</div>

</div>
<div class="Standard">
This is a function that finds the <tt>itemId</tt> and converts the resulting <tt>Item</tt> to a response based on the request suffix. The <tt>toResponse</tt> method looks like:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: scala">  /*
   * Given a suffix and an item, make a LiftResponse
   */
  private def toResponse(suffix: String, item: Item) =
    suffix match {
      case &quot;xml&quot; =&gt; XmlResponse(item)
      case _ =&gt; JsonResponse(item)
    }
</pre>
</div>

</div>
<div class="Standard">
That’s all pretty straight forward, if a little verbose. Let’s look at the other example in this file. It uses an extractor to convert the <tt>String</tt> of the third element of the request path to an <tt>Item</tt>:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: scala">    // path with extractor
    case Req(&quot;simple2&quot; :: &quot;item&quot; :: Item(item) :: Nil, 
             suffix, GetRequest) =&gt;
</pre>
</div>

</div>
<div class="Standard">
In this case, the pattern will not be matched unless that third element of the path is a valid <tt>Item</tt>. If it is, the variable <tt>item</tt> will contain the <tt>Item</tt> for processing. Converting this to a valid response looks like:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: scala">               // a function that returns the response
               () =&gt; Full(toResponse(suffix, item))
</pre>
</div>

</div>
<div class="Standard">
Let’s look at the <tt>object Item</tt>’s unapply method to see how the extraction works:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: scala">  /**
   * Extract a String (id) to an Item
   */
  def unapply(id: String): Option[Item] = Item.find(id)
</pre>
</div>

</div>
<div class="Standard">
In fact, let’s look at the entire <tt>Item</tt> code listing. As promised, <i>Simply Lift</i>, does not explicitly cover persistence. This class is an in-memory mock persistence class, but it behaves like any other persistence mechanism in Lift.
</div>
<div class="listing">
<div class="caption">
Item.scala
</div>
<pre class="listing brush: scala">package code
package model
​
import net.liftweb._
import util._
import Helpers._
import common._
import json._
​
import scala.xml.Node
​
/**
 * An item in inventory
 */
case class Item(id: String, name: String, 
                description: String,
                price: BigDecimal, taxable: Boolean,
                weightInGrams: Int, qnty: Int)
​
/**
 * The Item companion object
 */
object Item {
  private implicit val formats =
    net.liftweb.json.DefaultFormats + BigDecimalSerializer
​
  private var items: List[Item] = parse(data).extract[List[Item]]
​
  private var listeners: List[Item =&gt; Unit] = Nil
​
  /**
   * Convert a JValue to an Item if possible
   */
  def apply(in: JValue): Box[Item] = Helpers.tryo{in.extract[Item]}
​
  /**
   * Extract a String (id) to an Item
   */
  def unapply(id: String): Option[Item] = Item.find(id)
​
  /**
   * Extract a JValue to an Item
   */
  def unapply(in: JValue): Option[Item] = apply(in)
​
  /**
   * The default unapply method for the case class.
   * We needed to replicate it here because we
   * have overloaded unapply methods
   */
  def unapply(in: Any): Option[(String, String, 
                                String,
                                BigDecimal, Boolean,
                                Int, Int)] = {
    in match {
      case i: Item =&gt; Some((i.id, i.name, i.description,
                            i.price, i.taxable,
                            i.weightInGrams, i.qnty))
      case _ =&gt; None
    }
  }
​
  /**
   * Convert an item to XML
   */
  implicit def toXml(item: Item): Node = 
    <item>{Xml.toXml(item)}</item>
​
​
  /**
   * Convert the item to JSON format.  This is
   * implicit and in the companion object, so
   * an Item can be returned easily from a JSON call
   */
  implicit def toJson(item: Item): JValue = 
    Extraction.decompose(item)
​
  /**
   * Convert a Seq[Item] to JSON format.  This is
   * implicit and in the companion object, so
   * an Item can be returned easily from a JSON call
   */
  implicit def toJson(items: Seq[Item]): JValue = 
    Extraction.decompose(items)
​
  /**
   * Convert a Seq[Item] to XML format.  This is
   * implicit and in the companion object, so
   * an Item can be returned easily from an XML REST call
   */
  implicit def toXml(items: Seq[Item]): Node = 
    <items>{
      items.map(toXml)
    }</items>
​
  /**
   * Get all the items in inventory
   */
  def inventoryItems: Seq[Item] = items
​
  // The raw data
  private def data = 
&quot;&quot;&quot;[
  {&quot;id&quot;: &quot;1234&quot;, &quot;name&quot;: &quot;Cat Food&quot;,
  &quot;description&quot;: &quot;Yummy, tasty cat food&quot;,
  &quot;price&quot;: 4.25,
  &quot;taxable&quot;: true,
  &quot;weightInGrams&quot;: 1000,
  &quot;qnty&quot;: 4
  },
  {&quot;id&quot;: &quot;1235&quot;, &quot;name&quot;: &quot;Dog Food&quot;,
  &quot;description&quot;: &quot;Yummy, tasty dog food&quot;,
  &quot;price&quot;: 7.25,
  &quot;taxable&quot;: true,
  &quot;weightInGrams&quot;: 5000,
  &quot;qnty&quot;: 72
  },
  {&quot;id&quot;: &quot;1236&quot;, &quot;name&quot;: &quot;Fish Food&quot;,
  &quot;description&quot;: &quot;Yummy, tasty fish food&quot;,
  &quot;price&quot;: 2,
  &quot;taxable&quot;: false,
  &quot;weightInGrams&quot;: 200,
  &quot;qnty&quot;: 45
  },
  {&quot;id&quot;: &quot;1237&quot;, &quot;name&quot;: &quot;Sloth Food&quot;,
  &quot;description&quot;: &quot;Slow, slow sloth food&quot;,
  &quot;price&quot;: 18.33,
  &quot;taxable&quot;: true,
  &quot;weightInGrams&quot;: 750,
  &quot;qnty&quot;: 62
  },
]
&quot;&quot;&quot;
​
  /**
   * Select a random Item
   */
  def randomItem: Item = synchronized {
    items(Helpers.randomInt(items.length))
  }
​
  /**
   * Find an item by id
   */
  def find(id: String): Box[Item] = synchronized {
    items.find(_.id == id)
  }
​
  /**
   * Add an item to inventory
   */
  def add(item: Item): Item = {
    synchronized {
      items = item :: items.filterNot(_.id == item.id)
      updateListeners(item)
    }
  }
​
  /**
   * Find all the items with the string in their name or
   * description
   */
  def search(str: String): List[Item] = {
    val strLC = str.toLowerCase()
​
    items.filter(i =&gt;
      i.name.toLowerCase.indexOf(strLC) &gt;= 0 ||
                 i.description.toLowerCase.indexOf(strLC) &gt;= 0)
  }
​
  /**
   * Deletes the item with id and returns the
   * deleted item or Empty if there's no match
   */
  def delete(id: String): Box[Item] = synchronized {
    var ret: Box[Item] = Empty
​
    val Id = id // an upper case stable ID for pattern matching
​
    items = items.filter {
      case i@Item(Id, _, _, _, _, _, _) =&gt; 
        ret = Full(i) // side effect
        false
      case _ =&gt; true
    }
​
    ret.map(updateListeners)
  }
​
  /**
   * Update listeners when the data changes
   */
  private def updateListeners(item: Item): Item = {
    synchronized {
      listeners.foreach(f =&gt; 
        Schedule.schedule(() =&gt; f(item), 0 seconds))
​
      listeners = Nil
    }
    item
  }
​
  /**
   * Add an onChange listener
   */
  def onChange(f: Item =&gt; Unit) {
    synchronized {
      // prepend the function to the list of listeners
      listeners ::= f
    }
  }
    
}
​
/**
 * A helper that will JSON serialize BigDecimal
 */
object BigDecimalSerializer extends Serializer[BigDecimal] {
  private val Class = classOf[BigDecimal]
​
  def deserialize(implicit format: Formats): PartialFunction[(TypeInfo, JValue), BigDecimal] = {
    case (TypeInfo(Class, _), json) =&gt; json match {
      case JInt(iv) =&gt; BigDecimal(iv)
      case JDouble(dv) =&gt; BigDecimal(dv)
      case value =&gt; throw new MappingException(&quot;Can't convert &quot; + value + &quot; to &quot; + Class)
    }
  }
​
  def serialize(implicit format: Formats): PartialFunction[Any, JValue] = {
    case d: BigDecimal =&gt; JDouble(d.doubleValue)
  }
}
</pre>
</div>
<div class="Standard">
Let’s take a look at what the resulting output is:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: scala">dpp@raptor:~/proj/simply_lift/samples/http_rest$ curl http://localhost:8080/simple/item/1234
{
  &quot;id&quot;:&quot;1234&quot;,
  &quot;name&quot;:&quot;Cat Food&quot;,
  &quot;description&quot;:&quot;Yummy, tasty cat food&quot;,
  &quot;price&quot;:4.25,
  &quot;taxable&quot;:true,
  &quot;weightInGrams&quot;:1000,
  &quot;qnty&quot;:4
}
​
dpp@raptor:~/proj/simply_lift/samples/http_rest$ curl http://localhost:8080/simple/item/1234.xml
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;item&gt;
  &lt;id&gt;1234&lt;/id&gt;
  &lt;name&gt;Cat Food&lt;/name&gt;
  &lt;description&gt;Yummy, tasty cat food&lt;/description&gt;
  &lt;price&gt;4.25&lt;/price&gt;
  &lt;taxable&gt;true&lt;/taxable&gt;
  &lt;weightInGrams&gt;1000&lt;/weightInGrams&gt;
  &lt;qnty&gt;4&lt;/qnty&gt;
&lt;/item&gt;  
dpp@raptor:~/proj/simply_lift/samples/http_rest$ 
​
</pre>
</div>

</div>
<h2 class="Section">
<a name="toc-Section-5.3" class="toc">5.3</a> Making it easier with <tt>RestHelper</tt>
</h2>
<div class="Standard">
The above example shows you how Lift deals with REST calls. However, it’s a tad verbose. Lift’s <tt>RestHelper</tt> trait contains a lot of very helpful shortcuts that make code more concise, easier to read and easier to maintain. Let’s look at a bunch of examples and then we’ll work through each one:
</div>
<div class="listing">
<div class="caption">
BasicWithHelper.scala
</div>
<pre class="listing brush: scala">package code
package lib
​
import model._
​
import net.liftweb._
import common._
import http._
import rest._
import json._
import scala.xml._
​
/**
 * A simple example of a REST style interface
 * using the basic Lift tools
 */
object BasicWithHelper extends RestHelper {
  /*
   * Serve the URL, but have a helpful error message when you
   * return a 404 if the item is not found
   */
  serve {
    case &quot;simple3&quot; :: &quot;item&quot; :: itemId :: Nil JsonGet _ =&gt;
      for {
        // find the item, and if it's not found,
        // return a nice message for the 404
        item &lt;- Item.find(itemId) ?~ &quot;Item Not Found&quot;
      } yield item: JValue
​
    case &quot;simple3&quot; :: &quot;item&quot; :: itemId :: Nil XmlGet _ =&gt;
      for {
        item &lt;- Item.find(itemId) ?~ &quot;Item Not Found&quot;
      } yield item: Node
  }
​
​
  
  serve {
    // Prefix notation
    case JsonGet(&quot;simple4&quot; :: &quot;item&quot; :: Item(item) :: Nil, _) =&gt;
      // no need to explicitly create a LiftResponse
      // Just make it JSON and RestHelper does the rest
      item: JValue
​
    // infix notation
    case &quot;simple4&quot; :: &quot;item&quot; :: Item(item) :: Nil XmlGet _ =&gt;
      item: Node
  }
​
  // serve a bunch of items given a single prefix
  serve ( &quot;simple5&quot; / &quot;item&quot; prefix {
    // all the inventory
    case Nil JsonGet _ =&gt; Item.inventoryItems: JValue
    case Nil XmlGet _ =&gt; Item.inventoryItems: Node
​
    // a particular item
    case Item(item) :: Nil JsonGet _ =&gt; item: JValue
    case Item(item) :: Nil XmlGet _ =&gt; item: Node
  })
​
  /**
   * Here's how we convert from an Item
   * to JSON or XML depending on the request's
   * Accepts header
   */
  implicit def itemToResponseByAccepts: JxCvtPF[Item] = {
    case (JsonSelect, c, _) =&gt; c: JValue
    case (XmlSelect, c, _) =&gt; c: Node
  }
​
  /**
   * serve the response by returning an item
   * (or a Box[Item]) and let RestHelper determine
   * the conversion to a LiftResponse using
   * the itemToResponseByAccepts partial function
   */
  serveJx[Item] {
    case &quot;simple6&quot; :: &quot;item&quot; :: Item(item) :: Nil Get _ =&gt; item
    case &quot;simple6&quot; :: &quot;item&quot; :: &quot;other&quot; :: item :: Nil Get _ =&gt; 
      Item.find(item) ?~ &quot;The item you're looking for isn't here&quot;
  }
​
  /**
   * Same as the serveJx example above, but we've
   * used prefixJx to avoid having to copy the path
   * prefix over and over again
   */
  serveJx[Item] {
    &quot;simple7&quot; / &quot;item&quot; prefixJx {
      case Item(item) :: Nil Get _ =&gt; item
      case &quot;other&quot; :: item :: Nil Get _ =&gt; 
        Item.find(item) ?~ &quot;The item you're looking for isn't here&quot;
    }
  }
  
}
</pre>
</div>
<div class="Standard">
The first thing is how we declare and register the <tt>RestHelper</tt>-based service:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: scala">/**
 * A simple example of a REST style interface
 * using the basic Lift tools
 */
object BasicWithHelper extends RestHelper {
</pre>
</div>

</div>
<div class="Standard">
Our <tt>BaseicWithHelper</tt> singleton extends the <tt>net.liftweb.http.rest.RestHelper</tt> trait. We register the dispatch in <tt>Boot.scala</tt>:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: scala">    LiftRules.statelessDispatchTable.append(BasicWithHelper)
</pre>
</div>

</div>
<div class="Standard">
This means that the whole <tt>BasicWithHelper</tt> singleton is a <tt>PartialFunction[Req, () =&gt; Box[LiftResponse]]</tt> that aggregates all the sub-patterns contained inside it. We defined the sub-patterns in a <tt>serve</tt> block which contains the pattern to match. For example:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: scala">  serve {
    case &quot;simple3&quot; :: &quot;item&quot; :: itemId :: Nil JsonGet _ =&gt;
      for {
        // find the item, and if it’s not found,
        // return a nice message for the 404
        item &lt;- Item.find(itemId) ?~ &quot;Item Not Found&quot;
      } yield item: JValue
​
    case &quot;simple3&quot; :: &quot;item&quot; :: itemId :: Nil XmlGet _ =&gt;
      for {
        item &lt;- Item.find(itemId) ?~ &quot;Item Not Found&quot;
      } yield item: Node
  }
</pre>
</div>

</div>
<div class="Standard">
Let’s break this down further:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: scala">case &quot;simple3&quot; :: &quot;item&quot; :: itemId :: Nil JsonGet _ =&gt;
</pre>
</div>

</div>
<div class="Standard">
The above matches <tt>/simple3/item/</tt>xxx where xxx is extracted to the <tt>itemId</tt> variable. The request must also have an <tt>Accepts</tt> header that calls for JSON.
</div>
<div class="Standard">
If the pattern matches, execute the following code:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: scala">      for {
        // find the item, and if it’s not found,
        // return a nice message for the 404
        item &lt;- Item.find(itemId) ?~ &quot;Item Not Found&quot;
      } yield item: JValue
</pre>
</div>

</div>
<div class="Standard">
Some things to notice, we didn’t explicitly create a function that returns a <tt>Box[LiftResponse]</tt>. Instead, the type is <tt>Box[JValue]</tt>. <tt>RestHelper</tt> provides implicit conversions from <tt>Box[JValue]</tt> to <tt>() =&gt; Box[LiftResponse]</tt>. Specifically, if the <tt>Box</tt> is a <tt>Failure</tt>, <tt>RestHelper</tt> will generate a 404 response with the <tt>Failure</tt> message as the 404’s body. If the <tt>Box</tt> is <tt>Full</tt>, <tt>RestHelper</tt> will create a <tt>JsonResponse</tt> with the value in the payload. Let’s take a look at the two cases:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: scala">dpp@raptor:~/proj/simply_lift/samples/http_rest$ curl http://localhost:8080/simple3/item/12999
Item Not Found
​
dpp@raptor:~/proj/simply_lift/samples/http_rest$ curl http://localhost:8080/simple3/item/1234
{
  &quot;id&quot;:&quot;1234&quot;,
  &quot;name&quot;:&quot;Cat Food&quot;,
  &quot;description&quot;:&quot;Yummy, tasty cat food&quot;,
  &quot;price&quot;:4.25,
  &quot;taxable&quot;:true,
  &quot;weightInGrams&quot;:1000,
  &quot;qnty&quot;:4
}
</pre>
</div>

</div>
<div class="Standard">
The XML example is pretty much the same, except we coerse the response to <tt>Box[Node]</tt> which <tt>RestHelper</tt> converts into an <tt>XmlResponse</tt>:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: scala">    case &quot;simple3&quot; :: &quot;item&quot; :: itemId :: Nil XmlGet _ =&gt;
      for {
        item &lt;- Item.find(itemId) ?~ &quot;Item Not Found&quot;
      } yield item: Node
</pre>
</div>

</div>
<div class="Standard">
Which results in the following:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: scala">dpp@raptor:~/proj/simply_lift/samples/http_rest$ curl -i -H &quot;Accept: application/xml&quot; http://localhost:8080/simple3/item/1234
HTTP/1.1 200 OK
Expires: Wed, 9 Mar 2011 01:48:38 UTC
Content-Length: 230
Cache-Control: no-cache; private; no-store
Content-Type: text/xml; charset=utf-8
Pragma: no-cache
Date: Wed, 9 Mar 2011 01:48:38 UTC
X-Lift-Version: Unknown Lift Version
Server: Jetty(6.1.22)
​
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;item&gt;
  &lt;id&gt;1234&lt;/id&gt;
  &lt;name&gt;Cat Food&lt;/name&gt;
  &lt;description&gt;Yummy, tasty cat food&lt;/description&gt;
  &lt;price&gt;4.25&lt;/price&gt;
  &lt;taxable&gt;true&lt;/taxable&gt;
  &lt;weightInGrams&gt;1000&lt;/weightInGrams&gt;
  &lt;qnty&gt;4&lt;/qnty&gt;
&lt;/item&gt;
</pre>
</div>

</div>
<div class="Standard">
Okay... that’s simpler because we define stuff in the <tt>serve</tt> block and the conversions from <tt>JValue</tt> and <tt>Node</tt> to the right response types is taken care of. Just to be explicit about where the implicit conversions are defined, they’re in the <tt>Item</tt> singleton:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: scala">  /**
   * Convert an item to XML
   */
  implicit def toXml(item: Item): Node = 
    &lt;item&gt;{Xml.toXml(item)}&lt;/item&gt;
​
​
  /**
   * Convert the item to JSON format.  This is
   * implicit and in the companion object, so
   * an Item can be returned easily from a JSON call
   */
  implicit def toJson(item: Item): JValue = 
    Extraction.decompose(item)
</pre>
</div>

</div>
<div class="Standard">
Okay, so, yippee skippy, we can do simpler REST. Let’s keep looking at examples of how we can make it even simpler. This example uses extractors rather than doing the explicit <tt>Item.find</tt>:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: scala">  serve {
    // Prefix notation
    case JsonGet(&quot;simple4&quot; :: &quot;item&quot; :: Item(item) :: Nil, _) =&gt;
      // no need to explicitly create a LiftResponse
      // Just make it JSON and RestHelper does the rest
      item: JValue
​
    // infix notation
    case &quot;simple4&quot; :: &quot;item&quot; :: Item(item) :: Nil XmlGet _ =&gt;
      item: Node
  }
</pre>
</div>

</div>
<div class="Standard">
If you like DRY and don’t want to keep repeating the same path prefixes, you can use <tt>prefix</tt>, for example:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: scala">  // serve a bunch of items given a single prefix
  serve ( &quot;simple5&quot; / &quot;item&quot; prefix {
    // all the inventory
    case Nil JsonGet _ =&gt; Item.inventoryItems: JValue
    case Nil XmlGet _ =&gt; Item.inventoryItems: Node
​
    // a particular item
    case Item(item) :: Nil JsonGet _ =&gt; item: JValue
    case Item(item) :: Nil XmlGet _ =&gt; item: Node
  })
</pre>
</div>

</div>
<div class="Standard">
The above code will list all the items in response to <tt>/simple5/item</tt> and will serve a specific item in response to <tt>/simple5/item/1234</tt>, as we see in:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: scala">dpp@raptor:~/proj/simply_lift/samples/http_rest$ curl http://localhost:8080/simple5/item
[{
  &quot;id&quot;:&quot;1234&quot;,
  &quot;name&quot;:&quot;Cat Food&quot;,
  &quot;description&quot;:&quot;Yummy, tasty cat food&quot;,
  &quot;price&quot;:4.25,
  &quot;taxable&quot;:true,
  &quot;weightInGrams&quot;:1000,
  &quot;qnty&quot;:4
},
...
,{
  &quot;id&quot;:&quot;1237&quot;,
  &quot;name&quot;:&quot;Sloth Food&quot;,
  &quot;description&quot;:&quot;Slow, slow sloth food&quot;,
  &quot;price&quot;:18.33,
  &quot;taxable&quot;:true,
  &quot;weightInGrams&quot;:750,
  &quot;qnty&quot;:62
}]
​
dpp@raptor:~/proj/simply_lift/samples/http_rest$ curl http://localhost:8080/simple5/item/1237
{
  &quot;id&quot;:&quot;1237&quot;,
  &quot;name&quot;:&quot;Sloth Food&quot;,
  &quot;description&quot;:&quot;Slow, slow sloth food&quot;,
  &quot;price&quot;:18.33,
  &quot;taxable&quot;:true,
  &quot;weightInGrams&quot;:750,
  &quot;qnty&quot;:62
}
</pre>
</div>

</div>
<div class="Standard">
In the above examples, we’ve explicitly coersed the results into a <tt>JValue</tt> or <tt>Node</tt> depending on the request type. With Lift, it’s possible to define a conversion from a given type to response types (the default response types are JSON and XML) based on the request type and then define the request patterns to match and <tt>RestHelper</tt> takes care of the rest (so to speak.) Let’s define the conversion from <tt>Item</tt> to <tt>JValue</tt> and <tt>Node</tt> (note the <tt>implicit</tt> keyword, that says that the conversion is available to <tt>serveJx</tt> statements:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: scala">  implicit def itemToResponseByAccepts: JxCvtPF[Item] = {
    case (JsonSelect, c, _) =&gt; c: JValue
    case (XmlSelect, c, _) =&gt; c: Node
  }
</pre>
</div>

</div>
<div class="Standard">
This is pretty straight forward. If it’s a <tt>JsonSelect</tt>, return a <tt>JValue</tt> and if it’s an <tt>XmlSelect</tt>, convert to a <tt>Node</tt>.
</div>
<div class="Standard">
This is used in the <tt>serveJx</tt> statement:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: scala">  serveJx[Item] {
    case &quot;simple6&quot; :: &quot;item&quot; :: Item(item) :: Nil Get _ =&gt; item
    case &quot;simple6&quot; :: &quot;item&quot; :: &quot;other&quot; :: item :: Nil Get _ =&gt; 
      Item.find(item) ?~ &quot;The item you’re looking for isn’t here&quot;
  }
</pre>
</div>

</div>
<div class="Standard">
So <tt>/simple6/item/1234</tt> will match and result in an <tt>Item</tt> being returned and based on the above implicit conversion, we turn the <tt>Item</tt> into a <tt>JValue</tt> or <tt>Node</tt> depending on the <tt>Accepts</tt> header and then convert that to a <tt>() =&gt; Box[LiftResponse]</tt>. Let’s see what <tt>curl</tt> has to say about it:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: scala">dpp@raptor:~/proj/simply_lift/samples/http_rest$ curl http://localhost:8080/simple6/item/1237
{
  &quot;id&quot;:&quot;1237&quot;,
  &quot;name&quot;:&quot;Sloth Food&quot;,
  &quot;description&quot;:&quot;Slow, slow sloth food&quot;,
  &quot;price&quot;:18.33,
  &quot;taxable&quot;:true,
  &quot;weightInGrams&quot;:750,
  &quot;qnty&quot;:62
}
​
dpp@raptor:~/proj/simply_lift/samples/http_rest$ curl -H &quot;Accept: application/xml&quot; http://localhost:8080/simple6/item/1234
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;item&gt;
  &lt;id&gt;1234&lt;/id&gt;
  &lt;name&gt;Cat Food&lt;/name&gt;
  &lt;description&gt;Yummy, tasty cat food&lt;/description&gt;
  &lt;price&gt;4.25&lt;/price&gt;
  &lt;taxable&gt;true&lt;/taxable&gt;
  &lt;weightInGrams&gt;1000&lt;/weightInGrams&gt;
  &lt;qnty&gt;4&lt;/qnty&gt;
&lt;/item&gt;  
</pre>
</div>

</div>
<div class="Standard">
Note also that <tt>/simple6/item/other/1234</tt> does the right thing. This is because the path is 4 elements long, so it won’t match the first part of the pattern, but does match the second part of the pattern.
</div>
<div class="Standard">
Finally, let’s combine <tt>serveJx</tt> and it’s DRY helper, <tt>prefixJx</tt>. 
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: scala">  serveJx[Item] {
    &quot;simple7&quot; / &quot;item&quot; prefixJx {
      case Item(item) :: Nil Get _ =&gt; item
      case &quot;other&quot; :: item :: Nil Get _ =&gt; 
        Item.find(item) ?~ &quot;The item you’re looking for isn’t here&quot;
    }
  }
</pre>
</div>

</div>
<h2 class="Section">
<a name="toc-Section-5.4" class="toc">5.4</a> A complete REST example
</h2>
<div class="Standard">
The above code gives us the bits and pieces that we can combine into a full fledged REST service. Let’s do that combination and see what such a service looks like:
</div>
<div class="listing">
<div class="caption">
FullRest.scala
</div>
<pre class="listing brush: scala">package code
package lib
​
import model._
​
import net.liftweb._
import common._
import http._
import rest._
import util._
import Helpers._
import json._
import scala.xml._
​
/**
 * A full REST example
 */
object FullRest extends RestHelper {
​
  // Serve /api/item and friends
  serve( &quot;api&quot; / &quot;item&quot; prefix {
    
    // /api/item returns all the items
    case Nil JsonGet _ =&gt; Item.inventoryItems: JValue
​
    // /api/item/count gets the item count
    case &quot;count&quot; :: Nil JsonGet _ =&gt; JInt(Item.inventoryItems.length)
​
    // /api/item/item_id gets the specified item (or a 404)
    case Item(item) :: Nil JsonGet _ =&gt; item: JValue
​
    // /api/item/search/foo or /api/item/search?q=foo
    case &quot;search&quot; :: q JsonGet _ =&gt;
      (for {
        searchString &lt;- q ::: S.params(&quot;q&quot;)
        item &lt;- Item.search(searchString)
      } yield item).distinct: JValue
​
    // DELETE the item in question
    case Item(item) :: Nil JsonDelete _ =&gt; 
      Item.delete(item.id).map(a =&gt; a: JValue)
​
    // PUT adds the item if the JSON is parsable
    case Nil JsonPut Item(item) -&gt; _ =&gt; Item.add(item): JValue
    
    // POST if we find the item, merge the fields from the 
    // the POST body and update the item
    case Item(item) :: Nil JsonPost json -&gt; _ =&gt; 
      Item(mergeJson(item, json)).map(Item.add(_): JValue)
​
    // Wait for a change to the Items
    // But do it asynchronously
    case &quot;change&quot; :: Nil JsonGet _ =&gt;
      RestContinuation.async {
        satisfyRequest =&gt; {
          // schedule a &quot;Null&quot; return if there's no other answer
          // after 110 seconds
          Schedule.schedule(() =&gt; satisfyRequest(JNull), 110 seconds)
​
          // register for an &quot;onChange&quot; event.  When it
          // fires, return the changed item as a response
          Item.onChange(item =&gt; satisfyRequest(item: JValue))
        }
      }
  })
}
</pre>
</div>
<div class="Standard">
The whole service is JSON only and contained in a single <tt>serve</tt> block and uses the <tt>prefix</tt> helper to define all the requests under <tt>/api/item</tt> as part of the service.
</div>
<div class="Standard">
The first couple of patterns are a re-hash of what we’ve already covered:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: scala">    // /api/item returns all the items
    case Nil JsonGet _ =&gt; Item.inventoryItems: JValue
​
    // /api/item/count gets the item count
    case &quot;count&quot; :: Nil JsonGet _ =&gt; JInt(Item.inventoryItems.length)
​
    // /api/item/item_id gets the specified item (or a 404)
    case Item(item) :: Nil JsonGet _ =&gt; item: JValue
</pre>
</div>

</div>
<div class="Standard">
The next is a search feature at <tt>/api/item/search</tt>. Using a little Scala library fun, we create a list of the request path elements that come after the <tt>search</tt> element and all the query parameters named <tt>q</tt>. Based on these, we search for all the <tt>Item</tt>s that match the search term. We wind up with a <tt>List[Item]</tt> and we remove duplicates with <tt>distinct</tt> and finally coerse the <tt>List[Item]</tt> to a <tt>JValue</tt>:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: scala">    // /api/item/search/foo or /api/item/search?q=foo
    case &quot;search&quot; :: q JsonGet _ =&gt;
      (for {
        searchString &lt;- q ::: S.params(&quot;q&quot;)
        item &lt;- Item.search(searchString)
      } yield item).distinct: JValue
</pre>
</div>

</div>
<div class="Standard">
Next, let’s see how to delete an <tt>Item</tt>:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: scala">    // DELETE the item in question
    case Item(item) :: Nil JsonDelete _ =&gt; 
      Item.delete(item.id).map(a =&gt; a: JValue)
</pre>
</div>

</div>
<div class="Standard">
The only real difference is we’re looking for a <tt>JsonDelete</tt> HTTP request.
</div>
<div class="Standard">
Let’s see how we add an <tt>Item</tt> with a PUT:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: scala">    // PUT adds the item if the JSON is parsable
    case Nil JsonPut Item(item) -&gt; _ =&gt; Item.add(item): JValue
</pre>
</div>

</div>
<div class="Standard">
Note the <tt>Item(item) -&gt; _</tt> after <tt>JsonPut</tt>. The extraction signature for <tt>JsonPut</tt> is <tt>(List[String], (JValue, Req))</tt>. The <tt>List[String]</tt> part is simple... it’s a <tt>List</tt> that contains the request path. The second part of the Pair is a Pair itself that contains the <tt>JValue</tt> and the underlying <tt>Req</tt> (in case you need to do something with the request itself). Because there’s a <tt>def unapply(in: JValue): Option[Item]</tt> method in the <tt>Item</tt> singleton, we can extract (pattern match) the <tt>JValue</tt> that is built from the PUT request body. This means if the user PUTs a JSON blob that can be turned into an <tt>Item</tt> the pattern will match and we’ll evaluate the right hand side of the case statement which adds the <tt>Item</tt> to inventory. That’s a big ole dense pile of information. So, we’ll try it again with POST.
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: scala">    case Item(item) :: Nil JsonPost json -&gt; _ =&gt; 
      Item(mergeJson(item, json)).map(Item.add(_): JValue)
</pre>
</div>

</div>
<div class="Standard">
In this case, we’re match a POST on <tt>/api/item/1234</tt> that has some parsable JSON in the POST body. The <tt>mergeJson</tt> method takes all the fields in the found <tt>Item</tt> and replaces them with any of the fields in the JSON in the POST body. So a POST body of <tt>{&quot;qnty&quot;: 123}</tt> would replace the <tt>qnty</tt> field in the <tt>Item</tt>. The <tt>Item</tt> is then added back into the backing store.
</div>
<div class="Standard">
Cool. So, we’ve got a variety of GET support in our REST service, a DELETE, PUT and POST. All using the patterns that <tt>RestHelper</tt> gives us.
</div>
<div class="Standard">
Now we have some fun.
</div>
<div class="Standard">
One of the features of Lift’s HTML side is support for Comet (server push via long-polling.) If the web container supports it, Lift will automatically use asynchronous support. That means that during a long poll, while no computations are being performed related to the servicing of the request, no threads will be consumed. This allows lots and lots of open long polling clients. Lift’s REST support includes asynchronous support. In this case, we’ll demonstrate opening an HTTP request to <tt>/api/item/change</tt> and wait for a change to the backing store. The request will be satisfied with a change to the backing store or a JSON JNull after 110 seconds:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: scala">    case &quot;change&quot; :: Nil JsonGet _ =&gt;
      RestContinuation.async {
        satisfyRequest =&gt; {
          // schedule a &quot;Null&quot; return if there’s no other answer
          // after 110 seconds
          Schedule.schedule(() =&gt; satisfyRequest(JNull), 110 seconds)
​
          // register for an &quot;onChange&quot; event.  When it
          // fires, return the changed item as a response
          Item.onChange(item =&gt; satisfyRequest(item: JValue))
        }
      }
</pre>
</div>

</div>
<div class="Standard">
If we receive a GET request to <tt>/api/item/change</tt>, invoke <tt>RestContinuation.async</tt>. We pass a closure that sets up the call. We set up the call by scheduling a <tt>JNull</tt> to be sent after 110 seconds. We also register a function which is invoked when the backing store is changed. When either event (110 seconds elapses or the backing store changes), the functions will be invoked and they will apply the <tt>satifyRequest</tt> function which will invoke the continuation and send the response back to the client. Using this mechanism, you can create long polling services that do not consume threads on the server. Note too that the <tt>satisfyRequest</tt> function is fire-once so you can call it lots of times, but only the first time counts.
</div>
<h2 class="Section">
<a name="toc-Section-5.5" class="toc">5.5</a> Wrap Up
</h2>
<div class="Standard">
In this chapter, we’ve covered how you create web services in Lift. While there is a lot of implicit conversion stuff going on under the covers in <tt>RestHelper</tt>, the resulting code is pretty easy to read, create, and maintain. At the core, you match an incoming request against a pattern, if the pattern matches, evaluate the expression on the right hand side of the pattern.
</div>
<div class="Standard">

</div>
<h1 class="Chapter">
<a name="toc-Chapter-6" class="toc">6</a> Wiring
</h1>
<div class="Standard">
Interactive web applications have many interdependent components on a single web page. For example (and this is the example we’ll use for this chapter), you may have a shopping cart in your application. The shopping cart will contain items and quantities. As you add/remove items from the cart, the cart should update, along with the sub-total, the tax, the shipping and the grand total. Plus, the count of the items in the cart may be displayed on some pages without the cart contents. Keeping track of all of these dependencies for all the different page layouts is pretty tough work. When it comes to updating the site, the team must remember where all of the items are and how to update them and if they get one wrong, the site looks broken.
</div>
<div class="Standard">
Lift’s Wiring provides a simple solution to managing complex dependencies on a single page and on multiple tabs. Lift’s Wiring allows you to declare the formulaic relationships among cells (like a spreadsheet) and then the user interface components (yes, there can be more than one component) associated with each cell. Lift will automatically update the dependent user interface components based on change in the predicates. Lift will do this on initial page render and with each Ajax or Comet update to the page. Put another way, Wiring is like a spreadsheet and the page will automatically get updated when any of the predicate values change such that the change results in a change in the display value.
</div>
<h2 class="Section">
<a name="toc-Section-6.1" class="toc">6.1</a> Cells
</h2>
<div class="Standard">
Like a spreadsheet, Lift’s Wiring is based on Cells. Cells come in three types: <tt>ValueCell</tt>, <tt>DynamicCell</tt>, and <tt>FuncCell</tt>.
</div>
<div class="Standard">
A <tt>ValueCell</tt> contains a value that is entered by a user or depends on some user action. A <tt>ValueCell</tt> may represent the items in our shopping cart or the tax rate.
</div>
<div class="Standard">
A <tt>DynamicCell</tt> contains a value that changes every time the cell is accessed. For example, a random number or the current time.
</div>
<div class="Standard">
A <tt>FuncCell</tt> has a value based on a formula applied to the value or other cells.
</div>
<div class="Standard">
Let’s see some code that demonstrates this:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: scala">val quantity = ValueCell(0)
val price = ValueCell(1d)
val total = price.lift(_ * quantity)
</pre>
</div>

</div>
<div class="Standard">
We define two <tt>ValueCell</tt>s, one for <tt>quantity</tt> and the other for <tt>price</tt>. Next, define the <tt>total</tt> by “lifting” the <tt>price</tt> in a formula that multiplies it by <tt>quantity</tt>. Let’s see how it works in the console:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: scala">scala&gt; import net.liftweb._
import net.liftweb._
​
scala&gt; import util._
import util._
​
scala&gt; val quantity = ValueCell(0)
quantity: net.liftweb.util.ValueCell[Int] = ValueCell(0)
​
scala&gt; val price = ValueCell(0d)
price: net.liftweb.util.ValueCell[Double] = ValueCell(0.0)
​
scala&gt; val total = price.lift(_ * quantity)
total: net.liftweb.util.Cell[Double] = FuncCell1(ValueCell(0.0),&lt;function1&gt;)
​
scala&gt; total.get
res1: Double = 0.0
​
scala&gt; quantity.set(10)
res2: Int = 10
​
scala&gt; price.set(0.5d)
res3: Double = 0.5
​
scala&gt; total.get       
res4: Double = 5.0
</pre>
</div>

</div>
<div class="Standard">
Okay... pretty nifty... we can define relationships that are arbitrarily complex between <tt>Cell</tt>s and they know how to calculate themselves.
</div>
<h2 class="Section">
<a name="toc-Section-6.2" class="toc">6.2</a> Hooking it up to the UI
</h2>
<div class="Standard">
Now that we can declare relationships among cells, how do we associate the value of <tt>Cell</tt>s with the user interface?
</div>
<div class="Standard">
Turns out that it’s pretty simple:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: scala"> &quot;#total&quot; #&gt; WiringUI.asText(total)
</pre>
</div>

</div>
<div class="Standard">
We associate the element with <tt>id=&quot;total&quot;</tt> with a function that displays the value in <tt>total</tt>. Here’s the method definition:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: scala">  /**
   * Given a Cell register the
   * postPageJavaScript that will update the element with
   * a new value.
   *
   * @param cell the cell to associate with
   * 
   * @return a function that will mutate the NodeSeq (an id attribute may be added if
   * there’s none already defined)
   */
  def asText[T](cell: Cell[T]): NodeSeq =&gt; NodeSeq = 
</pre>
</div>

</div>
<div class="Standard">
Huh? that’s a lot of mumbo-jumbo... what’s a <tt>postPageJavaScript</tt>?
</div>
<div class="Standard">
So, here’s the magic of <tt>WiringUI</tt>: Most web frameworks treat a page rendering as an event in time. Maybe (in the case of Seaside), there are some side effects of rendering that close over page rendering state such that when forms are submitted back, you get page state back. Lift treats a full HTML page render and subsequent Ajax requests on the page as a single event that has a single scope. This means that <tt>RequestVar</tt>s populated during a page render are available during subsequent Ajax requests on that page. Part of the state that results in a page render is the <tt>postPageJavaScript</tt> which is a bucket of <tt>() =&gt; JsCmd</tt> or a collection of functions that return JavaScript. Before responding to any HTTP request associated with the page, Lift runs all these functions and appends the resulting JavaScript to the response sent back to the browser. HTTP requests associated with the page include the initial page render, subsequent Ajax request associated with the page and associated Comet (long poll) requests generated by the page.
</div>
<div class="Standard">
For each <tt>Cell</tt> that you wire up to the user interface, Lift captures the id of the DOM node (and if there’s no id, Lift will assign one) and the current value of the <tt>Cell</tt>. Lift generates a function that looks at the current <tt>Cell</tt> value and if it’s changed, Lift generates JavaScript that updates the DOM node with the <tt>Cell</tt>’s current value.
</div>
<div class="Standard">
The result is that if an Ajax operation changes the value of a <tt>ValueCell</tt>, then all the dependent cells will update and the associated DOM updates will be carried back with the HTTP response.
</div>
<div class="Standard">
You have a lot of control over the display of the value. The <tt>asText</tt> method creates a <tt>Text(cell.toString)</tt>. However, <tt>WiringUI.apply</tt> allows you to associate a function that converts the <tt>Cell</tt>’s type <tt>T</tt> to a <tt>NodeSeq</tt>. Further, you can control the transition in the browser with a <tt>jsEffect</tt> (type signiture <tt>(String, Boolean, JsCmd) =&gt; JsCmd</tt>). There are pre-build <tt>jsEffects</tt> based on jQuery including my favorite, <tt>fade</tt>:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: scala">  /**
   * Fade out the old value and fade in the new value
   * using jQuery fast fade.
   */
  def fade: (String, Boolean, JsCmd) =&gt; JsCmd = {
    (id: String, first: Boolean, cmd: JsCmd) =&gt; {
      if (first) cmd
      else {
        val sel = &quot;jQuery(’#’+&quot;+id.encJs+&quot;)&quot;
        Run(sel+&quot;.fadeOut(’fast’, function() {&quot;+
            cmd.toJsCmd+&quot; &quot;+sel+&quot;.fadeIn(’fast’);})&quot;)
      }
    }
  }
</pre>
</div>

</div>
<div class="Standard">
Which you can use as: 
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: scala"> &quot;#total&quot; #&gt; WiringUI.asText(total, JqWiringSupport.fade)
</pre>
</div>

</div>
<div class="Standard">
Now, when the total field updates, the old value will fade out and the new value will fade in... cool.
</div>
<h2 class="Section">
<a name="toc-Section-6.3" class="toc">6.3</a> Shared Shopping
</h2>
<div class="Standard">
Let’s move onto a real code example. You can find this code at <a href="https://github.com/dpp/simply_lift/tree/master/samples/shopwithme" class="URL">Shop with Me source</a>.
</div>
<div class="Standard">
The example is going to be a simple shopping site. There are a bunch of items that you can view. You have a shopping cart. You can add items to the cart. If you’re viewing the cart in multiple tabs or browser windows, the cart in all tabs/windows will update when you change the cart. Further, you can share your cart with someone else and any changes to the cart will be propagated to all the different browsers sharing the same cart.
</div>
<div class="Standard">
The data model is the same that we used in the REST chapter (see<a href="#item_model" class="Reference"> on page 1↓</a>).
</div>
<div class="Standard">
Let’s look at the shopping cart definition:
</div>
<div class="listing">
<div class="caption">
Cart.scala
</div>
<pre class="listing brush: scala">package code
package lib
​
import model.Item
​
import net.liftweb._
import util._
​
/**
 * The shopping cart
 */
class Cart {
  /**
   * The contents of the cart
   */
  val contents = ValueCell[Vector[CartItem]](Vector())
​
  /**
   * The subtotal
   */
  val subtotal = contents.lift(_.foldLeft(zero)(_ + 
                                                _.qMult(_.price)))
​
  /**
   * The taxable subtotal
   */
  val taxableSubtotal = contents.lift(_.filter(_.taxable).
                                      foldLeft(zero)(_ + 
                                                     _.qMult(_.price)))
​
  /**
   * The current tax rate
   */
  val taxRate = ValueCell(BigDecimal(&quot;0.07&quot;))
​
  /**
   * The computed tax
   */
  val tax = taxableSubtotal.lift(taxRate)(_ * _)
​
  /**
   * The total
   */
  val total = subtotal.lift(tax)(_ + _)
​
  /**
   * The weight of the cart
   */
  val weight = contents.lift(_.foldLeft(zero)(_ +
                                              _.qMult(_.weightInGrams)))
​
  // Helper methods
​
  /**
   * A nice constant zero
   */
  def zero = BigDecimal(0)
​
  /**
   * Add an item to the cart.  If it's already in the cart,
   * then increment the quantity
   */
  def addItem(item: Item) {
    contents.atomicUpdate(v =&gt; v.find(_.item == item) match {
      case Some(ci) =&gt; v.map(ci =&gt; ci.copy(qnty = ci.qnty + 
                                           (if (ci.item == item) 1 else 0)))
      case _ =&gt; v :+ CartItem(item, 1)
    })
  }
​
  /**
   * Set the item quantity.  If zero or negative, remove
   */
  def setItemCnt(item: Item, qnty: Int) {
    if (qnty &lt;= 0) removeItem(item)
    else contents.atomicUpdate(v =&gt; v.find(_.item == item) match {
      case Some(ci) =&gt; v.map(ci =&gt; ci.copy(qnty =
                                           (if (ci.item == item) qnty 
                                            else ci.qnty)))
      case _ =&gt; v :+ CartItem(item, qnty)
    })
​
  }
​
  /**
   * Removes an item from the cart
   */
  def removeItem(item: Item) {
    contents.atomicUpdate(_.filterNot(_.item == item))
  }
}
​
/**
 * An item in the cart
 */
case class CartItem(item: Item, qnty: Int, 
                    id: String = Helpers.nextFuncName) {
​
  /**
   * Multiply the quantity times some calculation on the
   * contained Item (e.g., getting its weight)
   */
  def qMult(f: Item =&gt; BigDecimal): BigDecimal = f(item) * qnty
}
​
/**
 * The CartItem companion object
 */
object CartItem {
  implicit def cartItemToItem(in: CartItem): Item = in.item
}
</pre>
</div>
<div class="Standard">
Looks pretty straight forward. You’ve got 2 <tt>ValueCell</tt>s, the cart contents and the tax rate. You’ve gota bunch of calculated <tt>Cell</tt>s. At the bottom of the <tt>Cart</tt> class definition are some helper methods that allow you to add, remove and update cart contents. We also define the <tt>CartItem</tt> case class that contains the <tt>Item</tt> and the <tt>qnty</tt> (quantity).
</div>
<div class="Standard">
So far, so good. Next, let’s look at the way we display all the items:
</div>
<div class="listing">
<div class="caption">
AllItemsPage.scala
</div>
<pre class="listing brush: scala">package code
package snippet
​
import model.Item
import comet._
​
import net.liftweb._
import http._
import sitemap._
import util._
import Helpers._
​
object AllItemsPage {
  // define the menu item for the page that
  // will display all items
  lazy val menu = Menu.i(&quot;Items&quot;) / &quot;item&quot; &gt;&gt;
  Loc.Snippet(&quot;Items&quot;, render)
  
  // display the items
  def render =
    &quot;tbody *&quot; #&gt; renderItems(Item.inventoryItems)
​
  // for a list of items, display those items
  def renderItems(in: Seq[Item]) =
    &quot;tr&quot; #&gt; in.map(item =&gt; {
      &quot;a *&quot; #&gt; item.name &amp;
      &quot;a [href]&quot; #&gt; AnItemPage.menu.calcHref(item) &amp;
      &quot;@description *&quot; #&gt; item.description &amp;
      &quot;@price *&quot; #&gt; item.price.toString &amp;
      &quot;@add_to_cart [onclick]&quot; #&gt;
      SHtml.ajaxInvoke(() =&gt; TheCart.addItem(item))})
}
​
</pre>
</div>
<div class="Standard">
We define our <tt>SiteMap</tt> entry:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: scala">  lazy val menu = Menu.i(&quot;Items&quot;) / &quot;item&quot; &gt;&gt;
    Loc.Snippet(&quot;Items&quot;, render)
</pre>
</div>

</div>
<div class="Standard">
So, when the user browses to <tt>/item</tt>, they’re presented with all the items in inventory. 
</div>
<div class="Standard">
The template for displaying <tt>Item</tt>s looks like:
</div>
<div class="listing">
<div class="caption">
items.html
</div>
<pre class="listing brush: xml">&lt;table class=&quot;lift:Items&quot;&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td name=&quot;name&quot;&gt;&lt;a href=&quot;#&quot;&gt;Name&lt;/a&gt;&lt;/td&gt;
      &lt;td name=&quot;description&quot;&gt;Desc&lt;/td&gt;
      &lt;td name=&quot;price&quot;&gt;$50.00&lt;/td&gt;
      &lt;td&gt;&lt;button name=&quot;add_to_cart&quot;&gt;Add to Cart&lt;/button&gt;&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;
</pre>
</div>
<div class="Standard">
Next, let’s look at the code for displaying an <tt>Item</tt>:
</div>
<div class="listing">
<div class="caption">
AnItemPage.scala
</div>
<pre class="listing brush: scala">package code
package snippet
​
import model.Item
import comet._
​
import net.liftweb._
import util._
import Helpers._
import http._
import sitemap._
​
import scala.xml.Text
​
object AnItemPage {
  // create a parameterized page
  def menu = Menu.param[Item](&quot;Item&quot;, Loc.LinkText(i =&gt; Text(i.name)),
                              Item.find _, _.id) / &quot;item&quot; / *
}
​
class AnItemPage(item: Item) {
  def render = &quot;@name *&quot; #&gt; item.name &amp;
  &quot;@description *&quot; #&gt; item.description &amp;
  &quot;@price *&quot; #&gt; item.price.toString &amp;
  &quot;@add_to_cart [onclick]&quot; #&gt; SHtml.ajaxInvoke(() =&gt; TheCart.addItem(item))
}
​
</pre>
</div>
<div class="Standard">
This defines what happens when the user goes to <tt>/item/1234</tt>. This is more “controller-like” than most of the other Lift code. Let’s look at the menu item definition:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: scala">  def menu = Menu.param[Item](&quot;Item&quot;, Loc.LinkText(i =&gt; Text(i.name)),
                              Item.find _, _.id) / &quot;item&quot; / *
</pre>
</div>

</div>
<div class="Standard">
We are defining a parameterized <tt>Menu</tt> entry. The parameter type is <tt>Item</tt>. That means that the page will display an <tt>Item</tt> and that we must be able to calculate the <tt>Item</tt> based on the request.
</div>
<div class="Standard">
<tt>&quot;Item&quot;</tt> is the name of the menu entry. 
</div>
<div class="Standard">
<tt>Loc.LinkText(i =&gt; Text(i.name))</tt> takes an item and generates the display text for the menu entry.
</div>
<div class="Standard">
<tt>Item.find _</tt> is a function that takes a <tt>String</tt> and converts it to <tt>Box[Item]</tt>. It looks up the Item based on the parameter in the request that we’re interested in.
</div>
<div class="Standard">
<tt>_.id</tt> is a function (<tt>Item =&gt; String</tt>) that takes an <tt>Item</tt> and returns a <tt>String</tt> that represents how to build a URL that represents the Item page. This is used by <tt>&quot;a [href]&quot; #&gt; AnItemPage.menu.calcHref(item)</tt> to convert an <tt>Item</tt> to the HREF for the page that display the <tt>Item</tt>.
</div>
<div class="Standard">
Finally, the URL is defined by <tt>/ &quot;item&quot; / *</tt> which is pretty much what it looks like. It’ll match an incoming request of the form <tt>/item/xxx</tt> and <tt>xxx</tt> is passed to the <tt>String =&gt; Box[Item]</tt> function to determine the <tt>Item</tt> associated with the URL.
</div>
<div class="Standard">
So, we can display all the items. Navigate from all the items to a single item. Each item has a button that allows you to add the <tt>Item</tt> to the shopping cart. The <tt>Item</tt> is added to the cart with this code: <tt>SHtml.ajaxInvoke(() =&gt; TheCart.addItem(item))})</tt>. The <tt>TheCart.addItem(item)</tt> can be called from anywhere in the application without regard for what needs to be updated when the cart is changed.
</div>
<div class="Standard">
Let’s look at how the cart is displayed and managed:
</div>
<div class="listing">
<div class="caption">
CometCart.scala
</div>
<pre class="listing brush: scala">package code
package comet
​
import lib._
​
import net.liftweb._
import common._
import http._
import util._
import js._
import js.jquery._
import JsCmds._
import scala.xml.NodeSeq
import Helpers._
​
/**
 * What's the current cart for this session
 */
object TheCart extends SessionVar(new Cart())
​
/**
 * The CometCart is the CometActor the represents the shopping cart
 */
class CometCart extends CometActor {
  // our current cart
  private var cart = TheCart.get
​
  /**
   * Draw yourself
   */
  def render = {
    &quot;#contents&quot; #&gt; (
      &quot;tbody&quot; #&gt; 
      Helpers.findOrCreateId(id =&gt;  // make sure tbody has an id
        // when the cart contents updates
        WiringUI.history(cart.contents) {
          (old, nw, ns) =&gt; {
            // capture the tr part of the template
            val theTR = (&quot;tr ^^&quot; #&gt; &quot;**&quot;)(ns)
            
            def ciToId(ci: CartItem): String = ci.id + &quot;_&quot; + ci.qnty
​
            // build a row out of a cart item
            def html(ci: CartItem): NodeSeq = {
              (&quot;tr [id]&quot; #&gt; ciToId(ci) &amp; 
               &quot;@name *&quot; #&gt; ci.name &amp;
               &quot;@qnty *&quot; #&gt; SHtml.
               ajaxText(ci.qnty.toString,
                        s =&gt; {
                          TheCart.
                          setItemCnt(ci, 
                                     Helpers.toInt(s))
                        }, &quot;style&quot; -&gt; &quot;width: 20px;&quot;) &amp;
               &quot;@del [onclick]&quot; #&gt; SHtml.
             ajaxInvoke(() =&gt; TheCart.removeItem(ci)))(theTR)
            }
            
            // calculate the delta between the lists and
            // based on the deltas, emit the current jQuery
            // stuff to update the display
            JqWiringSupport.calculateDeltas(old, nw, id)(ciToId _, html _)
          }
        })) &amp;
    &quot;#subtotal&quot; #&gt; WiringUI.asText(cart.subtotal) &amp; // display the subttotal
    &quot;#tax&quot; #&gt; WiringUI.asText(cart.tax) &amp; // display the tax
    &quot;#total&quot; #&gt; WiringUI.asText(cart.total) // display the total
  }
   
  /**
   * Process messages from external sources
   */
  override def lowPriority = {
    // if someone sends us a new cart
    case SetNewCart(newCart) =&gt; {
      // unregister from the old cart
      unregisterFromAllDepenencies()
​
      // remove all the dependencies for the old cart
      // from the postPageJavaScript
      theSession.clearPostPageJavaScriptForThisPage()
​
      // set the new cart
      cart = newCart
​
      // do a full reRender including the fixed render piece
      reRender(true)
    }
  }
}
​
/**
 * Set a new cart for the CometCart
 */
case class SetNewCart(cart: Cart)
</pre>
</div>
<div class="Standard">
Let’s walk through the code:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: scala">object TheCart extends SessionVar(new Cart())
</pre>
</div>

</div>
<div class="Standard">
We define a <tt>SessionVar</tt> that holds the shopping cart.
</div>
<div class="Standard">
Our <tt>CometActor</tt> captures the the current cart from the <tt>SessionVar</tt>:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: scala">class CometCart extends CometActor {
  // our current cart
  private var cart = TheCart.get
</pre>
</div>

</div>
<div class="Standard">
Next, let’s see how to draw the <tt>cart.total</tt>:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: scala">&quot;#total&quot; #&gt; WiringUI.asText(cart.total) // display the total
</pre>
</div>

</div>
<div class="Standard">
That’s pretty much the way it should be.
</div>
<div class="Standard">
Let’s look at the gnarly piece... how to draw or redraw the cart contents based on changes and only send the JavaScript the will manipulate the browser DOM to add or remove items from the cart:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: scala">&quot;#contents&quot; #&gt; (
      &quot;tbody&quot; #&gt; 
      Helpers.findOrCreateId(id =&gt;  // make sure tbody has an id
        // when the cart contents updates
        WiringUI.history(cart.contents) {
          (old, nw, ns) =&gt; {
            // capture the tr part of the template
            val theTR = (&quot;tr ^^&quot; #&gt; &quot;**&quot;)(ns)
            
            def ciToId(ci: CartItem): String = ci.id + &quot;_&quot; + ci.qnty
​
            // build a row out of a cart item
            def html(ci: CartItem): NodeSeq = {
              (&quot;tr [id]&quot; #&gt; ciToId(ci) &amp; 
               &quot;@name *&quot; #&gt; ci.name &amp;
               &quot;@qnty *&quot; #&gt; SHtml.
               ajaxText(ci.qnty.toString,
                        s =&gt; {
                          TheCart.
                          setItemCnt(ci, 
                                     Helpers.toInt(s))
                        }, &quot;style&quot; -&gt; &quot;width: 20px;&quot;) &amp;
               &quot;@del [onclick]&quot; #&gt; SHtml.
             ajaxInvoke(() =&gt; TheCart.removeItem(ci)))(theTR)
            }
            
            // calculate the delta between the lists and
            // based on the deltas, emit the current jQuery
            // stuff to update the display
            JqWiringSupport.calculateDeltas(old, nw, id)(ciToId _, html _)
          }
        }))
</pre>
</div>

</div>
<div class="Standard">
First, we make sure we know the <tt>id</tt> of the <tt>&lt;tbody&gt;</tt> element: <tt>&quot;tbody&quot; #&gt; Helpers.findOrCreateId(id =&gt;</tt>
</div>
<div class="Standard">
Next, wire the <tt>CometCart</tt> up to the <tt>cart.contents</tt> such that when the contents change, we get the old value (<tt>old</tt>), the new value (<tt>nw</tt>) and the memoized <tt>NodeSeq</tt> (the template used to do the rendering): <tt>WiringUI.history(cart.contents) { (old, nw, ns) =&gt; {</tt>
</div>
<div class="Standard">
Capture the part of the template associated with the <tt>&lt;tr&gt;</tt> element in the <tt>theTR</tt> variable: <tt>val theTR = (&quot;tr ^^&quot; #&gt; &quot;**&quot;)(ns)</tt>
</div>
<div class="Standard">
Based on a <tt>CartItem</tt>, return a stable id for the DOM node the represents the <tt>CartItem</tt>: 
</div>
<div class="Standard">
The <tt>html</tt> method converts a <tt>CartItem</tt> to a <tt>NodeSeq</tt> including Ajax controls for changing quantity and removing the item from the cart.
</div>
<div class="Standard">
Finally, based on the deltas between the old list of <tt>CartItem</tt> and the new list, generate the JavaScript that will manipulate the DOM by inserting and removing the appropriate DOM elements: <tt>JqWiringSupport.calculateDeltas(old, nw, id)(ciToId _, html _)</tt>
</div>
<div class="Standard">
Next, let’s see how to change the cart. If we want to share the shopping cart between two browser sessions... two people shopping at their browser, but putting things in a single cart, we need a way to change the cart. We process the <tt>SetNewCart</tt> message to <tt>CometCart</tt>:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: scala">    // if someone sends us a new cart
    case SetNewCart(newCart) =&gt; {
      // unregister from the old cart
      unregisterFromAllDepenencies()
​
      // remove all the dependencies for the old cart
      // from the postPageJavaScript
      theSession.clearPostPageJavaScriptForThisPage()
​
      // set the new cart
      cart = newCart
​
      // do a full reRender including the fixed render piece
      reRender(true)
    }
</pre>
</div>

</div>
<div class="Standard">
There are two lines in the above code that hint at how Wiring interacts with Lift’s Comet support: <tt>unregisterFromAllDepenencies()</tt> and <tt>theSession.clearPostPageJavaScriptForThisPage()</tt>
</div>
<div class="Standard">
When a <tt>CometActor</tt> depends on something in <tt>WiringUI</tt>, Lift generates a weak reference between the <tt>Cell</tt> and the <tt>CometActor</tt>. When the <tt>Cell</tt> changes value, it pokes the <tt>CometActor</tt>. The <tt>CometActor</tt> then updates the browser’s screen real estate associated with changes to <tt>Cell</tt>s. <tt>unregisterFromAllDepenencies()</tt> disconnects the <tt>CometActor</tt> from the <tt>Cell</tt>s. <tt>theSession.clearPostPageJavaScriptForThisPage()</tt> removes all the <tt>postPageJavaScript</tt> associated with the <tt>CometActor</tt>. Because the <tt>CometActor</tt> is not associated with a single page, but can appear on many pages, it has its own <tt>postPageJavaScript</tt> context.
</div>
<div class="Standard">
The final piece of the puzzle is how we share a <tt>Cart</tt> across sessions. From the UI perspective, here’s how we display the modal dialog when the user presses the “Share Cart” button:
</div>
<div class="listing">
<div class="caption">
Link.scala
</div>
<pre class="listing brush: scala">package code
package snippet
​
import model._
import comet._
import lib._
​
import net.liftweb._
import http._
import util.Helpers._
import js._
import JsCmds._
import js.jquery.JqJsCmds._
​
class Link {
  // open a modal dialog based on the _share_link.html template
  def request = &quot;* [onclick]&quot; #&gt; SHtml.ajaxInvoke(() =&gt; {
    (for {
      template &lt;- TemplateFinder.findAnyTemplate(List(&quot;_share_link&quot;))
    } yield ModalDialog(template)) openOr Noop
      
  })
​
  // close the modal dialog
  def close = &quot;* [onclick]&quot; #&gt; SHtml.ajaxInvoke(() =&gt; Unblock)
​
  // Generate the href and link for sharing
  def generate = {
    val s = ShareCart.generateLink(TheCart)
    &quot;a [href]&quot; #&gt; s &amp; &quot;a *&quot; #&gt; s
  }
}
</pre>
</div>
<div class="Standard">
Basically, we use jQuery’s ModalDialog plugin to put a dialog up that contains a link generated by the <tt>ShareCart</tt> object. Let’s look at ShareCart.scala:
</div>
<div class="listing">
<div class="caption">
ShareCart.scala
</div>
<pre class="listing brush: scala">package code
package lib
​
import comet._
​
import net.liftweb._
import common._
import http._
import rest.RestHelper
import util._
import Helpers._
​
// it's a RestHelper
object ShareCart extends RestHelper {
  // private state
  private var carts: Map[String, (Long, Cart)] = Map()
​
  // given a Cart, generate a unique sharing code
  def codeForCart(cart: Cart): String = synchronized {
    val ret = Helpers.randomString(12)
​
    carts += ret -&gt; (10.minutes.later.millis -&gt; cart)
​
    ret
  }
​
  /**
   * Generate the right link to this cart
   */
  def generateLink(cart: Cart): String = {
    S.hostAndPath + &quot;/co_shop/&quot;+codeForCart(cart)
  }
​
  // An extractor that converts a String to a Cart, if
  // possible
  def unapply(code: String): Option[Cart] = synchronized {
    carts.get(code).map(_._2)
  }
​
  // remove any carts that are 10+ minutes old
  private def cleanup() {
    val now = Helpers.millis
    synchronized{
      carts = carts.filter{
        case (_, (time, _)) =&gt; time &gt; now
      }
    }
    Schedule.schedule(() =&gt; cleanup(), 5 seconds)
  }
  
  // clean up every 5 seconds
  cleanup()
​
  // the REST part of the code
  serve {
    // match the incoming URL
    case &quot;co_shop&quot; :: ShareCart(cart) :: Nil Get _ =&gt; {
      // set the cart
      TheCart.set(cart)
      
      // send the SetNewCart message to the CometCart
      S.session.foreach(
        _.sendCometActorMessage(&quot;CometCart&quot;, Empty,
                                SetNewCart(cart)))
​
      // redirect the browser to /
      RedirectResponse(&quot;/&quot;)
    }
  }
}
</pre>
</div>
<div class="Standard">
The code manages the association between random IDs and <tt>Cart</tt>s. If the user browses to <tt>/co_shop/share_cart_id</tt>, <tt>ShareCart</tt> will set <tt>TheCart</tt> to the shared <tt>Cart</tt> and send a <tt>SetNewCart</tt> message to the <tt>CometCart</tt> instance associated with the session.
</div>
<h2 class="Section">
<a name="toc-Section-6.4" class="toc">6.4</a> Wrap up
</h2>
<div class="Standard">
In this chapter we’ve seen how Lift’s Wiring can be used to create complex inter-relationships among values and then surface those relationships in the web user interface. Wiring can be used with Ajax or Comet. Wiring makes it simple to build complex web pages that are user friendly and easy to maintain.
</div>
<h1 class="Chapter">
<a name="toc-Chapter-7" class="toc">7</a> Core Concepts
</h1>
<div class="Standard">

</div>
<h2 class="Section">
<a name="toc-Section-7.1" class="toc">7.1</a> Snippets<a name="sec:Snippets" class="Label"> </a>
</h2>
<div class="Standard">
Lift is built on the Scala programming language. Scala is a hybrid of Functional and Object Oriented. Two core principles of functional programming languages are immutability and transformation.
</div>
<div class="Standard">
Immutability means that once a data structure is instantiated, it will not change for its life. More concretely, once you instantiate an object, you can freely pass the object around and the object will always return the same values for all its methods. Java’s <tt>String</tt> class is immutable. Python requires immutable classes as indexes to dictionaries. Immutability is also very powerful for multithreaded applications because you can pass references to immutable objects across thread boundaries without having to worry about locking or synchronization because you are guaranteed that the objects will not change state.
</div>
<h3 class="Subsection">
<a name="toc-Subsection-7.1.1" class="toc">7.1.1</a> Snippet <tt>NodeSeq =&gt; NodeSeq</tt>
</h3>
<div class="Standard">
Transformation provides an alternative to “writing to a stream” for composing web pages. Rather than having tags that cause characters to be streamed as part of the response, Lift loads the view and for each “snippet” encountered in the view, Lift transforms just the markup associated with the snippet invocation into a new set of HTML.
</div>
<div class="Standard">
Let’s make it more concrete, here’s some markup:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: xml">&lt;span class=&quot;foo lift:WhatTime&quot;&gt;The time is &lt;span id=&quot;current_time&quot;&gt;currentTime&lt;/span&gt;&lt;/span&gt;
</pre>
</div>

</div>
<div class="Standard">
And the associated snippet:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: scala">object WhatTime {
  def render = &quot;#current_time&quot; #&gt; (new Date).toString
}
</pre>
</div>

</div>
<div class="Standard">
The resulting markup will look like:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: xml">&lt;span class=&quot;foo&quot;&gt;The time is Mon Dec 06 21:01:36 PST 2010&lt;/span&gt;
</pre>
</div>

</div>
<div class="Standard">
Let’s walk through how this works. First, the class attribute in the <tt>&lt;span&gt;</tt> has two classes, <tt>foo</tt> and <tt>lift:WhatTime</tt>. Any class attribute that starts with <tt>lift:</tt> indicates a snippet invocation. A snippet is a function that transforms HTML to HTML, or in Scala, <tt>NodeSeq =&gt; NodeSeq</tt>.
</div>
<div class="Standard">
Lift looks up the snippet named <tt>WhatTime</tt> (See <a href="#sec:Snippet-Resolution" class="Reference">↓</a>) which in this case resolves to a singleton and invokes the <tt>render</tt> method. The render method returns a <tt>NodeSeq =&gt; NodeSeq</tt> built using Lift’s CSS Selector Transforms (See <a href="#sec:CSS-Selector-Transforms" class="Reference">↓</a>). The parameter to the function is the <tt>Element</tt> that caused the snippet invocation with the actual snippet invocation removed from the <tt>class</tt> attribute: 
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: xml">&lt;span class=&quot;foo&quot;&gt;The time is &lt;span id=&quot;current_time&quot;&gt;currentTime&lt;/span&gt;&lt;/span&gt;
</pre>
</div>

</div>
<div class="Standard">
The function is then applied and the resulting <tt>NodeSeq</tt> is inserted in the page where the original <tt>Element</tt> was. Because the page is composed of immutable XML objects, we can transform <tt>NodeSeq =&gt; NodeSeq</tt> and not worry about anything getting changed out from under us. We also know that we’ve got valid markup through the entire page transformation process.
</div>
<div class="Standard">
Further, retaining the page as a well formed XML document allows certain tags to be put in the <tt>&lt;head&gt;</tt> tag and other tags to be inserted just before the close of the <tt>&lt;/body&gt;</tt> tag (See <a href="#sec:Page-rewriting" class="Reference">↓</a>).
</div>
<div class="Standard">
But the simplicity of the transform is simulateously easy to understand and very powerful.
</div>
<h3 class="Subsection">
<a name="toc-Subsection-7.1.2" class="toc">7.1.2</a> Snippet instances
</h3>
<div class="Standard">
The snippet could also be defined as:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: scala">class WhatTime {
  private var x = 0
​
  def render = {
    x += 1
    &quot;#current_time&quot; #&gt; ((new Date).toString + &quot; and you’ve seen this message &quot;+x+&quot; times)
  }
}
</pre>
</div>

</div>
<h3 class="Subsection">
<a name="toc-Subsection-7.1.3" class="toc">7.1.3</a> Multiple methods on a snippet class
</h3>
<h3 class="Subsection">
<a name="toc-Subsection-7.1.4" class="toc">7.1.4</a> Inter-snippet communication
</h3>
<h3 class="Subsection">
<a name="toc-Subsection-7.1.5" class="toc">7.1.5</a> Recursive Snippets
</h3>
<h3 class="Subsection">
<a name="toc-Subsection-7.1.6" class="toc">7.1.6</a> Snippet parameters
</h3>
<h2 class="Section">
<a name="toc-Section-7.2" class="toc">7.2</a> Box/Option<a name="sec:Box/Option" class="Label"> </a>
</h2>
<div class="Standard">
Scala has a ton of nice features. One of the features that I was slow to adopt, until Burak Emir gently reminded me a bunch of times, is &quot;Options&quot;. Read on about Options, Boxes, and how Lift makes good use of them to make clean, error resistant code. If you come from an imperative (Java, Ruby) background, you’ll probably recognize the following code:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: scala">x = someOperation 
if !x.nil? 
  y = someOtherOperation 
  if !y.nil? 
    doSomething(x,y) return &quot;it worked&quot; 
  end
end
return &quot;it failed&quot; 
</pre>
</div>

</div>
<div class="Standard">
Okay, so that’s pseudo-code, but there are tons of operation, guard, operation, guard, blah blah constructs.
</div>
<div class="Standard">
Further, null/nil are passed around as failures. This is especially bad when it’s null, but it’s pretty bad when it’s nil because it’s not clear to the consumer of the API that there can be a &quot;call failed&quot; return value.
</div>
<div class="Standard">
In Java, <tt>null</tt> is a non-object. It has no methods. It is the exception to the statically typed rule (<tt>null</tt> has no class, but any reference of any class can be set to <tt>null</tt>.) Invoking a method on <tt>null</tt> has one and only one result: an exception is thrown. <tt>null</tt> is often returned from methods as a flag indicating that the method ran successfully, but yielded no meaningful value. For example, <tt>CardHolder.findByCreditCardNumber(&quot;2222222222&quot;)</tt> In fact, the guy who invented <tt>null</tt> called it a <a href="http://www.infoq.com/presentations/Null-References-The-Billion-Dollar-Mistake-Tony-Hoare" class="URL">billion dollar mistake</a>.
</div>
<div class="Standard">
Ruby has <tt>nil</tt> which is marginally better than <tt>null</tt>. <tt>nil</tt> is a real, singleton object. There’s only one instance of <tt>nil</tt> in the whole system. It has methods. It is a subclass of <tt>Object</tt>. <tt>Object</tt> has a method called &quot;<tt>nil?</tt>&quot; which returns <tt>false</tt>, except the <tt>nil</tt> singleton overrides this method to return <tt>true</tt>. <tt>nil</tt> is returned much like <tt>null</tt> in Java. It’s the &quot;no valid answer&quot; answer.
</div>
<div class="Standard">
Scala does something different.
</div>
<div class="Standard">
There’s an abstract class, called <tt>Option</tt>. Options are strongly typed. They are declared <tt>Option[T]</tt>. This means an <tt>Option</tt> can be of any type, but once its type is defined, it does not change. There are two subclasses of <tt>Option</tt>: <tt>Some</tt> and <tt>None</tt>. <tt>None</tt> is a singleton (like <tt>nil</tt>). <tt>Some</tt> is a container around the actual answer. So, you might have a method that looks like:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: scala">def findUser(name: String): Option[User] = { 
  val query = buildQuery(name)
  val resultSet = performQuery(query)
  val retVal = if (resultSet.next) Some(createUser(resultSet)) else None
  resultSet.close 
  retVal 
} 
</pre>
</div>
 
</div>
<div class="Standard">
Some, you’ve got a <tt>findUser</tt> method that returns either <tt>Some(User)</tt> or <tt>None</tt>. So far, it doesn’t look a lot different than our example above. So, to confuse everyone, I’m going to talk about collections for a minute.
</div>
<div class="Standard">
A really nice thing in Scala (yes, Ruby has this too) is rich list operations. Rather than creating a counter and pulling list (array) elements out one by one, you write a little function and pass that function to the list. The list calls the function with each element and returns a new list with the values returned from each call. It’s easier to see it in code:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: scala">scala&gt; List(1,2,3).map(x =&gt; x * 2)
line0: scala.List[scala.Int] = List(2,4,6)
</pre>
</div>

</div>
<div class="Standard">
The above code multiplies each list item by two and &quot;map&quot; returns the resulting list. Oh, and you can be more terse, if you want:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: scala">scala&gt; List(1,2,3).map(_ * 2)
line2: scala.List[scala.Int] = List(2,4,6)
</pre>
</div>
You can nest map operations:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: scala">scala&gt; List(1,2,3).map(x =&gt; List(4,5,6).map(y =&gt; x * y))
line13: scala.List[scala.List[scala.Int]] = List(List(4,5,6),List(8,10,12),List(12,15,18))
</pre>
</div>

</div>
<div class="Standard">
And, you can &quot;flatten&quot; the inner list:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: scala">scala&gt; List(1,2,3).flatMap(x =&gt; List(4,5,6).map(y =&gt; x * y))
line14: scala.List[scala.Int] = List(4,5,6,8,10,12,12,15,18)
</pre>
</div>
Finally, you can &quot;filter&quot; only the even numbers from the first list:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: scala">scala&gt; List(1,2,3).filter(_ % 2 == 0). flatMap(x =&gt; List(4,5,6).map(y =&gt; x * y))
line16: scala.List[scala.Int] = List(8,10,12)
</pre>
</div>
But, as you can see, the <tt>map</tt>/<tt>flatMap</tt>/<tt>filter</tt> stuff gets pretty verbose. Scala introduced a &quot;for&quot; comprehension to make the code more readable:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: scala">scala&gt; for {
  x &lt;- List(1,2,3) if x % 2 == 0
  y &lt;- List(4,5,6)} yield x * y
res0: List[Int] = List(8, 10, 12)
</pre>
</div>
 
</div>
<div class="Standard">
Okay, but what does this have to do with <tt>Option[T]</tt>?
</div>
<div class="Standard">
Turns out that <tt>Option</tt> implements <tt>map</tt>, <tt>flatMap</tt>, and <tt>filter</tt> (the methods necessary for the Scala compiler to use in the ’for’ comprehension). Just as a side note, when I first encountered the phrase &quot;’for’ comprehension&quot;, I got scared. I’ve been doing programming for years and never heard of a &quot;comprenhension&quot; let alone a ’for’ one. Turns out, that there’s nothing fancy going on, but &quot;’for’ comprehension&quot; is just a term of art for the above construct.
</div>
<div class="Standard">
So, the cool thing is that you can use this construct very effectively. The first example is simple:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: scala">scala&gt; for {x &lt;- Some(3); y &lt;- Some(4)} yield x * y
res1: Option[Int] = Some(12)
</pre>
</div>
 
</div>
<div class="Standard">
&quot;That’s nice, you just wrote a lot of code to multiply 3 by 4.&quot;
</div>
<div class="Standard">
Let’s see what happens if we have a &quot;None&quot; in there:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: scala">scala&gt; val yOpt: Option[Int] = None
yOpt: Option[Int] = None 
scala&gt; for {x &lt;- Some(3); y &lt;- yOpt} yield x * y
res3: Option[Int] = None
</pre>
</div>

</div>
<div class="Standard">
So, we get a &quot;<tt>None</tt>&quot; back. How do we turn this into a default value?
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: scala">scala&gt; (for {x &lt;- Some(3); y &lt;- yOpt} yield x * y) getOrElse -1
res4: Int = -1
</pre>
</div>
 
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: scala">scala&gt; (for {x &lt;- Some(3); y &lt;- Some(4)} yield x * y) getOrElse -1
res5: Int = 12
</pre>
</div>

</div>
<div class="Standard">
Note that the &quot;<tt>getOrElse</tt>&quot; code is &quot;passed by name&quot;. Put another way, that code is only executed if the &quot;else&quot; clause is valid.
</div>
<div class="Standard">
Lift has an analogous construct called <tt>Box</tt>.
</div>
<div class="Standard">
A <tt>Box</tt> can be <tt>Full</tt> or not. A non-<tt>Full</tt> <tt>Box</tt> can be the <tt>Empty</tt> singleton or a <tt>Failure</tt>. A <tt>Failure</tt> carries around information about why the <tt>Box</tt> contains no value.
</div>
<div class="Standard">
<tt>Failure</tt> is very helpful because you can carry around information to display an error... an HTTP response code, a message, what have you.
</div>
<div class="Standard">
In Lift, I put this all together in the following way:
</div>
<ul>
<li>
methods that return request parameters return <tt>Box[String]</tt> 
</li>
<li>
finder methods on models (not find all, just the ones that return a single instance) return <tt>Box[Model]</tt>
</li>
<li>
any method that would have returned a null if I was writing in Java returns a <tt>Box[T]</tt> in Lift 
</li>

</ul>
<div class="Standard">
That means you get code that looks like:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: scala">scala&gt; for {id &lt;- S.param(&quot;id&quot;) ?~ &quot;id param missing&quot;
u &lt;- getUser(id) ?~ &quot;User not found&quot; 
} yield u.toXml 
res6: net.liftweb.common.Box[scala.xml.Elem] = Failure(id param missing,Empty,Empty) 
</pre>
</div>

</div>
<div class="Standard">
There’s no explicit guard/test to see if the &quot;<tt>id</tt>&quot; parameter was passed in and there’s no explicit test to see if the user was found.
</div>
<div class="Standard">
Note also that this code is completely type-safe. While there was no explicit type declarations, the compiler was able to figure out what types the various objects were.
</div>
<div class="Standard">
So, let’s look at the code inside a REST handler:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: scala">serve { 
  case &quot;user&quot; :: &quot;info&quot; :: _ XmlGet _ =&gt; 
    for {
      id &lt;- S.param(&quot;id&quot;) ?~ &quot;id param missing&quot; ~&gt; 401 
      u &lt;- User.find(id) ?~ &quot;User not found&quot; 
    } yield u.toXml 
}
</pre>
</div>

</div>
<div class="Standard">
If the <tt>id</tt> parameter is missing, present a nice error message and return a 401 (okay... this is random, but you get the point). And by default, if the user isn’t found, return a 404 with the error that the user isn’t found.
</div>
<div class="Standard">
Here’s what it looks like using wget:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: bash">dpp@bison:~/lift_sbt_prototype$ wget http://localhost:8080/user/info.xml
--2010-06-01 15:07:27-- http://localhost:8080/user/info.xml
Resolving localhost... ::1, 127.0.0.1 
Connecting to localhost|::1|:8080... connected. 
HTTP request sent, awaiting response... 401 Unauthorized 
Authorization failed.
​
dpp@bison:~/lift_sbt_prototype$ wget http://localhost:8080/user/info.xml?id=2
--2010-06-01 15:07:44-- http://localhost:8080/user/info.xml?id=2
Resolving localhost... ::1, 127.0.0.1
Connecting to localhost|::1|:8080... connected. 
HTTP request sent, awaiting response... 404 Not Found 
2010-06-01 15:07:44 ERROR 404: Not Found.
​
dpp@bison:~/lift_sbt_prototype$ wget http://localhost:8080/user/info.xml?id=1
--2010-06-01 15:24:12-- http://localhost:8080/user/info.xml?id=1
Resolving localhost... ::1, 127.0.0.1
Connecting to localhost|::1|:8080... connected. 
HTTP request sent, awaiting response... 
200 OK Length: 274 [text/xml] Saving to: ‘info.xml?id=1’
​
dpp@bison:~/lift_sbt_prototype$ cat info.xml\?id\=1
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
  &lt;User id=&quot;1&quot; firstName=&quot;Elwood&quot; ... validated=&quot;true&quot; superUser=&quot;false&quot;&gt;
&lt;/User&gt; 
</pre>
</div>

</div>
<div class="Standard">
One more thing about <tt>Box</tt> and <tt>Option</tt>... they lead to less complex, more maintainable code. Even if you didn’t know anything about Scala or Lift, you can read the XML serving code and the console exchange and figure out what happened any why it happened. This is a lot more readable than deeply nested if statements. And if it’s readable, it’s maintainable.
</div>
<div class="Standard">
I hope this is an understandable introduction to Scala’s <tt>Option</tt> class and ’for’ comprehension and how Lift makes use of these tools.
</div>
<h2 class="Section">
<a name="toc-Section-7.3" class="toc">7.3</a> S/SHtml<a name="sec:S/SHtml" class="Label"> </a>
</h2>
<h2 class="Section">
<a name="toc-Section-7.4" class="toc">7.4</a> Boot<a name="sec:Boot" class="Label"> </a>
</h2>
<h2 class="Section">
<a name="toc-Section-7.5" class="toc">7.5</a> SiteMap<a name="sec:SiteMap" class="Label"> </a>
</h2>
<h2 class="Section">
<a name="toc-Section-7.6" class="toc">7.6</a> GUIDs<a name="sec:GUIDs" class="Label"> </a>
</h2>
<div class="Standard">
A core concept in Lift is GUIDs. GUIDs are globally unique identifiers used to associate something in the browser with a function on the server. GUIDs make Lift more secure because they make replay attacks very difficult and GUIDs make it easier to develop complex, stateful, interactive applications because the developer spends more time on business logic and less time on the plumbing of it.
</div>
<h3 class="Subsection">
<a name="toc-Subsection-7.6.1" class="toc">7.6.1</a> How GUIDs are generated
</h3>
<h3 class="Subsection">
<a name="toc-Subsection-7.6.2" class="toc">7.6.2</a> Where they are used 
</h3>
<h2 class="Section">
<a name="toc-Section-7.7" class="toc">7.7</a> LiftRules<a name="sec:LiftRules" class="Label"> </a>
</h2>
<h2 class="Section">
<a name="toc-Section-7.8" class="toc">7.8</a> SessionVars and RequestVars<a name="sec:SessionVars-and-RequestVars" class="Label"> </a>
</h2>
<h2 class="Section">
<a name="toc-Section-7.9" class="toc">7.9</a> Helpers<a name="sec:Helpers" class="Label"> </a>
</h2>
<div class="Standard">

</div>
<h2 class="Section">
<a name="toc-Section-7.10" class="toc">7.10</a> CSS Selector Transforms<a name="sec:CSS-Selector-Transforms" class="Label"> </a>
</h2>
<div class="Standard">
Lift 2.2-M1 introduced a new mechanism for transforming XHTML: CSS Selector Transforms (<tt>CssBindFunc</tt>). The new mechanism provides a subset of CSS selectors that can be used to transform <tt>NodeSeq =&gt; NodeSeq</tt>. Examples of this feature include:
</div>
<ul>
<li>
<tt>&quot;#name&quot; #&gt; userName</tt> // replace the element with the id name with the variable userName 
</li>
<li>
<tt>&quot;#chat_lines *&quot; #&gt; listOfChats</tt> // replace the content of chat_lines with each element of listOfChats 
</li>
<li>
<tt>&quot;.pretty *&quot; #&gt; &lt;b&gt;Unicorn&lt;/b&gt;</tt> // each element with CSS class pretty, replace content with &lt;b&gt;Unicorn&lt;/b&gt;
</li>
<li>
<tt>&quot;dog=cat [href]&quot; #&gt; &quot;http://dogscape.com&quot;</tt> // set the href attribute of all elements with the dog attribute set to cat 
</li>
<li>
<tt>&quot;#name&quot; #&gt; userName &amp; &quot;#age&quot; #&gt; userAge</tt> // set name to userName and age to userAge
</li>
<li>
<tt>&quot;li *&quot; #&gt; userName &amp; &quot;li [class]&quot; #&gt; &quot;foo&quot;</tt> // set the contents of all &lt;li&gt; element with username and class to foo
</li>
<li>
<tt>&quot;li *&quot; #&gt; userName &amp; &quot;li [class+]&quot; #&gt; &quot;foo&quot;</tt> // set the contents of all &lt;li&gt; element with username and append foo to the class
</li>
<li>
<tt>&quot;*&quot; #&gt; &lt;span&gt;{userName}&lt;/span&gt;</tt> // set all the elements to &lt;span&gt;{userName}&lt;/span&gt;
</li>

</ul>
<div class="Standard">
CSS Selector Transforms extends <tt>NodeSeq =&gt; NodeSeq</tt>... they are quite literally functions and can be passes as a parameter to anything expecting <tt>NodeSeq =&gt; NodeSeq</tt> or returned as a result for any method that returns <tt>NodeSeq =&gt; NodeSeq</tt>.
</div>
<div class="Standard">
Let’s look at each of the pieces to see how they work.
</div>
<div class="Standard">
First, you must <tt>import net.liftweb.util._</tt> and <tt>import Helpers._</tt> These packages include the classes and the implicit conversions that make the CSS Selector Tranforms work.
</div>
<div class="Standard">
The transform is defined by: String representing selector #&gt; transform value.
</div>
<div class="Standard">
The selector is a String constant which implements the following subset of CSS Selectors:
</div>
<ul>
<li>
<tt>#id</tt> - selects the element with the specified id 
</li>
<li>
<tt>.class</tt> - selects all elements have a class attribute where one of the space-separated values equals class 
</li>
<li>
<tt>attr_name=attr_value</tt> - selects all elements where the given attribute equals the given value
</li>
<li>
<tt>element_name</tt> - selects all the elements matching the name
</li>
<li>
<tt>*</tt> - selects all elements
</li>
<li>
<tt>@name</tt> - selects all elements with <tt>the specified name</tt>
</li>
<li>
<tt>:button</tt> - selects all the elements with <tt>type=&quot;button&quot;</tt>
</li>
<li>
<tt>:checkbox</tt> - selects all the elements with <tt>type=&quot;checkbox&quot;</tt>
</li>
<li>
<tt>:file</tt> - selects all the elements with <tt>type=&quot;file&quot;</tt>
</li>
<li>
<tt>:password</tt> - selects all the elements with <tt>type=&quot;password&quot;</tt>
</li>
<li>
<tt>:radio</tt> - selects all the elements with <tt>type=&quot;radio&quot;</tt>
</li>
<li>
<tt>:reset</tt> - selects all the elements with <tt>type=&quot;reset&quot;</tt>
</li>
<li>
<tt>:submit</tt> - selects all the elements with <tt>type=&quot;submit&quot;</tt>
</li>
<li>
<tt>:text</tt> - selects all the elements with <tt>type=&quot;text&quot;</tt>
</li>

</ul>
<div class="Standard">
You can put replacement rules after the selector:
</div>
<ul>
<li>
none (e.g., <tt>&quot;#id&quot;</tt>) replaces all matching elements with the values<br/>
<tt>&quot;#name&quot; #&gt; &quot;David&quot; // &lt;span&gt;&lt;span id=&quot;name&quot;/&gt;&lt;/span&gt; -&gt; &lt;span&gt;David&lt;/span&gt;</tt>
</li>
<li>
* (e.g., &quot;<tt>#id *</tt>&quot;) replaces the content children of the matching elements with the values<br/>
<tt>&quot;#name *&quot; #&gt; &quot;David&quot; // &lt;span&gt;&lt;span id=&quot;name&quot;/&gt;&lt;/span&gt; -&gt; &lt;span&gt;&lt;span id=&quot;name&gt;David&lt;/span&gt;&lt;/span&gt;</tt>
</li>
<li>
*+ or <tt>*&lt;</tt> (e.g., &quot;<tt>#id *</tt>+&quot;) appends the value to the the content children nodes<br/>
<tt>&quot;#name *+&quot; #&gt; &quot;David&quot; // &lt;span&gt;&lt;span id=&quot;name&quot;&gt;Name: &lt;/span&gt;&lt;/span&gt; -&gt; &lt;span&gt;&lt;span id=&quot;name&gt;Name: David&lt;/span&gt;&lt;/span&gt;</tt>
</li>
<li>
<tt>-*</tt> or<tt> &gt;*</tt> (e.g., &quot;<tt>#id -*</tt>&quot;) prepends the value to the the content children nodes<br/>
<tt>&quot;#name -*&quot; #&gt; &quot;David&quot; // &lt;span&gt;&lt;span id=&quot;name&quot;&gt; Pollak&lt;/span&gt;&lt;/span&gt; -&gt; &lt;span&gt;&lt;span id=&quot;name&gt;David Pollak&lt;/span&gt;&lt;/span&gt;</tt>
</li>
<li>
<tt>[attr]</tt> (e.g., &quot;#id <tt>[href]</tt>&quot;) replaces the matching attribute’s value with the values. <br/>
<tt>&quot;#link [href]&quot; #&gt; &quot;http://dogscape.com&quot; <br/>
// &lt;a href=&quot;#&quot; id=&quot;link&quot;&gt;Dogscape&lt;/a&gt; -&gt; &lt;a href=&quot;http://dogscape.com&quot; id=&quot;link&quot;&gt;Dogscape&lt;/a&gt;</tt>
</li>
<li>
<tt>[attr+]</tt> (e.g., &quot;#id <tt>[class+]</tt>&quot;) appends the value to the existing attribute.<br/>
<tt>&quot;span [class+]&quot; #&gt; &quot;error&quot; <br/>
// &lt;span class&quot;foo&quot;&gt;Dogscape&lt;/span&gt; -&gt; &lt;span class&quot;foo error&quot;&gt;Dogscape&lt;/span&gt;</tt>
</li>
<li>
<tt>[attr!]</tt> (e.g., &quot;#id <tt>[class!]</tt>&quot;) removes the matching value to the existing from.<br/>
<tt>&quot;span [class!]&quot; #&gt; &quot;error&quot; <br/>
// &lt;span class&quot;error foo&quot;&gt;Dogscape&lt;/span&gt; -&gt; &lt;span class&quot;foo&quot;&gt;Dogscape&lt;/span&gt;</tt>
</li>
<li>
<tt>^^</tt> - lifts the selected element to the root of the elements that are returned making it possible to choose an element from a template
</li>
<li>
<tt>^*</tt> - lifts the selected element’s children to the root of the elements that are returned making it possible to choose an element’s children from a template
</li>

</ul>
<div class="Standard">
The right hand side of the CSS Selector Transform can be one of the following:
</div>
<ul>
<li>
<tt>String</tt> — a <tt>String</tt> constant, for example: <br/>
&quot;#name *&quot; #&gt; &quot;David&quot; // &lt;span id=&quot;name&quot;/&gt; -&gt; &lt;span id=&quot;name&quot;&gt;David&lt;/span&gt; <br/>
&quot;#name *&quot; #&gt; getUserNameAsString
</li>
<li>
<tt>NodeSeq</tt> - a <tt>NodeSeq</tt> constant, for example:<br/>
&quot;#name *&quot; #&gt; &lt;i&gt;David&lt;/i&gt; // &lt;span id=&quot;name&quot;/&gt; -&gt; &lt;span id=&quot;name&quot;&gt;&lt;i&gt;David&lt;/i&gt;&lt;/span&gt;<br/>
&quot;#name *&quot; #&gt; getUserNameAsHtml
</li>
<li>
<tt>NodeSeq =&gt; NodeSeq</tt> — a function that transforms the node (yes, it can be a CssBindFunc):<br/>
<tt>&quot;#name&quot; #&gt; ((n: NodeSeq) =&gt; n % (&quot;class&quot; -&gt; &quot;dog&quot;))</tt> // &lt;span id=&quot;name&quot;/&gt; -&gt; &lt;span id=&quot;name&quot; class=&quot;dog&quot;/&gt;
</li>
<li>
<tt>Bindable</tt> — something that implements the <tt>Bindable</tt> trait (e.g., <tt>MappedField</tt> and <tt>Record.Field</tt>)
</li>
<li>
<tt>StringPromotable</tt> — A constant that can be promoted to a <tt>String</tt> (<tt>Int</tt>, <tt>Symbol</tt>, <tt>Long</tt> or <tt>Boolean</tt>). There is an automatic (implicit) conversion from Int, Symbol, Long or Boolean to StringPromotable.<br/>
<tt>&quot;#id_like_cats&quot; #&gt; true &amp; &quot;#number_of_cats&quot; #&gt; 2</tt>
</li>
<li>
<tt>IterableConst</tt> — A <tt>Box</tt>, <tt>Seq</tt>, or <tt>Option</tt> of <tt>NodeSeq =&gt; NodeSeq</tt>, <tt>String</tt>, <tt>NodeSeq</tt>, or <tt>Bindable</tt>. Implicit conversions automatically promote the likes of <tt>Box[String]</tt>, <tt>List[String]</tt>, <tt>List[NodeSeq]</tt>, etc. to <tt>IterableConst</tt>.<br/>
<tt>&quot;#id&quot; #&gt; (Empty: Box[String]) // &lt;span&gt;&lt;span id=&quot;id&quot;&gt;Hi&lt;/span&gt;&lt;/span&gt; -&gt; &lt;span/&gt;<br/>
&quot;#id&quot; #&gt; List(&quot;a&quot;, &quot;b&quot;, &quot;c&quot;) // &lt;span&gt;&lt;span id=&quot;id&quot;/&gt;&lt;/span&gt; -&gt; &lt;span&gt;abc&lt;/span&gt;<br/>
&quot;#id [href]&quot; #&gt; (None: Option[String]) &lt;a id=&quot;id&quot; href=&quot;dog&quot;/&gt; -&gt; &lt;a id=&quot;id&quot;/&gt;</tt>
</li>

</ul>
<div class="Standard">
Note that if you bind to the children of a selected element, multiple copies of the element result from bind to an <tt>IterableConst</tt> (if the element has an id attribute, the id attribute will be stripped after the first element): 
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: scala">&quot;#line *&quot; #&gt; List(&quot;a&quot;, &quot;b&quot;, &quot;c&quot;) // &lt;li id=&quot;line&gt;sample&lt;/li&gt; -&gt; 
                              // &lt;li id=&quot;line&quot;&gt;a&lt;/li&gt;&lt;li&gt;b&lt;/li&gt;&lt;li&gt;c&lt;/li&gt;
​
&quot;#age *&quot; #&gt; (None: Option[NodeSeq]) // &lt;span&gt;&lt;span id=&quot;age&quot;&gt;Dunno&lt;/span&gt;&lt;/span&gt; -&gt; 
                                    // &lt;span/&gt;
</pre>
</div>

</div>
<div class="Standard">
The above use cases may seem a little strange (they are not quite orthogonal), but they address common use cases in Lift. * IterableFunc — A Box, Seq, or Option of functions that transform NodeSeq =&gt; String, NodeSeq, Seq[String], Seq[NodeSeq], Box[String], Box[NodeSeq], Option[String] or Option[NodeSeq]. The same rules for handling multiple values in IterableConst apply to IterableFunc. Implicit conversions automatically promote the functions with the appropriate signature to an IterableFunc.
</div>
<div class="Standard">
You can chain CSS Selector Transforms with the <tt>&amp;</tt> method:<br/>
<tt>&quot;#id&quot; #&gt; &quot;33&quot; &amp; &quot;#name&quot; #&gt; &quot;David&quot; &amp; &quot;#chat_line&quot; #&gt; List(&quot;a&quot;, &quot;b&quot;, &quot;c&quot;) &amp; ClearClearable</tt>
</div>
<div class="Standard">
CSS Selector Transforms offer an alternative to Lift’s traditional binding (See <tt>Helpers.bind()</tt>).
</div>
<h2 class="Section">
<a name="toc-Section-7.11" class="toc">7.11</a> Client-side behavior invoking server-side functions<a name="sec:Client-side-behavior-invoking" class="Label"> </a>
</h2>
<h2 class="Section">
<a name="toc-Section-7.12" class="toc">7.12</a> Ajax<a name="sec:Ajax" class="Label"> </a>
</h2>
<h2 class="Section">
<a name="toc-Section-7.13" class="toc">7.13</a> Comet<a name="sec:Comet" class="Label"> </a>
</h2>
<h2 class="Section">
<a name="toc-Section-7.14" class="toc">7.14</a> LiftActor<a name="sec:LiftActor" class="Label"> </a>
</h2>
<h2 class="Section">
<a name="toc-Section-7.15" class="toc">7.15</a> Pattern Matching<a name="sec:Pattern-Matching" class="Label"> </a>
</h2>
<h2 class="Section">
<a name="toc-Section-7.16" class="toc">7.16</a> Type safety<a name="sec:Type-safety" class="Label"> </a>
</h2>
<h2 class="Section">
<a name="toc-Section-7.17" class="toc">7.17</a> Page rewriting<a name="sec:Page-rewriting" class="Label"> </a>
</h2>
<h2 class="Section">
<a name="toc-Section-7.18" class="toc">7.18</a> Security<a name="sec:Security" class="Label"> </a>
</h2>
<h1 class="Chapter">
<a name="toc-Chapter-8" class="toc">8</a> Common Patterns
</h1>
<div class="Standard">

</div>
<h2 class="Section">
<a name="toc-Section-8.1" class="toc">8.1</a> <a name="sec:Localization" class="Label"> </a>Localization
</h2>
<div class="Standard">
Lift has broad support for localization at the page and element level.
</div>
<h3 class="Subsection">
<a name="toc-Subsection-8.1.1" class="toc">8.1.1</a> Localizing Templates
</h3>
<div class="Standard">
The locale for the current request is calculated based on the function in <tt>LiftRules.localeCalculator</tt>. By default, the function looks at the <a href="http://download.oracle.com/javaee/1.2.1/api/javax/servlet/ServletRequest.html#getLocale%28%29" class="URL">Locale in the HTTP request</a>. But you can change this function to look at the Locale for the current user by changing <tt>LiftRules.localeCalculator</tt>.
</div>
<div class="Standard">
When a template is requested, Lift’s <tt>TemplateFinder</tt> looks for a template with the suffix <tt>_langCOUNTRY.html</tt>, then <tt>_lang.html</tt>, then <tt>.html</tt>. So, if you’re loading <tt>/frog</tt> and your Locale is <tt>enUS</tt>, then Lift will look for <tt>/frog_enUS.html</tt>, then <tt>/frog_en.html</tt>, then <tt>/frog.html</tt>. But if your Locale is Czech, then Lift would look for <tt>/frog_csCZ.html</tt>, <tt>/frog_cs.html</tt>, and <tt>/frog.html</tt>. The same lookup mechanism is used for templates accessed via the Surround (See <a href="#sec:Tail" class="Reference">↓</a>) and Embed (See <a href="#sec:Embed" class="Reference">↓</a>) snippets. So, at the template level, Lift offers very flexible templating.
</div>
<div class="Standard">
<div style="width: 100%;" class="Frameless">
Note: Lift parses all templates in UTF-8. Please make sure your text editor is set to UTF-8 encoding.
</div>

</div>
<h3 class="Subsection">
<a name="toc-Subsection-8.1.2" class="toc">8.1.2</a> Resource Lookup
</h3>
<div class="Standard">
Lift uses the following mechanism to look up resources. Localized resources are stored in template files along-side your HTML pages. The same parser is used to load resources and the pages themselves. A global set of resources is searched for in the following files: <tt>/_resources.html</tt>, <tt>/templates-hidden/_resources.html</tt>, and <tt>/resources-hidden/_resources.html</tt>. Keep in mind that Lift will look for the _resources file using the suffixes based on the Locale.
</div>
<div class="Standard">
The resource file should be in the following format:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: scala">&lt;resources&gt;
  &lt;res name=&quot;welcome&quot;&gt;Benvenuto&lt;/res&gt;
  &lt;res name=&quot;thank.you&quot;&gt;Grazie&lt;/res&gt;
  &lt;res name=&quot;locale&quot;&gt;Località&lt;/res&gt;
  &lt;res name=&quot;change&quot;&gt;Cambia&lt;/res&gt;
&lt;/resources&gt;
</pre>
</div>

</div>
<div class="Standard">
In addition to global resource files, there are per-page resource files (based on the current <tt>Req</tt>.) If you are currently requesting page <tt>/foo/bar</tt>, the following resource files will also be consulted: <tt>/foo/_resources_bar.html</tt>, <tt>/templates-hidden/foo/_resources_bar.html</tt>, and <tt>/foo/resources-hidden/_resources_bar.html</tt> (and all Locale-specific suffixes.) You can choose to create a separate resource file for each locale, or lump multiple locales into the <tt>_resources_bar.html</tt> file itself using the following format:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: scala">&lt;resources&gt;
  &lt;res name=&quot;hello&quot; lang=&quot;en&quot; default=&quot;true&quot;&gt;Hello&lt;/res&gt;
  &lt;res name=&quot;hello&quot; lang=&quot;en&quot; country=&quot;US&quot;&gt;Howdy, dude!&lt;/res&gt;
  &lt;res name=&quot;hello&quot; lang=&quot;it&quot;&gt;Benvenuto&lt;/res&gt;
  &lt;res name=&quot;thank.you&quot; lang=&quot;en&quot; default=&quot;true&quot;&gt;Thank You&lt;/res&gt;
  &lt;res name=&quot;thank.you&quot; lang=&quot;it&quot;&gt;Grazie&lt;/res&gt;
  &lt;res name=&quot;locale&quot; lang=&quot;en&quot; default=&quot;true&quot;&gt;Locale&lt;/res&gt;
  &lt;res name=&quot;locale&quot; lang=&quot;it&quot;&gt;Località&lt;/res&gt;
  &lt;res name=&quot;change&quot; lang=&quot;en&quot; default=&quot;true&quot;&gt;Change&lt;/res&gt;
  &lt;res name=&quot;change&quot; lang=&quot;it&quot;&gt;Cambia&lt;/res&gt;
&lt;/resources&gt;
</pre>
</div>

</div>
<h3 class="Subsection">
<a name="toc-Subsection-8.1.3" class="toc">8.1.3</a> Accessing Resources
</h3>
<div class="Standard">
Lift makes it easy to access resources.
</div>
<div class="Standard">
From snippets: <tt>&lt;span class=&quot;lift:Loc.hello&quot;&gt;This Hello will be replaced if possible&lt;/span&gt;</tt> Note that the value after the . in the snippet invocation is used to look up the resource name.
</div>
<div class="Standard">
From code:
</div>
<ul>
<li>
<tt>S.loc(&quot;hello&quot;)</tt> - return a <tt>Box[NodeSeq]</tt> containing the localized value for the resource named “hello”.
</li>
<li>
<tt>S.??(&quot;Hello World&quot;)</tt> - look for a resource named “Hello World” and return the String value for that resource. If the resource is not found, return “Hello World”.
</li>

</ul>
<h3 class="Subsection">
<a name="toc-Subsection-8.1.4" class="toc">8.1.4</a> Conclusion
</h3>
<div class="Standard">
Lift offers a broad range of mechanisms for localizing your application on a page-by-page and resource-by-resource by-resource basis.
</div>
<h2 class="Section">
<a name="toc-Section-8.2" class="toc">8.2</a> Dependency Injection<a name="sec:Dependency-Injection" class="Label"> </a>
</h2>
<div class="Standard">
Dependency injection is an important topic in the Java world. It’s important because Java lacks certain basic features (e.g., functions) that tend to bind abstract interfaces to concrete implementations. Basically, it’s so much easier to do <tt>MyInterface thing = new MyInterfaceImpl()</tt>, so most developers do just that. 
</div>
<div class="Standard">
Scala’s <a href="http://scala.sygneca.com/patterns/component-mixins" class="URL">cake pattern</a> goes a long way to help developers compose complex behaviors by combining Scala traits. Jonas Bonér wrote an excellent piece on <a href="http://jonasboner.com/2008/10/06/real-world-scala-dependency-injection-di.html" class="URL">Dependency Injection</a>.
</div>
<div class="Standard">
The cake pattern only goes half way to giving a Java developer complete dependency injection functionality. The cake pattern allows you to compose the complex classes out of Scala traits, but the cake pattern is less helpful in terms of allowing you to make dynamic choices about which combination of cake to vend in a given situation. Lift provides extra features that complete the dependency injection puzzle. 
</div>
<h3 class="Subsection">
<a name="toc-Subsection-8.2.1" class="toc">8.2.1</a> Lift Libraries and Injector
</h3>
<div class="Standard">
Lift is both a web framework and a set of Scala libraries. Lift’s <tt>common</tt>, <tt>actor</tt>, <tt>json</tt>, and <tt>util</tt> packages provide common libraries for Scala developers to build their application. Lift’s libraries are well tested, widely used, well supported, and released on a well defined schedule (montly milestones, quarterly releases). 
</div>
<div class="Standard">
Lift’s <tt>Injector</tt> trait forms the basis of dependency injection: 
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: scala">/** 
 * A trait that does basic dependency injection.
 */
trait Injector {
  implicit def inject[T](implicit man: Manifest[T]): Box[T]
}
</pre>
</div>

</div>
<div class="Standard">
You can use this trait as follows: 
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: scala">object MyInjector extends Injector {...}
​
val myThing: Box[Thing] = MyInjector.inject
</pre>
</div>

</div>
<div class="Standard">
The reason that the instance of <tt>MyThing</tt> is in a <tt>Box</tt> is because we’re not guaranteed that <tt>MyInjector</tt> knows how to create an instance of <tt>Thing</tt>. Lift provides an implementation of <tt>Injector</tt> called <tt>SimpleInjector</tt> that allows you to register (and re-register) functions for injection:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: scala">object MyInjector extends SimpleInjector
​
def buildOne(): Thing = if (testMode) new Thing with TestThingy {} else new Thing with RuntimeThingy {}
​
MyInjector.registerInjection(buildOne _) // register the function that builds Thing 
​
val myThing: Box[Thing] = MyInjector.inject
</pre>
</div>

</div>
<div class="Standard">
This isn’t bad... it allows us to define a function that makes the injection-time decision, and we can change the function out during runtime (or test-time.) However, there are two problems: getting Boxes for each injection is less than optimal. Further, globally scoped functions mean you have to put a whole bunch of logic (test vs. production vs. xxx) into the function. <tt>SimpleInjector</tt> has lots of ways to help out.
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: scala">object MyInjector extends SimpleInjector {
  val thing = new Inject(buildOne _) {} // define a thing, has to be a val so it’s eagerly evaluated and registered
}
​
def buildOne(): Thing = if (testMode) new Thing with TestThingy {} else new Thing with RuntimeThingy {} 
​
val myThingBox: Box[Thing] = MyInjector.injectval 
​
myThing = MyInjector.thing.vend // vend an instance of Thing 
</pre>
</div>

</div>
<div class="Standard">
<tt>Inject</tt> has a futher trick up its sleave... with <tt>Inject</tt>, you can scope the function... this is helpful for testing and if you need to change behavior for a particular call scope:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: scala">MyInjector.thing.doWith(new Thing with SpecialThing {}) { 
  val t = MyInjector.thing.vend // an instance of SpecialThing 
  val bt: Box[Thing] = MyInjector.inject // Full(SpecialThing) 
}
​
MyInjector.thing.default.set(() =&gt; new Thing with YetAnotherThing {}) // set the global scope 
</pre>
</div>

</div>
<div class="Standard">
Within the scope of the <tt>doWith</tt> call, <tt>MyInjector.thing</tt> will vend instances of <tt>SpecialThing</tt>. This is useful for testing as well as changing behavior within the scope of the call or globally. This gives us much of the functionality we get with dependency injection packages for Java. But within Lift WebKit, it gets better.
</div>
<h3 class="Subsection">
<a name="toc-Subsection-8.2.2" class="toc">8.2.2</a> Lift WebKit and enhanced injection scoping 
</h3>
<div class="Standard">
Lift’s WebKit offers broad ranging tools for handling HTTP requests as well as HTML manipulation.
</div>
<div class="Standard">
Lift WebKit’s <tt>Factory</tt> extends <tt>SimpleInjector</tt>, but adds the ability to scope the function based on current HTTP request or the current container session:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: scala">object MyInjector extends Factory { 
  val thing = new FactoryMaker(buildOne _) {} // define a thing, has to be a val so it’s eagerly 
                                              // evaluated and registered
} 
​
MyInjector.thing.session.set(new Thing with ThingForSession {}) // set the instance that will be vended 
                                                                // for the duration of the session 
​
MyInjector.thing.request.set(new Thing with ThingForRequest {}) // set the instance that will be vended 
                                                                // for the duration of the request
</pre>
</div>
 
</div>
<div class="Standard">
WebKit’s <tt>LiftRules</tt> is a <tt>Factory</tt> and many of the properties that <tt>LiftRules</tt> contains are <tt>FactoryMakers</tt>. This means that you can change behavior during call scope (useful for testing):
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: scala">LiftRules.convertToEntity.doWith(true) { ... test that we convert certain characters to entities} 
</pre>
</div>

</div>
<div class="Standard">
Or based on the current request (for example you can change the rules for calculating the docType during the current request):
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: scala">if (isMobileReqest) LiftRules.docType.request.set((r: Req) =&gt; Full(DocType.xhtmlMobile))
</pre>
</div>

</div>
<div class="Standard">
Or based on the current session (for example, changing maxConcurrentRequests based on some rules when a session is created):
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: scala">if (browserIsSomethingElse) LiftRules.maxConcurrentRequests.session.set((r: Req) =&gt; 32) 
              // for this session, we allow 32 concurrent requests 
</pre>
</div>

</div>
<h3 class="Subsection">
<a name="toc-Subsection-8.2.3" class="toc">8.2.3</a> Conclusion 
</h3>
<div class="Standard">
Lift’s <tt>SimpleInjector</tt>/<tt>Factory</tt> facilities provide a powerful and flexible mechanism for vending instances based on a global function, call stack scoping, request and session scoping and provides more flexible features than most Java-based dependency injection frameworks without resorting to XML for configuration or byte-code rewriting magic.
</div>
<h2 class="Section">
<a name="toc-Section-8.3" class="toc">8.3</a> Modules
</h2>
<div class="Standard">
Lift has supported modules from the first version of the project in 2007. Lift’s entire handling of the HTTP request/response cycle is open to hooks. Further, Lift’s templating mechanism where resulting HTML pages are composed by transforming page content via snippets (See <a href="#sec:Snippets" class="Reference">↑</a>) which are simply functions that take HTML and return HTML: <tt>NodeSeq =&gt; NodeSeq</tt>. Because Lift’s snippet resolution mechanism is open and any code referenced in Boot (See <a href="#sec:Boot" class="Reference">↑</a>), any code can be a Lift “module” by virtue of registering its snippets and other resources in <tt>LiftRules</tt>. Many Lift modules already exist including PayPal, OAuth, OpenID, LDAP, and even a module containing many jQuery widgets.
</div>
<div class="Standard">
The most difficult issue relating to integration of external modules into Lift is how to properly insert the module’s menu items into a SiteMap (See <a href="#sec:SiteMap-1" class="Reference">↑</a>) menu hierarchy. Lift 2.2 introduces a more flexible mechanism for mutating the <tt>SiteMap</tt>: <tt>SiteMap</tt> mutators. <tt>SiteMap</tt> mutators are functions that rewrite the SiteMap based on rules for where to insert the module’s menus in the menu hierarchy. Each module may publish markers. For example, here are the markers for ProtoUser:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: scala">/**
* Insert this LocParam into your menu if you want the
* User’s menu items to be inserted at the same level
* and after the item
*/
final case object AddUserMenusAfter extends Loc.LocParam[Any]
/**
* replace the menu that has this LocParam with the User’s menu
* items
*/
final case object AddUserMenusHere extends Loc.LocParam[Any]
/**
* Insert this LocParam into your menu if you want the
* User’s menu items to be children of that menu
*/
final case object AddUserMenusUnder extends Loc.LocParam[Any]
</pre>
</div>

</div>
<div class="Standard">
The module also makes a <tt>SiteMap</tt> mutator available, this can either be returned from the module’s <tt>init</tt> method or via some other method on the module. ProtoUser makes the <tt>sitemapMutator</tt> method available which returns a <tt>SiteMap =&gt; SiteMap</tt>.
</div>
<div class="Standard">
The application can add the marker to the appropriate menu item:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: scala">Menu(&quot;Home&quot;) / &quot;index&quot; &gt;&gt; User.AddUserMenusAfter
</pre>
</div>

</div>
<div class="Standard">
And when the application registers the <tt>SiteMap</tt> with <tt>LiftRules</tt>, it applies the mutator:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: scala">LiftRules.setSiteMapFunc(() =&gt; User.sitemapMutator(sitemap()))
</pre>
</div>

</div>
<div class="Standard">
Because the mutators are composable:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: scala">val allMutators = User.sitemapMutator andThen FruitBat.sitemapMutator
LiftRules.setSiteMapFunc(() =&gt; allMutators(sitemap()))
</pre>
</div>

</div>
<div class="Standard">
For each module, the implementation of the mutators is pretty simple:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: scala">  private lazy val AfterUnapply = SiteMap.buildMenuMatcher(_ == AddUserMenusAfter)
  private lazy val HereUnapply = SiteMap.buildMenuMatcher(_ == AddUserMenusHere)
  private lazy val UnderUnapply = SiteMap.buildMenuMatcher(_ == AddUserMenusUnder)
​
  /**
   * The SiteMap mutator function
   */
  def sitemapMutator: SiteMap =&gt; SiteMap = SiteMap.sitemapMutator {
    case AfterUnapply(menu) =&gt; menu :: sitemap
    case HereUnapply(_) =&gt; sitemap
    case UnderUnapply(menu) =&gt; List(menu.rebuild(_ ::: sitemap))
  }(SiteMap.addMenusAtEndMutator(sitemap))
</pre>
</div>

</div>
<div class="Standard">
We’ve defined some extractors that help with pattern matching. <tt>SiteMap.buildMenuMatcher</tt> is a helper method to make building the extractors super-simple. Then we supply a <tt>PartialFunction[Menu, List[Menu]]</tt> which looks for the marker <tt>LocParam</tt> and re-writes the menu based on the marker. If there are no matches, the additional rule is fired, in this case, we append the menus at the end of the <tt>SiteMap</tt>.
</div>
<div class="Standard">

</div>
<h2 class="Section">
<a name="toc-Section-8.4" class="toc">8.4</a> HtmlProperties, XHTML and HTML5
</h2>
<div class="Standard">
Lift unifies many aspects of parsing and displaying the HTML page in a single trait, <tt>HtmlProperties</tt>.
</div>
<div class="Standard">
HtmlProperties defines, on a session-by-session (and even a request-by-request) basis, the way that templates are parsed and the way that Scala’s <tt>NodeSeq</tt> is converted into valid HTML output. The properties on <tt>HtmlProperties</tt> are:
</div>
<ul>
<li>
<tt>docType</tt> - the DocType for the HTML page, e.g., <tt>&lt;!DOCTYPE html PUBLIC &quot;-//W3C//DTD XHTML 1.0 Transitional//EN&quot; &quot;http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd&quot;&gt;</tt> or <tt>&lt;!DOCTYPE html&gt;</tt>
</li>
<li>
<tt>encoding</tt> - the page’s encoding, e.g., <tt>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;</tt>
</li>
<li>
contentType - the setting of the Content-Type response header, e.g., <tt>application/xhtml+xml; charset=utf-8</tt> or <tt>text/html; charset=utf-8</tt>
</li>
<li>
<tt>htmlOutputHeader</tt> - calculates the way to combine the <tt>docType</tt> and <tt>encoding</tt> (this is important for IE6 support where encoding goes after docType).
</li>
<li>
<tt>htmlParser</tt> - a function that converts an <tt>InputStream</tt> to a <tt>Box[NodeSeq]</tt>. This is used by Lift to parse templates.
</li>
<li>
<tt>htmlWriter</tt> - a function that writes a <tt>NodeSeq</tt> to a <tt>Writer</tt>. This is used by Lift to convert the internal XML representation of a page to a stream of bytes representing an HTML page.
</li>
<li>
<tt>html5FormsSupport</tt> - a flag indicating whether the current browser supports HTML5 forms.
</li>
<li>
<tt>maxOpenRequests</tt> - the maximum number of concurrent HTTP requests the browser supports to a named host.
</li>
<li>
<tt>userAgent</tt> - the User-Agent string sent from the browser.
</li>

</ul>
<h3 class="Subsection">
<a name="toc-Subsection-8.4.1" class="toc">8.4.1</a> XHTML via <tt>OldHtmlProperties</tt>
</h3>
<div class="Standard">
The default properties that keep compability with the disparate LiftRules used to calculate DocType and Encoding. Uses the <tt>PCDataXmlParser</tt> parser which requires well-formed XML files. Output is generally XHTML via <tt>AltXML.toXML</tt>, but cerain tags (e.g., <tt>&lt;br&gt;</tt>) are written in IE6/IE7 friendly ways.
</div>
<h3 class="Subsection">
<a name="toc-Subsection-8.4.2" class="toc">8.4.2</a> HTML5 via <tt>Html5Properties</tt>
</h3>
<div class="Standard">
Prior to Lift 2.2, Lift always emitted XHTML and by default set the Content-Type header to <tt>application/xhtml+xml; charset=utf-8</tt>. This continues to be Lift’s default behavior. It turns out that most browsers, even modern ones (Firefox, Chrome and Safari) had issues with XHTML. Further, XHTML limited the behavior of certain JavaScript libraries.
</div>
<div class="Standard">
By invoking <tt>LiftRules.htmlProperties.default.set((r: Req) =&gt; new Html5Properties(r.userAgent))</tt> in Boot.scala, you can set Lift to full HTML5 support. Lift uses the <a href="http://about.validator.nu/htmlparser/" class="URL">nu.validator</a> HTML parser and emits the correct DocType and response headers such that all tested browsers (IE6+, Firefox 2+, Safari 2+, Chrome 1+) render pages correctly.
</div>
<div class="Standard">
Because the HTML5 parser is different from the standard XML parser, you will need to adjust your existing templates in the following ways:
</div>
<ul>
<li>
All tags are converted to lower case. This means the <tt>&lt;lift:FooBar/&gt;</tt> gets converted to <tt>&lt;lift:foobar/&gt;</tt> I advise converting to designer friendly where possible (e.g., <tt>&lt;div class=&quot;lift:FooBar&quot;&gt;&lt;/div&gt;</tt>).
</li>
<li>
Tags of the format <tt>&lt;div/&gt;</tt> and <tt>&lt;my_thing:bind/&gt;</tt> are not legal. They must be converted to <tt>&lt;div&gt;&lt;/div&gt;</tt> and <tt>&lt;my_thing:bind&gt;&lt;/my_thing:bind&gt;</tt>. Unfortunately, the parser is very forgiving so rather than barking about the lack of closing tag, the parser will nest things in unexpected ways.
</li>
<li>
There are some tags that the parser &quot;ensures&quot;. For example a <tt>&lt;tr&gt;</tt>, <tt>&lt;thead&gt;</tt>, or <tt>&lt;tbody&gt;</tt> tag <b>must</b> be the first tag inside <tt>&lt;table&gt;</tt>. This breaks the <tt><br/>
&lt;table&gt;&lt;mysnippet:line&gt;<br/>
&lt;tr&gt;&lt;td&gt;&lt;mysnippet:bind_here&gt;&lt;/mysnippet:bind_here&gt;&lt;/td&gt;&lt;/tr&gt;<br/>
&lt;/mysnippet:line&gt;&lt;table&gt;</tt> <br/>
paradigm. You can get the desired behavior with<br/>
<tt>&lt;table&gt;&lt;tr lift:bind=&quot;mysnippet:line&quot;&gt;&lt;td&gt;&lt;mysnippet:bind_here&gt;&lt;/mysnippet:bind_here&gt;&lt;/td&gt;&lt;/tr&gt;&lt;table&gt;</tt>.
</li>

</ul>
<h3 class="Subsection">
<a name="toc-Subsection-8.4.3" class="toc">8.4.3</a> Changing behavior mid-session or mid-request
</h3>
<div class="Standard">
You can change the behavior of HtmlProperties mid-session or mid-request. <tt>LiftSession.sessionHtmlProperties</tt> is a <tt>SessionVar</tt> that contains the <tt>HtmlProperties</tt> for the session. <tt>LiftSession.requestHtmlProperties</tt> is a <tt>TranientRequestVar</tt> containing the <tt>HtmlProperties</tt> for the request. At the begining of the request, <tt>requestHtmlProperties</tt> is set to the value of <tt>sessionHtmlProperties</tt>. You can alter a property for the duration of the request using:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: scala">for {
  session &lt;- S.session
} session.requestHtmlProperties.set(session.
          requestHtmlProperties.is.setDocType(() =&gt; 
                                   Full(&quot;&lt;!DOCTYPE moose&gt;&quot;)))
</pre>
</div>

</div>
<h1 class="Chapter">
<a name="toc-Chapter-9" class="toc">9</a> Built-in Snippets
</h1>
<h2 class="Section">
<a name="toc-Section-9.1" class="toc">9.1</a> CSS<a name="sec:CSS" class="Label"> </a>
</h2>
<h2 class="Section">
<a name="toc-Section-9.2" class="toc">9.2</a> <a name="sec:Msgs" class="Label"> </a>Msgs
</h2>
<h2 class="Section">
<a name="toc-Section-9.3" class="toc">9.3</a> <a name="sec:Msg" class="Label"> </a>Msg
</h2>
<h2 class="Section">
<a name="toc-Section-9.4" class="toc">9.4</a> <a name="sec:Menu" class="Label"> </a>Menu
</h2>
<h2 class="Section">
<a name="toc-Section-9.5" class="toc">9.5</a> <a name="sec:A" class="Label"> </a>A
</h2>
<h2 class="Section">
<a name="toc-Section-9.6" class="toc">9.6</a> <a name="sec:Children" class="Label"> </a>Children
</h2>
<h2 class="Section">
<a name="toc-Section-9.7" class="toc">9.7</a> <a name="sec:CometSnippet" class="Label"> </a>Comet
</h2>
<h2 class="Section">
<a name="toc-Section-9.8" class="toc">9.8</a> <a name="sec:Form" class="Label"> </a>Form
</h2>
<h2 class="Section">
<a name="toc-Section-9.9" class="toc">9.9</a> <a name="sec:Ignore" class="Label"> </a>Ignore
</h2>
<h2 class="Section">
<a name="toc-Section-9.10" class="toc">9.10</a> <a name="sec:Loc" class="Label"> </a>Loc
</h2>
<h2 class="Section">
<a name="toc-Section-9.11" class="toc">9.11</a> <a name="sec:Surround" class="Label"> </a>Surround
</h2>
<h2 class="Section">
<a name="toc-Section-9.12" class="toc">9.12</a> <a name="sec:TestCond" class="Label"> </a>TestCond
</h2>
<h2 class="Section">
<a name="toc-Section-9.13" class="toc">9.13</a> <a name="sec:Embed" class="Label"> </a>Embed
</h2>
<h2 class="Section">
<a name="toc-Section-9.14" class="toc">9.14</a> <a name="sec:Tail" class="Label"> </a>Tail
</h2>
<h2 class="Section">
<a name="toc-Section-9.15" class="toc">9.15</a> <a name="sec:WithParam" class="Label"> </a>WithParam
</h2>
<h2 class="Section">
<a name="toc-Section-9.16" class="toc">9.16</a> <a name="sec:VersionInfo" class="Label"> </a>VersionInfo
</h2>
<h2 class="Section">
<a name="toc-Section-9.17" class="toc">9.17</a> <a name="sec:SkipDocType" class="Label"> </a>SkipDocType
</h2>
<h2 class="Section">
<a name="toc-Section-9.18" class="toc">9.18</a> <a name="sec:XmlGroup" class="Label"> </a>XmlGroup
</h2>
<h2 class="Section">
<a name="toc-Section-9.19" class="toc">9.19</a> <a name="sec:LazyLoad" class="Label"> </a>LazyLoad
</h2>
<h2 class="Section">
<a name="toc-Section-9.20" class="toc">9.20</a> <a name="sec:WithResourceId" class="Label"> </a>WithResourceId
</h2>
<h1 class="Chapter">
<a name="toc-Chapter-10" class="toc">10</a> SiteMap
</h1>
<h1 class="Chapter">
<a name="toc-Chapter-11" class="toc">11</a> <a name="cha:REST" class="Label"> </a>REST
</h1>
<div class="Standard">
Lift makes providing REST-style web services very simple.
</div>
<div class="Standard">
First, create an object that extends <tt>RestHelper</tt>:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: scala">import net.liftweb.http._
import net.liftweb.http.rest._
​
object MyRest extends RestHelper {
  
}
</pre>
</div>

</div>
<div class="Standard">
And hook your changes up to Lift in <tt>Boot.scala</tt>:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: scala">LiftRules.dispatch.append(MyRest) // stateful — associated with a servlet container session
LiftRules.statelessDispatchTable.append(MyRest) // stateless — no session created
</pre>
</div>

</div>
<div class="Standard">
Within your MyRest object, you can define which URLs to serve:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: scala">serve { 
  case Req(&quot;api&quot; :: &quot;static&quot; :: _, &quot;xml&quot;, GetRequest) =&gt; &lt;b&gt;Static&lt;/b&gt; 
  case Req(&quot;api&quot; :: &quot;static&quot; :: _, &quot;json&quot;, GetRequest) =&gt; JString(&quot;Static&quot;) 
}
</pre>
</div>
 
</div>
<div class="Standard">
The above code uses the suffix of the request to determine the response type. Lift supports testing the <tt>Accept</tt> header for a response type:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: scala">serve { 
  case XmlGet(&quot;api&quot; :: &quot;static&quot; :: _, _) =&gt; &lt;b&gt;Static&lt;/b&gt; 
  case JsonGet(&quot;api&quot; :: &quot;static&quot; :: _, _) =&gt; JString(&quot;Static&quot;) 
}
</pre>
</div>
 
</div>
<div class="Standard">
The above can also be written:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: scala">serve { 
  case &quot;api&quot; :: &quot;static&quot; :: _ XmlGet _=&gt; &lt;b&gt;Static&lt;/b&gt; 
  case &quot;api&quot; :: &quot;static&quot; :: _ JsonGet _ =&gt; JString(&quot;Static&quot;) 
} 
</pre>
</div>

</div>
<div class="Standard">
Note: If you want to navigate your Web Service, you must remember to add a <tt>*.xml</tt> or <tt>*.json</tt> (depending in what you have implemented) at the end of the URL: <tt>http://localhost:8080/XXX/api/static/call.json</tt> <tt>http://localhost:8080/XXX/api/static/call.xml</tt> 
</div>
<div class="Standard">
Because the REST dispatch code is based on Scala’s pattern matching, we can extract elements from the request (in this case the third element will be extracted into the id variable which is a String:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: scala">serve { 
  case &quot;api&quot; :: &quot;user&quot; :: id :: _ XmlGet _ =&gt; &lt;b&gt;ID: {id}&lt;/b&gt;
  case &quot;api&quot; :: &quot;user&quot; :: id :: _ JsonGet _ =&gt; JString(id) 
} 
</pre>
</div>
And with extractors, we convert an element to a particular type and only succeed with the pattern match (and the dispatch) if the parameter can be converted. For example:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: scala">serve { 
  case &quot;api&quot; :: &quot;user&quot; :: AsLong(id) :: _ XmlGet _ =&gt; &lt;b&gt;ID: {id}&lt;/b&gt;
  case &quot;api&quot; :: &quot;user&quot; :: AsLong(id) :: _ JsonGet _ =&gt; JInt(id) 
} 
</pre>
</div>

</div>
<div class="Standard">
In the above example, id is extracted if it can be converted to a Long.
</div>
<div class="Standard">
Lift’s REST helper can also extract <tt>XML</tt> or <tt>JSON</tt> from a <tt>POST</tt> or <tt>PUT</tt> request and only dispatch the request if the XML or JSON is valid:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: scala">serve { 
  case &quot;api&quot; :: &quot;user&quot; :: _ XmlPut xml -&gt; _ =&gt; // xml is a scala.xml.Node 
    User.createFromXml(xml).map { u =&gt; u.save; u.toXml}
​
  case &quot;api&quot; :: &quot;user&quot; :: _ JsonPut json -&gt; _ =&gt; // json is a net.liftweb.json.JsonAST.JValue
    User.createFromJson(json).map { u =&gt; u.save; u.toJson} 
} 
</pre>
</div>

</div>
<div class="Standard">
There may be cases when you want to have a single piece of business logic to calculate a value, but then convert the value to a result based on the request type. That’s where <tt>serveJx</tt> comes in … it’ll serve a response for <tt>JSON</tt> and <tt>XML</tt> requests. If you define a trait called <tt>Convertable</tt>:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: scala">trait Convertable {
  def toXml: Elem 
  def toJson: JValue 
}
</pre>
</div>

</div>
<div class="Standard">
Then define a pattern that will convert from a <tt>Convertable</tt> to a <tt>JSON</tt> or <tt>XML</tt>:
</div>
<div class="Standard">
implicit def cvt: JxCvtPF[Convertable] = { case (JsonSelect, c, _) =&gt; c.toJson case (XmlSelect, c, _) =&gt; c.toXml } 
</div>
<div class="Standard">
And anywhere you use <tt>serveJx</tt> and your pattern results in a <tt>Box[Convertable]</tt>, the <tt>cvt</tt> pattern is used to generate the appropriate response:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: scala">serveJx { 
  case Get(&quot;api&quot; :: &quot;info&quot; :: Info(info) :: _, _) =&gt; Full(info) 
}
</pre>
</div>

</div>
<div class="Standard">
Or:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: scala">// extract the parameters, create a user 
// return the appropriate response 
​
def addUser(): Box[UserInfo] = 
  for { 
    firstname &lt;- S.param(&quot;firstname&quot;) ?~ &quot;firstname parameter missing&quot; ~&gt; 400 
    lastname &lt;- S.param(&quot;lastname&quot;) ?~ &quot;lastname parameter missing&quot; 
    email &lt;- S.param(&quot;email&quot;) ?~ &quot;email parameter missing&quot; 
  } yield { 
    val u = User.create.firstName(firstname). 
      lastName(lastname).email(email)
​
    S.param(&quot;password&quot;) foreach u.password.set
    u.saveMe 
  }
​
serveJx {
  case Post(&quot;api&quot; :: &quot;add_user&quot; :: _, _) =&gt; addUser() 
}
</pre>
</div>

</div>
<div class="Standard">
In the above example, if the <tt>firstname</tt> parameter is missing, the response will be a 400 with the response body “firstname parameter missing”. If the <tt>lastname</tt> parameter is missing, the response will be a 404 with the response body “lastname parameter missing”.
</div>
<h1 class="Chapter">
<a name="toc-Chapter-12" class="toc">12</a> MVC (If you really want it)
</h1>
<div class="Standard">

</div>
<h1 class="Chapter">
<a name="toc-Chapter-13" class="toc">13</a> <a name="cha:From-MVC" class="Label"> </a>From MVC
</h1>
<div class="Standard">
Okay, so you’re coming from MVC-land and you’re used to defining routes, defining controlers and defining views.
</div>
<div class="Standard">
Lift is different. For HTML requests, Lift loads the view first and builds your page from the view. Lift also supports REST style requests for non-HTML data. (See <a href="#cha:REST" class="Reference">11 on page 1↑</a>)
</div>
<div class="Standard">
“Why?” Because complex HTML pages rarely contain a dominant piece of logic... a single controller... but contain many different components. Some of those components interact and some do not. In Lift, you define the collection of components to be rendered in the resulting HTML page in the view.
</div>
<div class="Standard">
So, to create a page that has dynamic content, we need to do three things:
</div>
<ul>
<li>
Make a SiteMap entry for the page
</li>
<li>
Create the view (the HTML)
</li>
<li>
Create the behavior (the Snippet that transforms the incoming HTML to the dynamically generated HTML)
</li>

</ul>
<div class="Standard">
You can find the source for this project at <a href="https://github.com/dpp/simply_lift/tree/master/samples/from_mvc" class="URL">https://github.com/dpp/simply_lift/tree/master/samples/from_mvc</a>.
</div>
<h2 class="Section">
<a name="toc-Section-13.1" class="toc">13.1</a> First things first
</h2>
<div class="Standard">
The first step to using Lift is to make sure you’ve got Java 1.6 or better installed on your machine... you’ll need tar or zip as well.
</div>
<div class="Standard">
Download the <a href="https://github.com/lift/lift_23_sbt/tarball/master" class="URL">TAR</a> or <a href="https://github.com/lift/lift_23_sbt/zipball/master" class="URL">Zip</a> version of the Lift templates and extract the files.
</div>
<div class="Standard">
Copy the <tt>lift_basic</tt> project into another directory called <tt>first_lift</tt>.
</div>
<div class="Standard">
<tt>cd</tt> into <tt>first_lift</tt> and type <tt>sbt</tt>. It will take a few minutes for <tt>sbt</tt>, the Simple Build Tool, to download all the depedencies. At the <tt>&gt;</tt> prompt type <tt>update</tt> which will download Lift and everything else you need to get started. Once all that stuff is downloaded, type <tt>jetty-run</tt> and point your browser to <tt>http://localhost:8080</tt> and you’ll see a live application. To continuously update your running application as you to code, enter <tt>~prepare-webapp</tt> at the sbt prompt.
</div>
<h2 class="Section">
<a name="toc-Section-13.2" class="toc">13.2</a> Making a <tt>SiteMap</tt> entry
</h2>
<div class="Standard">
Every page on the site needs a <tt>SiteMap</tt> entry. For more on <tt>SiteMap</tt>, see <a href="#sec:SiteMap-1" class="Reference">3.2 on page 1↑</a> and <a href="#sec:SiteMap" class="Reference">7.5 on page 1↑</a>.
</div>
<div class="Standard">
Open the <tt>Boot.scala</tt> file (<tt>src/main/scala/bootstrap/liftweb/Boot.scala</tt>) and update the <tt>SiteMap</tt> definition:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: scala">    // Build SiteMap
    def sitemap(): SiteMap = SiteMap(
      Menu(&quot;Home&quot;) / &quot;index&quot;,
      Menu(&quot;Second Page&quot;) / &quot;second&quot;
    )
</pre>
</div>

</div>
<h2 class="Section">
<a name="toc-Section-13.3" class="toc">13.3</a> Creating the view
</h2>
<div class="Standard">
Next you have to create a file that corresponds to the path defined in the <tt>SiteMap</tt>. So, let’s look at the <tt>src/main/webapp/index.html</tt> file:
</div>
<div class="listing">
<div class="caption">
index.html
</div>
<pre class="listing brush: scala">

  
    <meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
    <title>Home</title>
  
  
    <div class="lift:surround?with=default&amp;at=content" id="main">
      <div>
        Hi, I'm a page that contains the time:
        <span class="lift:TimeNow">??? some time</span>.
      </div>
​
      <div>
        And a button: <button class="lift:ClickMe">Click Me</button>.
      </div>
    </div>
  

​
</pre>
</div>
<div class="Standard">
The page is valid HTML5. <tt>&lt;body class=&quot;lift:content_id=main&quot;&gt;</tt> says “ignore everything on this page except the Element with id ’main’.”
</div>
<div class="Standard">
<tt>&lt;div id=&quot;main&quot; class=&quot;lift:surround?with=default&amp;at=content&quot;&gt;</tt> says “Wrap the default page chrome around this Element.”
</div>
<div class="Standard">
<tt>&lt;span class=&quot;lift:TimeNow&quot;&gt;??? some time&lt;/span&gt;</tt> says “Find the <tt>TimeNow</tt> snippet and transform this Element with the rules contained in that snippet.” See <a href="#sec:Snippets" class="Reference">7.1 on page 1↑</a>. The result will be <tt>&lt;span&gt;Fri Jan 21 11:30:34 PST 2011&lt;/span&gt;</tt>
</div>
<div class="Standard">
So, that’s simple. You tell Lift what Snippet to use to transform your static content into dynamic content.
</div>
<h2 class="Section">
<a name="toc-Section-13.4" class="toc">13.4</a> Creating the Snippet
</h2>
<div class="Standard">
Next you have to tell Lift what the rules are for transforming the section of your template based on dynamic rules. This is a Snippet... it’s a function that transforms <tt>NodeSeq =&gt; NodeSeq</tt>. Let’s look at the <tt>TimeNow</tt> snippet:
</div>
<div class="listing">
<div class="caption">
TimeNow.scala
</div>
<pre class="listing brush: scala">// make sure this is the snippet package so Lift
// can find the snippet
package code
package snippet
​
// some inputs
import net.liftweb._
import util._
import Helpers._
​
// our snippet
object TimeNow {
  // create a function (NodeSeq =&gt; NodeSeq)
  // that puts the current time into the
  // body of the incoming Elem
  def render = &quot;* *&quot; #&gt; now.toString
}
</pre>
</div>
<div class="Standard">
This snippet must be in the <tt>snippet</tt> package so Lift knows how to find it by convention.
</div>
<div class="Standard">
It is an <tt>object</tt> which is a singleton because the snippet has no state.
</div>
<div class="Standard">
Lift calls the <tt>render</tt> method on a snippet unless you specify another method when you invoke your snippet.
</div>
<div class="Standard">
The snippet generates a function, <tt>NodeSeq =&gt; NodeSeq</tt>, that uses Lift’s CSS Selector Transforms (See <a href="#sec:CSS-Selector-Transforms" class="Reference">7.10 on page 1↑</a>) to insert the current time into the body of all HTML Elements: <tt>def render = &quot;* *&quot; #&gt; now.toString</tt>
</div>
<h2 class="Section">
<a name="toc-Section-13.5" class="toc">13.5</a> Getting Ajaxy
</h2>
<div class="Standard">
The <tt>ClickMe</tt> snippet is a little more complex, but it demonstrates, especially on the “Second Page” the power of Lift’s View First in which no particular component on the page is the dominant component. Here’s the <tt>ClickMe</tt> code:
</div>
<div class="listing">
<div class="caption">
ClickMe.scala
</div>
<pre class="listing brush: scala">// make sure this is the snippet package so Lift
// can find the snippet
package code
package snippet
​
// some inputs
import net.liftweb._
import util._
import Helpers._
import http._
import js.JsCmds._
​
// our snippet
object ClickMe {
  // variables associated with the request
  private object pos extends RequestVar(0)
  private object cnt extends RequestVar(0)
​
  // create a function (NodeSeq =&gt; NodeSeq)
  // set the onClick method of the button
  def render = {
    // capture our position on the page
    val posOnPage = pos.set(pos.is + 1)
​
    &quot;button [onclick]&quot; #&gt; 
    SHtml.ajaxInvoke(() =&gt; {
      cnt.set(cnt.is + 1) // increment the click count
      Alert(&quot;Thanks pos: &quot;+posOnPage+
          &quot; click count &quot;+cnt)
    })
  }
}
</pre>
</div>
<div class="Standard">
We define two <tt>RequestVar</tt>s that hold request-scoped values. For Lift, the scope of a request is the initial full HTML page load plus any Ajax requests associated with that page.
</div>
<div class="Standard">
When the snippet’s <tt>render</tt> method is called, we capture the current value for the <tt>pos</tt> <tt>RequestVar</tt>.
</div>
<div class="Standard">
The snippet associates the invocation of an Ajax call with the button’s <tt>onclick</tt> method. When the button is clicked, the function is invoked.
</div>
<div class="Standard">
The function closed over the scope of the position of the button on the page. The buttons all share the <tt>cnt</tt> <tt>RequestVar</tt> and thus for a single page load, the number of button-presses are counted. If you have 5 different browser tabs open to the same page, each tab will have a unique page count.
</div>
<div class="Standard">
This demonstrates the component nature of Lift and why having complex items on a page means not having a front-controller, but having lots of behaviors associated with lots of HTML elements.
</div>
<h2 class="Section">
<a name="toc-Section-13.6" class="toc">13.6</a> Next Steps
</h2>
<div class="Standard">
If you want to see more of Lift’s snazzy Ajax and Comet, check out <a href="#cha:The-ubiquitous-Chat" class="Reference">2 on page 1↑</a>. If you want to see more of the basics of <tt>SiteMap</tt> and snippets, check out <a href="#cha:Snippets-and-SiteMap" class="Reference">3 on page 1↑</a>. If you want to see how Lift does forms, check out <a href="#cha:Forms" class="Reference">4 on page 1↑</a>.
</div>
<h1 class="Part">
<a name="toc-Part-II" class="toc">Part II.</a> Recipes
</h1>
<div class="Standard">

</div>
<h1 class="Chapter">
<a name="toc-Chapter-14" class="toc">14</a> Dynamic html tables created from <tt>DB.runQuery()</tt>
</h1>
<h2 class="Section">
<a name="toc-Section-14.1" class="toc">14.1</a> Problem
</h2>
<div class="Standard">
What I’m trying is:
</div>
<div class="Standard">
1. query the SQL server via <tt>DB.runQuery()</tt>
</div>
<div class="Standard">
2. put the result (multiple, rows and columns) into a Table structure like this:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: xml">&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;&lt;th&gt;&lt;/th&gt;&lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
  &lt;tr&gt;&lt;td&gt;&lt;/td&gt;&lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;
</pre>
</div>

</div>
<h2 class="Section">
<a name="toc-Section-14.2" class="toc">14.2</a> Solution
</h2>
<div class="Standard">
The DB.runQuery(sql_query_string) method returns (List[String], List[List[String]]), to put that in a table, your view looks like:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: xml">&lt;table class=&quot;lift:MySnippet&quot;&gt;
  &lt;thead&gt;
    &lt;tr&gt;&lt;th id=&quot;my_th&quot;&gt;Field Name&lt;/th&gt;&lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
  &lt;tr id=&quot;my_tr&quot;&gt;&lt;td&gt;An item&lt;/td&gt;&lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;
</pre>
</div>

</div>
<div class="Standard">
And your snippet uses CSS Selector Transforms (See <a href="#sec:CSS-Selector-Transforms" class="Reference">↑</a>) and looks like:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: scala">object MySnippet {
  def render = {
    val (fieldNames: List[String], fieldValues: List[List[String]]) = DB.runQuery(...)
​
    &quot;#my_th *&quot; #&gt; fieldNames &amp;
    &quot;#my_tr *&quot; #&gt; fieldValues.map(values =&gt; &quot;td *&quot; #&gt; values)
  }
}
</pre>
</div>

</div>
<h1 class="Chapter">
<a name="toc-Chapter-15" class="toc">15</a> Dynamically choosing content
</h1>
<h2 class="Section">
<a name="toc-Section-15.1" class="toc">15.1</a> Problem
</h2>
<div class="Standard">
I want to to keep design completely separated from logic and I am bit stuck. I have a page that loads different pieces of html depending on some variables and it also has some ajax code so it may load new pieces of html. So far, that page uses only one snippet that has the logic to decide what html should be loaded. So here is the question, how should the snippet get an only-with-design piece of html to bind data to it.
</div>
<h2 class="Section">
<a name="toc-Section-15.2" class="toc">15.2</a> Solution
</h2>
<div class="Standard">
Snippets are evaluated recursively... this means that you can return markup from a snippet that contains other snippets.
</div>
<div class="Standard">
The other thing to pay attention to is the <tt>&lt;lift:embed&gt;</tt> snippet (See <a href="#sec:Embed" class="Reference">↑</a>).
</div>
<div class="Standard">
Combining the two:
</div>
<div class="Standard">
Main page:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: scala">&lt;html&gt;&lt;body&gt; Stuff here
&lt;div class=&quot;lift:ChooseBehavior&quot;&gt;Different behavior will go here&lt;/div&gt;
&lt;/body&gt;&lt;/html&gt;
</pre>
</div>

</div>
<div class="Standard">
The snippet:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: scala">object ChooseBehavior {
  def render = someState match {
    case ShowData =&gt; &lt;lift:embed what=&quot;_showData&quot; /&gt;
    case EditData =&gt; &lt;lift:embed what=&quot;_editData&quot; /&gt;
    case AjaxThing =&gt; &lt;lift:embed what=&quot;_ajaxThing&quot; /&gt;
  }
}
</pre>
</div>

</div>
<div class="Standard">
Then your designer need only edit the main page and each of the templates, and then you wire them together.
</div>
<h1 class="Chapter">
<a name="toc-Chapter-16" class="toc">16</a> Ajax Forms
</h1>
<h1 class="Chapter">
<a name="toc-Chapter-17" class="toc">17</a> Protecting REST APIs
</h1>
<h2 class="Section">
<a name="toc-Section-17.1" class="toc">17.1</a> Problem
</h2>
<div class="Standard">
I want to expose part of my site as authenticated REST, but with custom authentication (not the HTTP based authentication).
</div>
<div class="Standard">
Right now, I’m thinking of using a custom dispatch, but that means I’ll have to check every request in the request handler itself to see if it is authenticated, right?
</div>
<div class="Standard">
Authentication is just a SessionVar on the server, so it also implies I need a way to pass the session identifier back and forth between the REST client and the service. If it were a cookie I think it would be transparent, but I think Lift adds te session ids to the URLs (at least that’s what I see in my address bar).
</div>
<div class="Standard">
So, assuming I have a public &quot;login&quot; REST call that sets a SessionVar, how do I pass this transarently to the REST client? I have thought about a token system as well, but that seems like copying the session system.
</div>
<div class="Standard">
Any suggestions? 
</div>
<h2 class="Section">
<a name="toc-Section-17.2" class="toc">17.2</a> Solution
</h2>
<div class="Standard">
If you’ve got a:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: scala">object MyService extends RestHelper {
....
}
</pre>
</div>

</div>
<div class="Standard">
And:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: scala">val ensureSession: PartialFunction[Req, Unit] = {
  case _ if isLoggedIn =&gt; 
}
</pre>
</div>

</div>
<div class="Standard">
then in Boot:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: scala">import net.liftweb.util.Helpers._
​
LiftRules.dispatch.append(ensureSession guard MyService)
</pre>
</div>

</div>
<div class="Standard">
This is a simple way to compose <tt>PartialFunctions</tt> and put a guard around all the elements of a <tt>PartialFunction</tt>.
</div>
<div class="Standard">

</div>
<h1 class="Chapter">
<a name="toc-Chapter-18" class="toc">18</a> URI-based locale selection
</h1>
<h2 class="Section">
<a name="toc-Section-18.1" class="toc">18.1</a> Problem
</h2>
<div class="Standard">
I’m evaluating Lift and one thing I miss, or cannot see how toimplement, is the ability to have the locale determined from an URI-pattern. In Struts2 I have:
</div>
<div class="Standard">
<tt><div class="listing">
<pre class="listing brush: xml">namespace=&quot;/{request_locale}&quot;
</pre>
</div>
</tt>
</div>
<div class="Standard">
So I can have an action (restful) invoked on an <tt>URI=/no/companies/company/1</tt> and it will call my CompanyAction with <tt>id=1</tt> and the locale
</div>
<div class="Standard">
set to <tt>no</tt> If called from <tt>URI=/en/companies/company/1</tt> it will callthe same <tt>CompanyAction</tt> but the locale will be set to &quot;<tt>en</tt>&quot;.
</div>
<div class="Standard">
So my question is: Is it possible to teach Lift to retrieve the locale based on some uri-pattern, so that it will try to resolve my <tt>*.xhtml</tt> after the <tt>/{request_locale}</tt> part?
</div>
<div class="Standard">
<tt>/no/index.xhtml</tt>
</div>
<div class="Standard">
<tt>/en/index.xhtml</tt>
</div>
<div class="Standard">
Should then map to the same templates but with different locale.
</div>
<h2 class="Section">
<a name="toc-Section-18.2" class="toc">18.2</a> Solution
</h2>
<div class="Standard">
This is an ideal use of URL rewriting.
</div>
<div class="Standard">
You have to hook up the module in <tt>Boot.scala</tt> with: <tt>UrlLocalizer.init()</tt>.
</div>
<div class="Standard">
You can see a complete runnable example at <a href="https://github.com/dpp/starting_point/tree/localize_url" class="URL">DPP's GitHub Starting Point</a>.
</div>
<div class="Standard">
Here’s the code:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: scala">package code
package lib
​
import net.liftweb._
import http._
import provider._
import common._
​
import java.util.Locale
​
object UrlLocalizer {
  // capture the old localization function
  val oldLocalizeFunc = LiftRules.localeCalculator
​
  /**
   * What are the available locales?
   */
  val locales: Map[String, Locale] = 
    Map(Locale.getAvailableLocales.map(l =&gt; l.toString -&gt; l) :_*)
​
  object currentLocale extends RequestVar(Locale.getDefault)
​
  /**
   * Extract the locale
   */
  def unapply(in: String): Option[Locale] = 
    if (currentLocale.set_?) None // don’t duplicate
  else locales.get(in) // if it’s a valid locale, it matches
​
  /**
   * Calculate the Locale
   */
  def calcLocale(in: Box[HTTPRequest]): Locale = 
    if (currentLocale.set_?) currentLocale.get
  else oldLocalizeFunc(in)
​
  /**
   * Initialize the locale
   */
  def init() {
    // hook into Lift
    LiftRules.localeCalculator = calcLocale
​
    // rewrite requests with a locale at the head
    // of the path
    LiftRules.statelessRewrite.append {
      case RewriteRequest(ParsePath(UrlLocalizer(locale) :: rest,
                                    _, _, _), _, _) =&gt; {
        currentLocale.set(locale)
        RewriteResponse(rest)
      }
    }
  }
}
</pre>
</div>

</div>
<h1 class="Chapter">
<a name="toc-Chapter-19" class="toc">19</a> Embedding JavaScript in an HTML page
</h1>
<h2 class="Section">
<a name="toc-Section-19.1" class="toc">19.1</a> Problem
</h2>
<div class="Standard">
What am I doing wrong? I’m trying to output a javascript object into the page (so my front end guy can do some stuff with the data without parsing it out of elements by id) but it’s replacing all the double quotes with <tt>&amp;quot;</tt> (only in view source - if I inspect it then firebug converts them to double quotes again)
</div>
<div class="Standard">
I’ve copied the example from <span class="versalitas">Exploring Lift</span>, but it still does the same:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: scala">&amp; &quot;.data_as_object *&quot; #&gt; {
   JsCrVar(&quot;myObject&quot;, JsObj((&quot;persons&quot;, JsArray(
       JsObj((&quot;name&quot;, &quot;Thor&quot;), (&quot;race&quot;, &quot;Asgard&quot;)),
       JsObj((&quot;name&quot;, &quot;Todd&quot;), (&quot;race&quot;, &quot;Wraith&quot;)),
       JsObj((&quot;name&quot;, &quot;Rodney&quot;), (&quot;race&quot;, &quot;Human&quot;))
   ))))
</pre>
</div>

</div>
<div class="Standard">
Becomes:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: xml">&lt;div class=&quot;data_as_object&quot; style=&quot;display: none;&quot;&gt;var myObject =
{&amp;quot;persons&amp;quot;: [{&amp;quot;name&amp;quot;: &amp;quot;Thor&amp;quot;,
&amp;quot;race&amp;quot;: &amp;quot;Asgard&amp;quot;}, {&amp;quot;name&amp;quot;:
&amp;quot;Todd&amp;quot;, &amp;quot;race&amp;quot;: &amp;quot;Wraith&amp;quot;},
{&amp;quot;name&amp;quot;: &amp;quot;Rodney&amp;quot;, &amp;quot;race&amp;quot;:
&amp;quot;Human&amp;quot;}]
};&lt;/div&gt;
</pre>
</div>

</div>
<div class="Standard">
I’ve noticed that if what I’m outputting is a number rather than a string then it’s fine.
</div>
<h2 class="Section">
<a name="toc-Section-19.2" class="toc">19.2</a> Solution
</h2>
<div class="Standard">
Try:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: scala">&amp; &quot;.data_as_object *&quot; #&gt; {
   Script(JsCrVar(&quot;myObject&quot;, JsObj((&quot;persons&quot;, JsArray(
​
       JsObj((&quot;name&quot;, &quot;Thor&quot;), (&quot;race&quot;, &quot;Asgard&quot;)),
       JsObj((&quot;name&quot;, &quot;Todd&quot;), (&quot;race&quot;, &quot;Wraith&quot;)),
       JsObj((&quot;name&quot;, &quot;Rodney&quot;), (&quot;race&quot;, &quot;Human&quot;))
   )))))
</pre>
</div>

</div>
<div class="Standard">
<tt>JsExp</tt> are also <tt>Node</tt>s, so they render out, but they render out escaped. Putting <tt>Script()</tt> around them turns them into:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: xml">&lt;script&gt;
// &lt;![CDATA[
....
]]&gt;
&lt;/script&gt;
</pre>
</div>

</div>
<h1 class="Part">
<a name="toc-Part-III" class="toc">Part III.</a> Questions and Answers
</h1>
<h1 class="Chapter">
<a name="toc-Chapter-20" class="toc">20</a> <a name="cha:Scaling" class="Label"> </a>Scaling
</h1>
<div class="Standard">
Lift is a web framework built on the Scala programming language. Lift takes advantage of many of Scala’s features that allow developers to very concisely code secure, scalable, highly interactive web applications. Lift provides a full set of layered abstractions on top of HTTP and HTML from &quot;close to the metal&quot; REST abstractions up to transportation agnostic server push (Comet) support. Scala compiles to JVM byte-code and is compatible with Java libraries and the Java object model. Lift applications are typically deployed as WAR files in J/EE web containers... Lift apps run in Tomcat, Jetty, Glassfish, etc. just like any other J/EE web application. Lift apps can generally be monitored and managed just like any Java web app. Web Applications, Sessions, and State. All web applications are stateful in one way or another. Even a &quot;static&quot; web site is made up of the files that are served... the application’s state is defined in those files. The site content may be served out of a database, but the content served does not depend on identity of the user or anything about the HTTP request except the contents of the HTTP request. These contents can include the URI, parameters, and headers. The complete value of the response can be calculated from the request without referencing any resources except the content resources. For the purpose of this discussion, I will refer to these as session-less requests. News sites like the UK Guardian, MSNBC, and others are prototypical examples of this kind of site. Sessions. Some applications are customized on a user-by-user basis. These applications include the likes of Foursquare and others where many HTTP requests make up a &quot;session&quot; in which the results of previous HTTP requests change the behavior of future HTTP requests. Put in concrete terms, a user can log into a site and for some duration, the responses are specific to that user. There are many mechanisms for managing sessions, but the most common and secure method is creating a cryptographically unique token (a session id), and putting that token in the Set-Cookie response header such that the browser will present that Cookie in subsequent HTTP requests for a certain period of time. The server-side state is referenced by the Cookie and the state is made available to the web application during the scope of servicing the request and any mutations the web app makes to session state during the request are kept on the server and are available to the application in subsequent requests. Another available technique for managing state is to serialize application state in the Cookie and deliver it to the browser such that the server is not responsible for managing state across requests. As we’ve recently discovered, this is a tremendously insecure way to manage application state. Further, for any moderately complex application, the amount of data the needs to be transferred as part of each request and response is huge. Migratory Sessions. Many web application managers allow for server-managed sessions to migrate across a cluster of web application servers. In some environments such as Ruby on Rails, this is a hard requirement because only one request at a time can be served per process, thus for any moderate traffic site, there must be multiple processes serving pages. There are many strategies for migrating state across processes: storing state on disk, in memcached, in a database (relational or NoSQL), or having some proprietary cluster communications protocol. In any of these scenarios sessions can migrate across the grid of processes serving requests for a given web application. Web applications that support migratory state are often referred to as &quot;stateless&quot; because the session state does not reside in the same process as the web application. Session Affinity. Some applications require that all requests related to a particular session are routed to the same process and that process keeps session-related content in local memory. In a cluster, there are multiple mechanisms for achieving session affinity... the two most popular being HAProxy and Nginx. Availability, Scalability, Security, Performance, and User Experience. There are many vectors on which to measure the overall-quality of a web application. Let’s take a quick peek at each one. Availability. Availability of an application is the amount of time it gives a meaningful response to a request. Highly available applications generally span multiple pieces of hardware and often multiple data centers. Highly available applications are also typically available during upgrades of part of the system that makes up the application. Highly available applications have very few single points of failure and those single points of failure are usually deployed on very reliable hardware. Scalability. A scalable application can, within certain bounds, respond with similar performance to increased load by adding hardware to process more load. No system is infinitely or linearly scalable. However, many systems have grossly disproportionate load demands such that, for example, you can add a lot of web application front-ends to a Rails application before there’s enough load on the back-end RDBMS such that scaling is impaired.
</div>
<div class="Standard">
Security. The Internet is a dangerous place and no request that is received from the Internet can be trusted. Applications, frameworks, systems and everything else must be designed to be secure and resist attacks. The most common attacks on web application are listed in the OWASP Top Ten. Performance. Web application performance can be measured on two vectors: response time to a request and system resources required to service the request. These two vectors are inter-dependent. User Experience. The user experience of a web app is an important measure of its quality. User experience can be measured on many different vectors including perceived responsiveness, visual design, interactivity, lack of &quot;hicups&quot;, etc. Ultimately, because we’re building applications for users, the user experience is very important. Lift’s trade-offs. Given the number and complexity related to the quality of a web application, there are a lot of trade-offs, implicit and explicit, to building a framework that allows developers and business people to deliver a great user experience. Let’s talk for a minute about what Lift is and what it isn’t. Lift is a web framework. It provides a set of abstractions over HTTP and HTML such that developers can write excellent web applications. Lift is persistence agnostic. You can use Lift with relational databases, file systems, NoSQL data stores, mule carts, etc. As long as you can materialize an object into the JVM where Lift is running, Lift can make use of that object. Lift sits on top of the JVM. Lift applications execute in the Java Virtual Machine. The JVM is a very high performance computing system. There are raging debates as to the relative performance of JVM code and native machine code. No matter which benchmarks you look at, the JVM is a very fast performer. Lift apps take advantage of the JVM’s performance characteristics. Moderately complex Lift apps that access the database can serve 1,000+ requests per second on quad-core Intel hardware. Even very complex Lift apps that make many back-end calls per request can serve hundreds of requests per second on EC2 large instances. Lift as proxy. Many web applications, typically REST applications, provide a very thin layer on top of a backing data store. The web application serves a few basic functions to broker between the HTTP request and the backing store. These functions include: request and parameter validation, authentication, parameter unpacking, back-end service request, and translation of response data to wire format (typically XML or JSON). Lift can service these kinds of requests within the scope of a session or without any session at all, depending on application design. For more information on Lift’s REST features, see Lift RestHelper. When running these kinds of services, Lift apps can be treated without regard for session affinity. Lift as HTML generator. Lift has a powerful and secure templating mechanism. All Lift templates are expressed as valid XML and during the rendering process, Lift keeps the page in XML format. Pages rendered via Lift’s templating mechanism are generally resistant to cross site scripting attacks and other attacks that insert malicious content in rendered pages. Lift’s templating mechanism is designer friendly yet supports complex and powerful substitution rules. Further, the rendered page can be evaluated and transformed during the final rendering phase to ensure that all script tags are at the bottom of the page, all CSS tags are at the top, etc. Lift’s templating mechanism can be used to serve sessionless requests or serve requests within the context of a session. Further, pages can be marked as not requiring a session, yet will make session state available if the request was made in the context of a container session. Lift page rendering can even be done in parallel such that if there are long off-process components on the page (e.g., advertising servers), those components can be Sessionless Lift, forms and Ajax Lift applications can process HTML forms and process Ajax requests even if there’s no session associated with the request. Such forms and Ajax requests have to have stable field names and stable URLs, but this is the same requirement as most web frameworks including Struts, Rails, and Django impose on their applications. In such a mode, Lift apps have the similar characteristics to web apps written on tops of Struts, Play, JSF and other popular Java web frameworks. Lift as Secure, Interactive App Platform Lift features require session affinity: GUID to function mapping, type-safe SessionVars and Comet. Applications that take advantage of these features need to have requests associated with the JVM that stores the session. I’ll discuss the reason for this limitation, the down-side to the limitation, the downside to migratory session, and the benefits of these features. Application servers that support migratory sessions (sessions that are available to application servers running in multiple address spaces/processes) require a mechanism for transferring the state information between processes. This is typically (with the exception of Terracotta) done by serializing the stored data. Serialization is the process of converting rich data structures into a stream of bytes. Some of Scala’s constructs are hard or impossible to serialize. For example, local variables that are mutated within a closure are promoted from stack variables to heap variables. When those variables are serialized at different times, the application winds up with two references even though the references are logically the same. Lift makes use of many of these constructs (I’ll explain why next) and Lift’s use of these constructs makes session serialization and migration impossible. It also means that Lift’s type-safe SessionVars are not guaranteed to be serialized. One of the key Lift constructs is to map a cryptographically unique identifier in the browser to a function on the server. Lift uses Scala functions which close over scope, including all of the variables referenced by the function. This means that it’s not necessary to expose primary keys to the client when editing a record in the database because the primary key of the record or the record itself is known to the function on the server. This guards against OWASP Vulnerability A4, Insecure Object References as well as Replay Attacks. From the developer’s standpoint, writing Lift applications is like writing a VisualBasic application... the developer associates the user action with a function. Lift supplies the plumbing to bridge between the two. Lift’s GUID to function mapping extends to Lift’s Ajax support. Associating a button, checkbox, or other HTML element with an Ajax call is literally a single line: SHtml.ajaxButton(&lt;b&gt;PressMe&lt;/b&gt;, () =&gt; Alert(&quot;You pressed a button at &quot;+Helpers.currentTimeFormatted) Lift’s Ajax support is simple, maintainable, and secure. There’s no need to build and maintain routing. Lift has the most advanced server-push/Comet support of any web framework or any other system currently available. Lift’s comet support relies on session affinity. Lift’s comet support associates an Actor with a section of screen real estate. A single browser window may have many pieces of screen real estate associated with many of Lift’s CometActors. When state changes in the Actor, the state change is pushed to the browser. Lift takes care of multiplexing a single HTTP connection to handle all the comet items on a given page, the versioning of the change deltas (if the HTTP connection is dropped while 3 changes become available, all 3 of those changes are pushed when the next HTTP request is made.) Further, Lift’s comet support will work the same way once web sockets are available to the client and server... there will be no application code changes necessary for web sockets support. Lift’s comet support requires that the connect is made from the browser back to the same JVM in which the CometActors are resident... the same JVM where the session is located.
</div>
<div class="Standard">
The downside to Lift’s session affinity requirement mainly falls on the operations team. They must use a session aware load balancer or other mechanism to route incoming requests to the server that the session is associated with. This is easily accomplished with HAProxy and Nginx. Further, if the server running a given session goes down, the information associated with that session is lost (note that any information distributed off-session [into a database, into a cluster of Akka actors, etc.] is preserved.) But, Lift has extended session facilities that support re-creation of session information in the event of session lost. Lift also has heart-beat functionality so that sessions are kept alive as long as a browser page is open to the application, so user inactivity will not result in session timeouts.
</div>
<div class="Standard">
Compared to the operational cost of a session aware load balancer, there are many costs associated with migratory sessions. First, there must be a persistence mechanism for those sessions. Memcached is an unreliable mechanism as memcached instances have no more stability than the JVM which hosts the application and being a cache, some sessions may get expired. Putting session data in backing store such as MySQL or Cassandra increases the latency of requests. Further, the costs of serializing state, transmitting the state across the network, storing it, retrieving it, transmitting it across the network, and deserializing it all costs a lot of cycles and bandwidth. When your Lift application scales beyond a single server, beyond 100 requests per second, the costs of migrating state on every request becomes a significant operational issue.
</div>
<div class="Standard">
Session serialization can cause session information loss in the case of multiple requests being executed in multiple processes. It’s common to have multiple tabs/windows open to the same application. If session data is serialized as a blob and two different requests from the same server are being executed at the same time, the last request to write session data into the store will over-write the prior session data. This is a concurrency problem and can lead to hard to debug issues in production because reproducing this kind of problem is non-trivial and this kind of problem is not expected by developers.
</div>
<div class="Standard">
The third issue with migratory sessions and session serialization is that the inability to store complex information in the session (e.g., a function that closes over scope) means that the developer has to write imperative code to serialize session state to implement complex user interactions like multi-screen wizards (which is a 400 line implementation in Lift). These complex, hand written serializations are error prone, can introduce security problems and are non-trivial to maintain.
</div>
<div class="Standard">
The operational costs of supporting session affinity are not materially different from the operational costs of providing backing store for migratory sessions. On the other hand, there are many significant downsides to migratory sessions. Let’s explore the advantages of Lift’s design.
</div>
<div class="Standard">
Lift’s use of GUIDs associated with functions on the server: Increase the security of the application by guarding against cross site request forgeries, replay attacks, and insecure object references Decrease application development and maintenance time and costs Increase application interactivity, thus a much better user experience Increase in application richness because of simpler Ajax, multi-page Wizards, and Comet Improved application performance because fewer cycles are spent serializing and transmitting session information No difference in scalability... just add more servers to the front end to scale the front end of your application The positive attributes of Lift’s design decisions are evident at Foursquare which handles thousands of requests per second all served by Lift. There are very few sites that have more traffic than Foursquare. They have scaled their web front end successfully and securely with Lift. Other high volume sites including Novell are successfully scaling with Lift. If you are scaling your site, there are also commercial Lift Cloud manager tools that can help manage clusters of Lift’s session requirements. Conclusion Lift provides a lot of choices for developing and deploying complex web applications. Lift can operate in a web container like any other Java web framework. If you choose to use certain Lift features and you are deploying across multiple servers, you need to have a session aware load balancer. Even when using Lift’s session-affinity dependent features, Lift applications have higher performance, identical availability, identical scalability, better security, and better user experience than applications written with web frameworks such as Ruby on Rails, Struts, and GWT.
</div>
<h1 class="Chapter">
<a name="toc-Chapter-21" class="toc">21</a> How Lift does function/GUID mapping
</h1>
<h1 class="Chapter">
<a name="toc-Chapter-22" class="toc">22</a> How Lift does Comet
</h1>
<div class="Standard">
I can speak to Lift’s Comet Architecture which was selected by Novell to power their Pulse product after they evaluated a number of different technologies.
</div>
<div class="Standard">
Lift’s Comet implementation uses a single HTTP connection to poll for changes to an arbitrary number of components on the page. Each component has a version number. The long poll includes the version number and the component GUID. On the server side, a listener is attached to all of the GUIDs listed in the long poll requests. If any of the components has a higher version number (or the version number increases during the period of the long poll), the deltas (a set of JavaScript describing the change from each version) is sent to the client. The deltas are applied and the version number on the client is set to the highest version number for the change set.
</div>
<div class="Standard">
Lift integrates long polling with session management so that if a second request comes into the same URL during a long poll, the long poll is terminated to avoid connection starvation (most browsers have a maximum of 2 HTTP connections per named server). Lift also supports DNS wild-carded servers for long poll requests such that each tab in the browser can do long polling against a different DNS wildcarded server. This avoids the connection starvation issues.
</div>
<div class="Standard">
Lift dynamically detects the container the Servlet is running in and on Jetty 6 &amp; 7 and (soon) Glassfish, Lift will use the platform’s &quot;continuations&quot; implementation to avoid using a thread during the long poll.
</div>
<div class="Standard">
Lift’s JavaScript can sit on top of jQuery and YUI (and could sit on top of Prototype/Scriptaculous as well.) The actual polling code includes back-off on connection failures and other &quot;graceful&quot; ways of dealing with transient connection failures.
</div>
<div class="Standard">
I’ve looked at Atmosphere and CometD (both JVM-oriented Comet technologies). Neither had (at the time I evaluated them) support for multiple components per page or connection starvation avoidance.
</div>
<div class="Standard">

</div>
<h1 class="Chapter">
<a name="toc-Chapter-23" class="toc">23</a> Advanced Concepts
</h1>
<h2 class="Section">
<a name="toc-Section-23.1" class="toc">23.1</a> <a name="sec:Snippet-Resolution" class="Label"> </a>Snippet Resolution
</h2>
<div class="Standard">
Lift snippets transform markup to dynamic content. The are functions that transform <tt>NodeSeq =&gt; NodeSeq</tt>.
</div>
<div class="Standard">
Snippets can be invoked from templates via tags:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: xml">&lt;lift:surround with=&quot;default&quot; at=&quot;content&quot;&gt;
  &lt;p&gt;
    You have reached this page, but you can only get here if you’ve logged in
    first.
  &lt;/p&gt;
&lt;/lift:surround&gt;
</pre>
</div>

</div>
<div class="Standard">
or via class attributes.
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: xml">&lt;p class=&quot;lift:surround?with=default;at=content&quot;&gt;
  You have reached this page, but you can only get here if you’ve logged in
  first.
&lt;/p&gt;
</pre>
</div>

</div>
<div class="Standard">
In both cases, the surround (See <a href="#sec:Surround" class="Reference">↑</a>) snippet will be invoked with attribute <tt>with</tt> set to <tt>default</tt> and <tt>at</tt> set to <tt>content</tt>. The parameter passed to the surround <tt>NodeSeq =&gt; NodeSeq</tt> function is:
</div>
<div class="Standard">
<div class="listing">
<pre class="listing brush: xml">&lt;p&gt;
  You have reached this page, but you can only get here if you’ve logged in
  first.
&lt;/p&gt;
</pre>
</div>

</div>
<div class="Standard">
Lift will resolve from the snippet name to a function in the following steps.
</div>
<h3 class="Subsection">
<a name="toc-Subsection-23.1.1" class="toc">23.1.1</a> <tt>LiftSession.liftTagProcessing</tt>
</h3>
<div class="Standard">
Lift consults a <tt>List[PartialFunction[(String, Elem, MetaData, NodeSeq, String), NodeSeq]]</tt> located in LiftSession.liftTagProcessing for the rules to use to evaluate the snippet name, attributes, etc. into the resulting <tt>NodeSeq</tt>. <tt>LiftSession.liftTagProcessing</tt> is the result of <tt>LiftRules.liftTagProcessing</tt> or else the default Lift tag processor. If you need special snippet resolution mechanisms, you can place them in <tt>LiftRules.liftTagProcessing</tt>. By default, the snippets get processed by <tt>LiftSession.processSnippet.</tt>
</div>
<h3 class="Subsection">
<a name="toc-Subsection-23.1.2" class="toc">23.1.2</a> <tt>LiftRules.liftTagProcessing</tt>
</h3>
<div class="Standard">
<tt>LiftRules.liftTagProcessing</tt> looks for the <tt>form</tt> attribute and sets the <tt>isForm</tt> variable. Next, Lift determines if the contents of the snippet should be evaluated eagerly by looking for one of <tt>eager_eval</tt>, <tt>l:eager_eval</tt>, or <tt>lift:eager_eval</tt> attributes.
</div>
<div class="Standard">
If the snippet is an eager evaluation, the child tags will be evaluated for any snippets.
</div>
<div class="Standard">
Either the originally passed children or the eagerly evaluated children will be referred to as children in the next section.
</div>
<h3 class="Subsection">
<a name="toc-Subsection-23.1.3" class="toc">23.1.3</a> Snippet name resolution
</h3>
<div class="Standard">
Lift looks for the named snippet in the following locations in order:
</div>
<ul>
<li>
<tt>S.locateMappedSnippet</tt> - the complete snippet name without any camel or snake application is used to look up a <tt>NodeSeq =&gt; NodeSeq</tt> in within the scope of the current extended request<span class="FootOuter"><span class="SupFootMarker"> [G] </span><span class="HoverFoot"><span class="SupFootMarker"> [G] </span>For the purposes of this discussion, the extended request is the scope of a <tt>RequestVar</tt>. This is the scope of a full page render plus any subsequent Ajax operations that originate from that page. This means that a snippet may be registered using <tt>S.mapSnippet</tt> during page rendering and the same snippet function with the same scope binding will be used by any Ajax commands.</span></span>. Snippets may be registered using <tt>S.mapSnippet</tt>. 
</li>
<li>
<tt>SiteMap</tt> <tt>Loc</tt> snippet - the current <tt>SiteMap</tt> <tt>Loc</tt> (<tt>S.location</tt>) will be queried to see if it has a <tt>NodeSeq =&gt; NodeSeq</tt> that matches the current snippet name (<tt>loc.snippet(snippetName)</tt>).
</li>
<li>
<tt>LiftRules.snippets</tt> - next, the snippet name is split at the ’.’ character to determine the snippet name and snippet method name. The <tt>snippets</tt> <tt>RulesSeq</tt> is tested for a match between the <tt>List[String]</tt> that results from splitting the name at the period and <tt>NodeSeq =&gt; NodeSeq</tt>.
</li>
<li>
If the above mechanisms do not result in a NodeSeq =&gt; NodeSeq, Lift looks for a <tt>Class</tt> that matches the name.<ul>
<li>
<tt>S.snippetForClass</tt> - is checked to see if a <tt>Class</tt> has been associated with the snippet name. If none is found...
</li>
<li>
<tt>LiftRules.snippetDispatch</tt> is checked to see if theres an instance of <tt>DispatchSnippet</tt> that matches to snippet name. Lift’s built-in snippets are registered with <tt>LiftRules.snippetDispatch</tt>. If there’s no match...
</li>
<li>
Lift tries reflection to find a matching class name (note that Lift will try camel case and snake case for class names, so the <tt>foo_bar</tt> snippet will match the class <tt>foo_bar</tt> as well as <tt>FooBar</tt>). Lift looks for classes in the <tt>snippet</tt> subpackage of all the packages added via <tt>LiftRules.addToPackages</tt>. So if you call <tt>LiftRules.addToPackages(&quot;foo.bar&quot;)</tt> in <tt>Boot.scala</tt>, then Lift will search for the classes <tt>foo.bar.snippet.foo_bar</tt> and <tt>foo.bar.snippet.FooBar</tt>.
</li>
<li>
Once the class is found, Lift will try to instantiate the class the following ways:<ul>
<li>
Lift will look at the current location (<tt>S.location</tt>) and if the parameter type of the <tt>Loc</tt> is not <tt>Unit</tt>, Lift get the current parameter and look for a constructor that matches the current parameter type or <tt>Box</tt> of current parameter type (and superclasses of both). If there’s a match the constructor will be called with the parameters. For example, if the current page is a <tt>Loc[Dog]</tt> and <tt>Dog</tt> is a subclass of <tt>Animal</tt>, the following constructors will match:<ul>
<li>
<tt>class MySnippet(dog: Dog)</tt>
</li>
<li>
<tt>class MySnippet(animal: Animal)</tt>
</li>
<li>
<tt>class MySnippet(dog: Box[Dog])</tt>
</li>
<li>
<tt>class MySnippet(animal: Box[Animal])</tt>
</li>
<li>
<tt>class MySnippet(dog: Dog, session: LiftSession)</tt>
</li>
<li>
<tt>class MySnippet(animal: Animal, session: LiftSession)</tt>
</li>
<li>
<tt>class MySnippet(dog: Box[Dog], session: LiftSession)</tt>
</li>
<li>
<tt>class MySnippet(animal: Box[Animal], session: LiftSession)</tt>
</li>

</ul>

</li>
<li>
If a typed constructor cannot be found, try the zero argument constructor;
</li>
<li>
If the zero argument constructor cannot be found, try to treat the <tt>Class</tt> as a Scala <tt>object</tt> singleton and get the instance that the singleton refers to.
</li>

</ul>

</li>
<li>
Once we’ve got an instance of the potential snippet handling class:<ul>
<li>
If it’s a <tt>StatefulSnippet</tt>, register with <tt>S.overrideSnippetForClass</tt>;
</li>
<li>
Update the <tt>LiftSession</tt> <tt>snippetMap</tt> <tt>RequestVar</tt> so subsequent references to the snippet during the same extended request uses same instance (that way if any instance variables are set on the class instance, they are picked up by subsequent accesses to the same snippet);
</li>
<li>
Next, Lift attempts to invoke the snippet method. If no explicit method is given, the <tt>render</tt> method is used.<ul>
<li>
Stateful and Dispatch use <tt>dispatch</tt> method to find the <tt>NodeSeq =&gt; NodeSeq</tt>
</li>
<li>
Non-dispatch, do the following method lookup:
</li>
<li>
method that takes no parameters and returns <tt>CssBindFunc</tt>, <tt>NodeSeq =&gt; NodeSeq</tt>, invoke the method and apply the function to the children; or
</li>
<li>
try to invoke the named method with <tt>Group(children)</tt> (<tt>NodeSeq</tt> signature) or invoke it with no parameters. If the return value is <tt>NodeSeq</tt>, <tt>Node</tt>, or <tt>Seq[Node]</tt>, then it was successful.
</li>

</ul>

</li>

</ul>

</li>

</ul>

</li>

</ul>
<h3 class="Subsection">
<a name="toc-Subsection-23.1.4" class="toc">23.1.4</a> Post-processing of results
</h3>
<ul>
<li>
LiftRules.snippetDispatch (built in snippets registered here)
</li>

</ul>
<div class="Standard">
parallel snippets
</div>
<h2 class="Section">
<a name="toc-Section-23.2" class="toc">23.2</a> <a name="sec:The-Merging-Phase" class="Label"> </a>The Merging Phase
</h2>
<h1 class="Part">
<a name="toc-Part-IV" class="toc">Part IV.</a> Misc
</h1>
<h1 class="Chapter">
<a name="toc-Chapter-24" class="toc">24</a> Releases
</h1>
<div class="Standard">

</div>
<h2 class="Section">
<a name="toc-Section-24.1" class="toc">24.1</a> Lift 2.2-RC1
</h2>
<h2 class="Date">
December 8, 2010
</h2>
<div class="Standard">
The <a href="http://liftweb.net/" class="URL">Lift</a> team is pleased to announce <a href="http://liftweb.net/download.html" class="URL">Lift 2.2-RC1</a>. In the month since the 2.2-M1 release, the team has closed 53 tickets and made significant improvements to Lift based on <a href="http://groups.google.com/group/liftweb" class="URL">community</a> feedback.
</div>
<div class="Standard">
Lift is an elegant, expressive framework that allows any size team build and maintain secure, highly interactive, scalable web applications quickly and efficiently. Lift is built on <a href="http://scala-lang.org" class="URL">Scala</a> and compiles to JVM byte-code. Lift applications deploy as WAR files on popular application servers and web containers including Jetty, Glassfish and Tomcat. Lift applications can be monitored and managed with the same proven infrastructure used to manage and monitor any Java web application. Lift is open source licensed under an Apache 2.0 license.
</div>
<h3 class="Subsection-">
<a name="toc-Subsection--1" class="toc"/>Lift features include:
</h3>
<ul>
<li>
Community... the Lift community is 2,400 members strong, super-active and always there to help with questions
</li>
<li>
Best Comet (server-push) support that allows the creation of dynamic application such as <a href="http://vibe.novell.com" class="URL">Novell Vibe</a>
</li>
<li>
Super simple Ajax for creating highly interactive web applications without worrying about HTTP plumbing
</li>
<li>
Secure by default... Lift apps are resistant to the OWASP top 10 vulnerabilities including XSS, XSRF, and parameter tampering
</li>
<li>
Concise and Maintainable... Lift apps typically contain fewer lines of code than corresponding Rails apps, yet are type safe so that many errors are flagged by the compiler
</li>
<li>
Scalable... Lift apps scale to millions of users across many servers, yet are highly efficient for single-box implementations
</li>
<li>
Compatible... Lift apps can take advantage of any Java library as well as the growing collection of Scala libraries
</li>

</ul>
<h3 class="Subsection-">
<a name="toc-Subsection--2" class="toc"/>Lift 2.2-RC1 improvements include:
</h3>
<ul>
<li>
HTML5 Support: Lift supports parsing HTML5 input files and rendering HTML5 to the browser in addition to Lift’s XHTML support
</li>
<li>
<a href="http://demo.liftweb.net/invoice_wiring" class="URL">Wiring</a>: Spreadsheets meet web application yielding an automatic mechanism for updating dependent elements on a page, making it even easier to build dynamic apps with Lift
</li>
<li>
Wizard and Screen Improvements: Build complex screens more easily with new helper methods for creating form elements and improved life-cycle callbacks
</li>
<li>
<a href="http://stable.simply.liftweb.net/#sec:CSS-Selector-Transforms" class="URL">CSS Selector Transforms</a> Improvements: including appending attributes, multiple selectors applying to a single element, and element lifting
</li>
<li>
Support for migratory sessions: <tt>ContainerVars</tt> provide type-safe, guaranteed serializable session variables that can migrate across application servers in a cluster
</li>
<li>
Improved i18n: including per-page localization strings and localization strings and HTML stored in templates rather than Java resource files which makes editing much easier
</li>
<li>
Security Improvements: including creation of new sessions on login
</li>
<li>
MongoDB Improvements: performance improvements as well as new features
</li>
<li>
Support for Scala 2.8.1 as well as 2.8.0 and 2.7.7
</li>
<li>
ProtoUser support for Record: Lift’s <tt>ProtoUser</tt> and <tt>CRUDify</tt> can be used on Record-based persistence classes as well as Mapper-based persistence classes
</li>
<li>
Squeryl integration improvements: Lift is updated to use the latest version of Squeryl
</li>

</ul>
<h3 class="Subsection-">
<a name="toc-Subsection--3" class="toc"/>Lift-powered sites include:
</h3>
<ul>
<li>
<a href="http://foursquare.com/" class="URL">Foursquare</a>: the multi-million user location based service that services millions of check-ins a day on their Lift-powered system
</li>
<li>
<a href="http://vibe.novell.com" class="URL">Novell Vibe</a>: enterprise collaboration software platform based on Google Wave
</li>
<li>
<a href="http://innovationgames.com/" class="URL">Innovation Games</a>: The fun way to do serious business — seriously
</li>
<li>
<a href="http://www.xmpie.com/" class="URL">Xerox/XMPie</a>: the leading provider of software for cross-media, variable data one-to-one marketing
</li>
<li>
<a href="http://exchango.com/" class="URL">Exchango</a>: The easy and convenient way to give and get free stuff.
</li>
<li>
<a href="http://snapsort.com/" class="URL">Snapsort</a>: Compare and decide on cameras
</li>
<li>
<a href="http://nofouls.com/" class="URL">No Fouls</a>: Find pickup basketball games
</li>

</ul>
<div class="Standard">
Please join the Lift community and help use grow Lift. And a super-big thanks to the 30+ Lift committers who have grown the Lift community and code-base to what it is today... and what it will be in the future!
</div>
<div class="Standard">

</div>
<h2 class="Section">
<a name="toc-Section-24.2" class="toc">24.2</a> Lift 2.2
</h2>
<h2 class="Date">
January 5, 2011
</h2>
<div class="Standard">
The <a href="http://liftweb.net/" class="URL">Lift</a> team is pleased to announce <a href="http://liftweb.net/download.html" class="URL">Lift 2.2</a>. In the three months since the 2.1 release, the team has closed over 100 tickets and made significant improvements to Lift based on <a href="http://groups.google.com/group/liftweb" class="URL">community</a> feedback.
</div>
<div class="Standard">
Lift is an elegant, expressive framework that allows any size team build and maintain secure, highly interactive, scalable web applications quickly and efficiently. Lift is built on <a href="http://scala-lang.org" class="URL">Scala</a> and compiles to JVM byte-code. Lift applications deploy as WAR files on popular application servers and web containers including Jetty, Glassfish and Tomcat. Lift applications can be monitored and managed with the same proven infrastructure used to manage and monitor any Java web application. Lift is open source licensed under an Apache 2.0 license.
</div>
<h3 class="Subsection-">
<a name="toc-Subsection--4" class="toc"/>Lift features include:
</h3>
<ul>
<li>
Community... the Lift community is 2,400 members strong, super-active and always there to help with questions
</li>
<li>
Best Comet (server-push) support that allows the creation of dynamic application such as <a href="http://vibe.novell.com" class="URL">Novell Vibe</a>
</li>
<li>
Super simple Ajax for creating highly interactive web applications without worrying about HTTP plumbing
</li>
<li>
Secure by default... Lift apps are resistant to the OWASP top 10 vulnerabilities including XSS, XSRF, and parameter tampering
</li>
<li>
Concise and Maintainable... Lift apps typically contain fewer lines of code than corresponding Rails apps, yet are type safe so that many errors are flagged by the compiler
</li>
<li>
Scalable... Lift apps scale to millions of users across many servers, yet are highly efficient for single-box implementations
</li>
<li>
Compatible... Lift apps can take advantage of any Java library as well as the growing collection of Scala libraries
</li>

</ul>
<h3 class="Subsection-">
<a name="toc-Subsection--5" class="toc"/>Lift 2.2 improvements include:
</h3>
<ul>
<li>
HTML5 Support: Lift supports parsing HTML5 input files and rendering HTML5 to the browser in addition to Lift’s XHTML support
</li>
<li>
<a href="http://demo.liftweb.net/invoice_wiring" class="URL">Wiring</a>: Spreadsheets meet web application yielding an automatic mechanism for updating dependent elements on a page, making it even easier to build dynamic apps with Lift
</li>
<li>
Wizard and Screen Improvements: Build complex screens more easily with new helper methods for creating form elements and improved life-cycle callbacks
</li>
<li>
<a href="http://stable.simply.liftweb.net/#sec:CSS-Selector-Transforms" class="URL">CSS Selector Transforms</a> Improvements: including appending attributes, multiple selectors applying to a single element, and element lifting
</li>
<li>
Support for migratory sessions: <tt>ContainerVars</tt> provide type-safe, guaranteed serializable session variables that can migrate across application servers in a cluster
</li>
<li>
Improved i18n: including per-page localization strings and localization strings and HTML stored in templates rather than Java resource files which makes editing much easier
</li>
<li>
Security Improvements: including creation of new sessions on login
</li>
<li>
MongoDB Improvements: performance improvements as well as new features
</li>
<li>
Support for Scala 2.8.1 as well as 2.8.0 and 2.7.7
</li>
<li>
ProtoUser support for Record: Lift’s <tt>ProtoUser</tt> and <tt>CRUDify</tt> can be used on Record-based persistence classes as well as Mapper-based persistence classes
</li>
<li>
Squeryl integration improvements: Lift is updated to use the latest version of Squeryl
</li>
<li>
<a href="http://www.assembla.com/wiki/show/liftweb/Designer_Friendly_Templates" class="URL">Designer-friendly templates</a>
</li>
<li>
<a href="http://www.assembla.com/wiki/show/liftweb/Stateless_Requests" class="URL">Stateless rendering</a>including the HTML pipeline
</li>
<li>
<a href="http://www.assembla.com/wiki/show/liftweb/MVC_%28if_you_really_want_it%29" class="URL">Support for MVC-style development</a>
</li>

</ul>
<h3 class="Subsection-">
<a name="toc-Subsection--6" class="toc"/>Lift-powered sites include:
</h3>
<ul>
<li>
<a href="http://foursquare.com/" class="URL">Foursquare</a>: the multi-million user location based service that services millions of check-ins a day on their Lift-powered system
</li>
<li>
<a href="http://vibe.novell.com" class="URL">Novell Vibe</a>: enterprise collaboration software platform based on Google Wave
</li>
<li>
<a href="http://innovationgames.com/" class="URL">Innovation Games</a>: The fun way to do serious business — seriously
</li>
<li>
<a href="http://www.xmpie.com/" class="URL">Xerox/XMPie</a>: the leading provider of software for cross-media, variable data one-to-one marketing
</li>
<li>
<a href="http://exchango.com/" class="URL">Exchango</a>: The easy and convenient way to give and get free stuff.
</li>
<li>
<a href="http://snapsort.com/" class="URL">Snapsort</a>: Compare and decide on cameras
</li>
<li>
<a href="http://nofouls.com/" class="URL">No Fouls</a>: Find pickup basketball games
</li>

</ul>
<div class="Standard">
Please join the Lift community and help use grow Lift. And a super-big thanks to the 30+ Lift committers who have grown the Lift community and code-base to what it is today... and what it will be in the future!
</div>
<a name="Index" class="toc"/><h1 class="index">Index</h1><p class="printindex">
<a name="index-MVC" class="printindex"/>MVC: <a href="#entry-MVC-0" class="IndexArrow">↑</a>
</p>
          <p class="bottom">(C) 2012 David Pollak</p>    </div>    <script type="text/javascript">SyntaxHighlighter.all()</script>  </body>
        
note: this error is displayed in the browser because your application is running in "development" or "test" mode.If you set the system property run.mode=production, this error will not be displayed, but there will be errors in the output logs.