Playframework(4)Java Project and Handling form Submission
4. Handling Form Submission
Defining a form
play.data.Form just defining the form with a class
public class User{
public String email;
public String password;
}
Form<User> userForm = form(User.class);
It works using Spring data binder.
Map<String, String> anyData = new HashMap();
anyData.put("email","
[email protected]");
anyData.put("password","111111");
User user = userForm.bind(anyData).get();
If we have a request available in the scope, we can bind directly from the request content:
User user = userForm.bindFromRequest().get();
Defining Constraints
JSR-303(Bean Validation) annotations:
…snip…
@Required
public String email;
…snip...
We can also define an ad-hoc validation by adding a validate method to my top object:
public class User{
…snip…
public String validate(){
…snip...
}
}
Handling binding failure
if(userForm.hasErrors()){
...
}else{
...
}
Filling a form with initial default values
userForm = userForm.fill(new User("email address","password"));
Register a custom DataBinder
Formatters.register(LocalTime.class, new SimpleFormatter<LocalTime>()
Form Template Helpers in templates
@(myForm: Form[User])
@helper.form(action = routes.Application.submit()){
@helper.inputText(myForm("username"))
@helper.inputPassword(myForm("password"))
}
There is Field constructors and we can write our own.
5. Handling and serving JSON requests
Handling a JSON request
A JSON request is an HTTP request using a valid JSON payload as request body. Its Content-Type header must specify the text/json or application/json MIME type.
public static index sayhi(){
JsonNode json = request().body().asJson();
…snip…
String name = json.findPath("name").getTextValue();
}
We can verify JSON request via cURL
>curl
--header "Content-type: application/json"
--request POST
--data '{"name": "Carl" }'
http://localhost:9000/sayhi
curl is a amazing tool to verify JSON REST API from command line.
Serving a JSON response
We will not only handle a JSON request, but also send back a valid JSON HTTP response.
@BodyParser.Of(Json.class)
public static index sayhi(){
JsonNode json = request().body().asJson();
ObjectNode result = Json.newObject();
String name = json.findPath("name").getTextValue();
…snip…
result.put("status", "OK");
result.put("message", "Hello " + name);
return ok(result);
}
6. Working with XML
An XML request is an HTTP request using a valid XML payload as request body. It should specify the text/xml MIME type in its Content-Type header.
org.w3c.Document
public static index sayhi(){
Document dom = request().body().asXml();
…snip…
String name = XPath.selectText("//name", dom);
…snip...
}
Or
@BodyParser.Of(Xml.class)
public static index sayhi(){
String name = XPath.selectText("//name", dom);
…snip...
}
Play with cURL
>curl
--header "Content-type: text/xml"
--request POST
--data '<name>Sillycat</name>'
http://localhost:9000/sayhi
Serving an XML response
@BodyParser.Of(Xml.class)
public static index sayhi(){
String name = XPath.selectText("//name", dom);
return ok("<message \"status\"=\"ok\">Hello " + name + "</message>");
}
7 Handling file Upload
Uploading files in a form using multipart/form-data
The special multipart/form-data encoding allows to mix standard form data with file attachments.
@form(action = routes.Application.upload, enctype -> "multipart/form-data"){
<input type="file" name="picture">
<p><input type="submit"></p>
}
Actions to fetch the data from form.
public static Result upload(){
MultipartFormData body = request().body().asMultipartFormData();
FilePart picture = body.getFile("picture");
if(picture != null){
String fileName = picture.getFilename();
String contentType = picture.getContentType();
File file = picture.getFile();
return ok("File upload");
}
}
Direct file upload
Another way to send files to the server is to use ajax to upload files asynchronously from a form. The request body will not be encoded as multipart/form-data. It will contain the plain file contents.
public static Request upload(){
File file = request().body().asRaw().asFile();
…snip...
}
References:
http://www.playframework.org/documentation/2.0.4/JavaHome
http://www.playframework.org/documentation/2.0.4/JavaForms