Question

Right now I'm just using params function to get the data that has been posted to an URL.

Is there any other way to deal with forms in Scalatra like in Play Framework? Does Scalatra support an object that can both be used to create a form and fill the form automatically?

Was it helpful?

Solution

Scalatra doesn't provide such a complex feature. It's not complex in the sense that it's difficult to implement, its complexity derives from the number of parties playing together.

First of all, you'd need a Model to represent objects in your domain, and Scalatra doesn't provide any model library by default. This model is then used by the runtime to convert arbitrary strings set in the HTTP request to an instance of some model. For example

  • if the request is a GET and specifies a parameter like user.id, the binding software converts this string to an object of type User, found in the database by its ID.
  • if the request is a POST, specifies three parameters like user.name, user.password and user.birthday and does not specify a user.id, the runtime builds an object of type User that is ready to be put in the DB with a simple User.save() - provided if passed the validation, if any, specified in the User class
  • if the request is a PUT (or equivalent as explained in the Scalatra docs) and contains user.id and user.birthday, first an User is retrieved by ID, then its birthday is updated and finally is made available to your controller, ready to call User.save()

As you can see, this requires a model library, a binding library, and glue support in the runtime.

To generate the HTML form, you need a helper library that can inspect a model and output the HTML bits for you. For example, your library inspects the User class, detects that it has three public fields name, password and birthday, and, according to the convention of using <model>.<property> as the inputs' names, outputs

<form action="$$$$" method="$$$$">
  <input name="user.name" />
  <input name="user.password" />
  <input name="user.birthday" />
  <input type="submit" />
</form>

Note that

  • the URL and the method can only be filled after some context is learned (for example routes)
  • the same naming convention must be used by the binding library to deserialize a User object submitted by this form
  • etc.

Once you have all the pieces put together, you have made up an MVC framework, so what's the point in using a tiny, RESTful software like Scalatra?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top