-
Notifications
You must be signed in to change notification settings - Fork 0
JavaForms
The play.data package contains several helpers to handle HTTP form data submission and validation. The easiest way to handle a form submission is to define a play.data.Form that wraps an existing class:
public class User {
public String email;
public String password;
}Form<User> userForm = form(User.class);Note: The underlying binding is done using Spring data binder.
This form can generate a User result value from HashMap<String,String> data:
Map<String,String> anyData = new HashMap();
anyData.put("email", "bob@gmail.com");
anyData.put("password", "secret");
User user = userForm.bind(anyData).get();If you have a request available in the scope, you can bind directly from the request content:
User user = userForm.bindFromRequest().get();You can define additional constraints that will be checked during the binding phase using JSR-303 (Bean Validation) annotations:
public class User {
@Required
public String email;
public String password;
}Tip: The
play.data.validation.Constraintsclass contains several built-in validation annotations.
You can also define an ad-hoc validation by adding a validate method to your top object:
public class User {
@Required
public String email;
public String password;
public String validate() {
if(authenticate(email,password) == null) {
return "Invalid email or password";
}
return null;
}
}Of course if you can define constraints, then you need to be able to handle the binding errors.
if(userForm.hasErrors()) {
return badRequest(form.render(userForm));
} else {
User user = userForm.get();
return ok("Got user " + user);
}Sometimes you’ll want to fill a form with existing values, typically for editing:
userForm.fill(new User("bob@gmail.com", "secret"))- HTTP programming
- Asynchronous HTTP programming
- The template engine
- HTTP form submission and validation
- Working with JSON
- Working with XML
- Handling file upload
- Accessing an SQL database
- Using the Cache
- Calling WebServices
- Integrating with Akka
- Internationalization
- The application Global object
- Testing your application