Is there a good way to deal with form submission in Scalatra
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?
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 likeuser.id
, the binding software converts this string to an object of typeUser
, found in the database by its ID. - if the request is a
POST
, specifies three parameters likeuser.name
,user.password
anduser.birthday
and does not specify auser.id
, the runtime builds an object of typeUser
that is ready to be put in the DB with a simpleUser.save()
- provided if passed the validation, if any, specified in theUser
class - if the request is a
PUT
(or equivalent as explained in the Scalatra docs) and containsuser.id
anduser.birthday
, first anUser
is retrieved by ID, then its birthday is updated and finally is made available to your controller, ready to callUser.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?