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

Playframework(3)Java Project and Handling asynchronous results

 
阅读更多
Playframework(3)Java Project and Handling asynchronous results
2. Handling asynchronous results
We were able to compute the result to send to the web client directly. This is not always the case: the result may depend of an expensive computation or on a long web service call.

Action should be as fast as possible. (non blocking). We should return a result if we are not yet able to compute, the response should be a promise of a result.

Promise<Result> instead of a normal Result.

Play will then serve this result as soon as the promise is redeemed.
The web client will be blocked while waiting for the response but nothing will be blocked on the server, and server resources can be used to serve other clients.

How to create a Promise<Result>

I am not quite understand this part. Maybe, I will learn it later.

Streaming HTTP responses
According to HTTP 1.1, the server must send the appropriate Content-Length HTTP header along with the response.
public static Result index(){
     return ok("Hello World")
}
Play is able to compute the content size for us and generate the appropriate header.

Serving Files
sending back a local file
…snip…
return ok(new java.io.File("/tmp/fileToServe.pdf"));
…snip...
The default Content-Dispostion will be Disposition: attachment; filename=fileToServe.pdf

Chunked Response
Chunked transfer encoding, dynamically-computed content with no content size available.
public static index(){
     Chunks<String> chunks = new StringChunks(){
          public void onReady(Chunks.Out<String> out){
               registerOutChannelSomewhere(out);
          }
     }
     ok(chunks);
}
public void registerOutChannelSomewhere(Chunks.Out<String> out){
     out.write("kiko");
     out.write("foo");
     out.close();
}
HTTP/1.1 200 OK    Content-Type: text/plain; charset=utf-8    Transfer-Encoding: chunked

Comet Sockets and WebSockets
play is able to handle these things. But I will learn them in the future.

3. The template engine
A Play Scala template is a simple text file that contains small blocks of Scala code. Templates can generate any text-based format, such as HTML, XML or CSV.

Templates are compiled as standard Scala functions, following a simple naming convention. If you create a
views/Application/index.scala.html
views.html.Application.index
class that has a render() method.

For example, template:
@(customer: Customer, orders: List[Order])
<h1>Welcome @customer.name!</h1>
<ul>
@for(order <- orders){
     <li>@order.getTitle()</li>
}
</ul>

Content html = views.html.Application.index.render(customer, orders);

Escape the special character like this @@.

@customer.getName()!    @customer.name! @(customer.getFirstName() + customer.getLastName())!
@{var name= customer.getFirstName() + customer.getLastName(); name}!    // multiple statements

Template parameters
A template is like a function, so it needs parameters, which must be declared at the top of the template file:
@(customer: models.Customer, orders: List[models.Order])
@(title: String = "Home")        //default value
@(title:String)(body: Html)     //several parameters

Iterating
<ul>
@for(p <- products){
     <li>@p.getName() ($@p.getPrice())</li>
}
</ul>

If-blocks   simply use Scala's standard if statement
@if(items.isEmpty()){
     <h1>Nothing to display</h1>
}else{
     <h1>@items.size() items!</h1>
}

Declaring Reusable Blocks
We can create reusable code blocks:
@display(product:models.Product) = {
     @product.getName() ($@product.getPrice())
}

<ul>
@for(product <- products){
     @display(product)
}
</ul>

Comments
@*  coments here *@

Escaping
Dynamic content parts are escaped according to the template type's rules(e.g. HTML or XML). If we want to output raw content fragment.
<p>
@Html(article.content)
</p>

Common Template Use Cases
Layout ---- views/main.scala.html
@(title: String)(content: Html)
<!DOCTYPE html>
<html>
     <head>
          <title>@title</title>
     </head>
     <body>
          <section class="content">@content</section>
     </body>
</html>

Out simple page can use this template views/Application/index.scala.html
@main(title = "Home"){
     <h1>Home page</h1>
}

Add a second page-specific content block for a sidebar or breadcrumb trail.
@(title: String)(sidebar: Html)(content: Html)
<!DOCTYPE html>
     <head>
          <title>@title</title>
     </head>
     <body>
          <section class="content">@content</section>
          <section class="sidebar">@sidebar</section>
     </body>
</html>

Our page template will be:
@main("Home"){
     <h1>Sidebar</h1>
}{
     <h1>Home page</h1>
}

Or we can declare the sidebar block separately:
@sidebar = {
     <h1>Sidebar</h1>
}

@main("Home")(sidebar) {
     <h1>Home page</h1>
}

Tags
views/tags/notice.scala.html
@(level: String = "error") (body: (string) => Html)
@level match{
     case "success" =>{
          <p class="success">
               @body("green")
          </p>
     }

     case "error" => {
          <p class="error">
               @body("red")
          </p>
     }
}

When we use the tag:
@import tags._
@notice("error"){ color =>
     Oops, something is <span style="color:@color">Wrong</span>
}


References:
http://www.playframework.org/documentation/2.0.4/JavaAsync
http://www.playframework.org/documentation/2.0.4/JavaHome

分享到:
评论

相关推荐

    Play Framework Essentials

    - **异步处理(Asynchronous Handling)**:能够提升服务器的吞吐量,提高响应速度。 #### Play框架的使用 - **设置开发环境**:安装Java开发工具包和Scala编译器。然后下载并设置Play框架环境,可以使用sbt...

    Manning - Play for Java 2014

    SUMMARYPlay for Java shows you how to build Java-based web applications using the Play 2 framework. The book starts by introducing Play through a comprehensive overview example. Then, you'll look at ...

    Java Framework源代码大全

    7. **AJAX (Asynchronous JavaScript and XML)** AJAX不是一种单一的技术,而是一组用于创建交互式Web应用的技术集合。它允许网页在不刷新整个页面的情况下与服务器交换数据并更新部分页面内容,提高了用户体验。在...

    Asynchronous Android Programming

    To start with, we will discuss the details of the Android process model and the Java low-level concurrent framework, delivered by the Android SDK. Next, we will discuss the creation of IntentServices...

    AJAX (Asynchronous JavaScript And XML)

    AJAX (Asynchronous JavaScript And XML)

    Asynchronous Http and WebSocket Client library for Java .zip

    Asynchronous Http and WebSocket Client library for Java

    ASP.NET MVC with Entity Framework and CSS

    ASP.NET MVC with Entity Framework and CSS by Lee Naylor 2016 | ISBN: 1484221362 | English | 608 pages | True PDF | 30 MB This book will teach readers how to build and deploy a fully working example ...

    Continuous Enterprise Development in Java

    Tackle testable business logic development and asynchronous messaging with an SMTP service Expose enterprise services as a RESTful interface, using Java EE’s JAX-RS framework Implement OAuth ...

    Reactive Streams in Java: Concurrency with RxJava, Reactor, and Akka Streams

    Reactive Streams in Java explains how to manage the exchange of stream data across an asynchronous boundary―passing elements on to another thread or thread-pool―while ensuring that the receiving ...

    Java - The Well-Grounded Java Developer

    - **Conciseness**: Discussion on Scala's concise syntax, which often results in shorter and more readable code compared to Java. - **Concurrency Models**: Explanation of Scala's support for reactive...

    Java_for_the_Web_with_Servlets

    including improved performance due to the Java virtual machine (JVM), easy integration with other Java technologies, and a rich set of APIs for handling HTTP requests. - **Application Architecture*...

    Asynchronous Programming Patterns .net异步编程模型

    The .NET Framework provides three patterns for performing asynchronous operations: Asynchronous Programming Model (APM) pattern Event-based Asynchronous Pattern (EAP) Task-based Asynchronous Pattern ...

    An Asynchronous Socket Server and Client

    在IT领域,异步套接字(Asynchronous Socket)服务器和客户端是网络编程中的核心概念,主要用于构建高效、可扩展的通信系统。本项目提供的代码示例深入探讨了这一技术,帮助开发者理解如何在实际应用中实现异步通信...

    Asynchronous Methods for Deep Reinforcement Learning

    lightweight framework for deep reinforcement learning that uses asynchronous gradient descent for optimization of deep neural network controllers. We present asynchronous variants of four standard ...

    Semantics of Asynchronous JavaScript

    The Node.js runtime has become a major platform for de- velopers ...level conceptual framework for reasoning about relationships between the execution of asynchronous callbacks in a Node.js application.

    Asynchronous Android Programming(PACKT,2ed,2016)

    To start with, we will discuss the details of the Android process model and the Java low-level concurrent framework, delivered by the Android SDK. Next, we will discuss the creation of IntentServices...

Global site tag (gtag.js) - Google Analytics