`
sillycat
  • 浏览: 2567433 次
  • 性别: Icon_minigender_1
  • 来自: 成都
社区版块
存档分类
最新评论

Playframework(4)Java Project and Handling form Submission

 
阅读更多
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","test@gmail.com");
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
分享到:
评论

相关推荐

    js-ajax-form-submission-源码.rar

    本压缩包"js-ajax-form-submission-源码.rar"(实际应为"js-ajax-form-submission-源码.zip")可能包含一个用于演示或教学目的的AJAX表单提交的完整示例。下面将详细解释AJAX表单提交的相关知识点。 1. **AJAX基础*...

    RMI-File-Submission-System-master.zip_java_submission_tornkaj

    《基于RMI的Java提交系统详解》 在Java编程领域,远程方法调用(Remote Method Invocation,简称RMI)是一项核心技术,它允许一个Java对象调用另一个在不同JVM上的对象的方法。在这个名为“RMI-File-Submission-...

    Document Submission Form 2018 (green).docx

    Document Submission Form 2018 (green).docx

    form表单的异步回调方法

    1. **表单提交(Form Submission)**:HTML表单通过`&lt;form&gt;`元素定义,其中包含`&lt;input&gt;`、`&lt;select&gt;`、`&lt;textarea&gt;`等元素来获取用户输入。默认情况下,表单提交会引发页面重定向,使用`&lt;form&gt;`的`action`属性指定...

    java登录源代码

    3. **表单提交与验证(Form Submission and Validation)**:用户输入的登录信息需要通过HTTP POST请求发送到服务器。在服务器端,使用`HttpServletRequest`对象获取这些数据,并进行有效性验证,如非空检查、长度...

    Ajax-Codeigniter-3-Ajax-Form-Submission.zip

    Ajax-Codeigniter-3-Ajax-Form-Submission.zip,“codeigniter 3 ajax表单提交和验证教程”一集的源代码,ajax代表异步javascript和xml。它是多种web技术的集合,包括html、css、json、xml和javascript。它用于创建...

    jquery-form.js

    jQuery Form Plugin是一款强大的JavaScript库,专为了解决使用jQuery进行异步表单提交(Ajax Form Submission)和文件上传的问题。它通过扩展jQuery的功能,使得处理复杂的表单交互变得更加简单、直观。在本文中,...

    Third-Party Multipath and MPIO Test and Submission Process

    ### 第三方多路径与MPIO测试及提交流程详解 #### 概述 本文档主要针对在Microsoft Windows操作系统中实现的第三方多路径(Multipath)驱动程序及其与Microsoft MPIO(Multi-Path I/O)架构之间的交互进行详尽的介绍...

    article submission

    &lt;a href="http://www.rankexperts.com"&gt;article submission&lt;/a&gt; , &lt;a href="http://www.rankexperts.com"&gt;article submission service&lt;/a&gt; , &lt;a href="http://www.rankexperts.com"&gt;build backlinks&lt;/a&gt; , ...

    Ext2.0 form使用实例的例程

    6. **事件处理(Event Handling)**:通过监听表单和字段的事件,如change、submit、validate等,开发者可以实现复杂的业务逻辑。例如,当用户更改字段值时触发特定操作,或在提交表单前进行额外的验证。 7. **表单...

    form-create:强大的动态表单生成器|form-create is a form generation component that can generate dynamic rendering, data collection, verification and submission functions through JSON

    如果有任何“建议或问题”,请询问本项目QQ讨论群预习 更多的表格操作 group组件描述 control配置描述 文件简体中文| 英语 配套名称描述@ form-create / iview iview版本@ form-create / iview4 视图设计版本@ form...

    Android.Games.Practical.Programming.By.Example.Quickstart

    Unit 2, Project Framework, discusses the storyline and framework of your first game Raccoon Rob. You'll be able to implement the activity's lifecycle callback methods and utilize handlers to switch ...

    IEEE Journal Submission (Trans. on MTT example).zip LaTeX投稿期模板

    标题 "IEEE Journal Submission (Trans. on MTT example)" 指的是一个提交到IEEE Transactions on Microwave Theory and Techniques(MTT)期刊的论文示例。这个压缩包包含了一系列用于准备和排版符合IEEE标准的...

    Titanic数据集(gender_submission,test,train)

    这里我们将深入探讨其中的"gender_submission"、"test"和"train"这三个文件,并分析它们包含的关键知识点。 首先,"gender_submission.csv"文件通常用来提供一个预测模型的基线结果。在这个案例中,它可能包含每个...

    JIFS-Submission-Templates-LaTeX.rar

    4. **章节和子章节结构**:提供标准的章节、节、子节等层次结构,方便组织论文内容。 5. **参考文献样式**:通常使用JIFS指定的参考文献样式,如IEEEtran或Chicago,确保引用格式一致。 6. **示例代码和样例内容**:...

    基于ssm+mysql高校就业管理系统设计与实现.docx

    MyBatis, on the other hand, simplifies the integration of SQL databases by providing a mapping framework between Java objects and database records. MySQL, a widely-used open-source relational ...

    Java代码中使用JSP/JSF表达式语言EL

    // handle form submission logic } } ``` 在JSP或JSF中,我们可以通过EL表达式访问和修改User Bean的属性,并通过方法调用来处理用户的操作。 在压缩包文件`EL30test`中,可能包含了相关的示例代码或者测试用例...

    vue-springboot高中信息技术课程在线测试系统java毕业论文.docx

    personal information modification, homework information management, learning resource access, examination administration, submission of student assignments, and grading information. The design ...

Global site tag (gtag.js) - Google Analytics