Up: Chapter 4

4.1 Old Fashioned Dumb Forms

Let’s take a look at the HTML for a form:
<div id="main" class="lift:surround?with=default&at=content">
    This is the simplest type of form processing... plain old
    mechanism of naming form elements and processing the form elements
    in a post-back.
    <form action="/dumb" method="post" class="lift:DumbForm">
      Name: <input name="name"><br>
      Age: <input name="age"><br>
      <input type="submit" value="Submit">
Okay... looks pretty normal... we define a form. The only thing we do is associate the behavior with the form with the class="lift:DumbForm" attribute on the <form> tag. The page is a post-back which means that the form is posted to the same URL that served the original content.
Let’s see the code to process the form:
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 <- S.request if r.post_? // make sure it's a post
      name <- S.param("name") // get the name field
      age <- S.param("age") // get the age field
    } {
      // if everything goes as expected,
      // display a notice and send the user
      // back to the home page
      S.notice("Name: "+name)
      S.notice("Age: "+age)
    // pass through the HTML if we don't get a post and
    // all the parameters
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.
There are plenty of reasons not to do things this way.
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.
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.
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.
Lift provides you with much more powereful and secure mechanisms for dealing with HTML forms.
Up: Chapter 4

(C) 2012 David Pollak