- 浏览: 2567432 次
- 性别:
- 来自: 成都
-
文章分类
最新评论
-
nation:
你好,在部署Mesos+Spark的运行环境时,出现一个现象, ...
Spark(4)Deal with Mesos -
sillycat:
AMAZON Relatedhttps://www.godad ...
AMAZON API Gateway(2)Client Side SSL with NGINX -
sillycat:
sudo usermod -aG docker ec2-use ...
Docker and VirtualBox(1)Set up Shared Disk for Virtual Box -
sillycat:
Every Half an Hour30 * * * * /u ...
Build Home NAS(3)Data Redundancy -
sillycat:
3 List the Cron Job I Have>c ...
Build Home NAS(3)Data Redundancy
Playframework(5)Java Project and SQL Database
8. Accessing an SQL Database
Configuring JDBC connection pools
conf/application.conf
# Default database configuration
db.default.driver=org.h2.Driver
db.default.url="jdbc:h2:mem:play"
#Orders database
db.orders.driver=org.h2.Driver
db.orders.url="jdbc:h2:mem:order"
#customers database
db.customers.driver=org.h2.Driver
db.customers.url="jdbc:h2:mem:customers"
Accessing the JDBC database: Database ds = DB.getDatasource();
Obtaining a JDBC connection Connection connection = DB.getConnection();
Exposing the datasource through JNDI
db.default.driver=org.h2.Driver
db.default.url="jdbc:h2:men:play"
db.default.jndiName=DefaultDS
Using Ebean ORM
http://www.avaje.org/
conf/application.conf:
ebean.default="models.*"
ebean.orders="models.Order, models.OrderItem"
ebean.customer="models.Customer, models.Address"
Using the play.dv.ebean.Model Superclass
@Entity
public class Task extends Model{
@Id
@Constraints.Min(10)
public Long id;
@constraints.Required
public String name;
public boolean done;
@Format.DateTime(pattern="dd/MM/yyyy")
public Data dueDate = new Date();
public static Finder<Long,Task> find = new Finder<Long, Task>(
Long.class, Task.class
);
}
Allmost like hibernate
Transactional actions
We need to enable the helper for that on Ebean.
Intergrating with JPA
Exposing the datasource through JNDI
Adding a JPA implementation to my project
"org.hibernate" % "hibernate-entitymanager" % "3.6.9.Final"
Creating a persistence unit
conf/META-INF/persistence.xml
Annotating JPA actions with @Transactional
Using the play.db.jpa.JPA helper
public static Company findById(Long id){
return JPA.em().find(Company.class, id);
}
9 The Play Cache API
The default cache API uses EHCache. play.cache.Cache
Cache.set("item.key", frontPageNews);
News news = Cache.get("item.key");
Remove the cache, Cache.set("item.key", null, 0) Cache.remove("item.key")
Caching HTTP Responses
@Cached("homePage")
public static Result index(){
return ok("Hello world");
}
10. Calling WebService
play.libs.WS provides a way to make asynchronous HTTP calls.
We will use promise then.
11. Integration with Akka
12. Internationalization
13. Application Global Settings
The Global Object
We need to define a global object in the root package
import play.*;
public class Global extends GlobalSettings{
}
Intercepting application start-up and shutdown
public class Global extends GlobalSettings{
public void onStart(Application app){
Logger.info("Application has started");
}
public void onStop(Application app){
Logger.info("Application shutdown...");
}
}
Providing an application error page
When an exception occurs in my application, the onError operation will be called.
public class Global extends GlobalSettings{
public Result onError(Throwable t){
return internalSeverError(
views.html.errorPage(t)
);
}
}
Handling action not found
If the framework doesn't find an action method for a request, the onHandlerNotFound operation will be called:
public class Global extends GlobalSettings{
public Result onHandlerNotFound(String uri){
return notFound(
views.html.pageNotFound(uri)
);
}
}
The onBadRequest operation will be called if a route was found, but it was not possible to bind the request parameters.
public class Global extends GlobalSettings{
public Result onBadRequest(String uri, String error){
return badRequest("Don't try to hack the URI!");
}
}
Intercepting Requests
One important aspect of the GlobalSettings class is that it provides a way to intercept requests and execute business logic before a request is dispatched to an action.
public class Global extends GlobalSettings{
public Action onRequest(Request request, Method actionMethod){
System.out.println("before each request…" + request.toString());
return super.onRequest(request, actionMethod);
}
}
14. Testing Your Application
Using JUnit and Running a fake application
fakeApplication(inMemoryDatabase())
Writing functional tests
Testing a template
@Test
public void renderTemplate(){
Content html = views.html.index.render("Coco");
assertThat(contentType(html)).isEqualTo("text/html");
assertThat(ContentAsString(html)).contains("Coco");
}
Testing your controllers
@Test
public void callIndex(){
Result result = callAction(
controllers.routes.ref.Application.index("Kiko");
);
assertThat(status(result)).isEqualTo(OK);
assertThat(contentType(result)).isEqualTo("text/html");
assertThat(charset(result)).isEqualTo("utf-8");
assertThat(contentAsString(result)).contains("Hello Kiki");
}
Testing the router
Instead of calling the Action, we can let the Router do it.
@Test
public void badRoute(){
Result result = routeAndCall(fakeRequest(GET, "/xx/Kiki"));
assertThat(result).isNull();
}
Starting a real HTTP server
@Test
public void testInServer(){
running(testServe(3333), new Callback0(){
assertThat(
WS.url("http://localhot:3333").get().get().status
).isEqualTo(OK);
});
}
Testing from within a web browser
Selenium WebDriver
@Test
public void runInBrowser(){
running(testServer(3333), HTMLUNIT, new Callback<TestBrowser>(){
public void invoke(TestBrowser browser){
browser.goTo("http://localhost:3333");
assertThat(browser.$("#title").getTexts().get(0)).isEqualTo("Hello Guest");
browser.$("a").click();
assertThat(browser.url()).isEqualTo("http://localhost:3333/Coco");
assertThat(browser.$("#title", 0).getText()).isEqualTo("Hello Coco");
}
})
}
References:
http://www.playframework.org/documentation/2.0.4/JavaHome
http://www.playframework.org/documentation/2.0.4/JavaDatabase
8. Accessing an SQL Database
Configuring JDBC connection pools
conf/application.conf
# Default database configuration
db.default.driver=org.h2.Driver
db.default.url="jdbc:h2:mem:play"
#Orders database
db.orders.driver=org.h2.Driver
db.orders.url="jdbc:h2:mem:order"
#customers database
db.customers.driver=org.h2.Driver
db.customers.url="jdbc:h2:mem:customers"
Accessing the JDBC database: Database ds = DB.getDatasource();
Obtaining a JDBC connection Connection connection = DB.getConnection();
Exposing the datasource through JNDI
db.default.driver=org.h2.Driver
db.default.url="jdbc:h2:men:play"
db.default.jndiName=DefaultDS
Using Ebean ORM
http://www.avaje.org/
conf/application.conf:
ebean.default="models.*"
ebean.orders="models.Order, models.OrderItem"
ebean.customer="models.Customer, models.Address"
Using the play.dv.ebean.Model Superclass
@Entity
public class Task extends Model{
@Id
@Constraints.Min(10)
public Long id;
@constraints.Required
public String name;
public boolean done;
@Format.DateTime(pattern="dd/MM/yyyy")
public Data dueDate = new Date();
public static Finder<Long,Task> find = new Finder<Long, Task>(
Long.class, Task.class
);
}
Allmost like hibernate
Transactional actions
We need to enable the helper for that on Ebean.
Intergrating with JPA
Exposing the datasource through JNDI
Adding a JPA implementation to my project
"org.hibernate" % "hibernate-entitymanager" % "3.6.9.Final"
Creating a persistence unit
conf/META-INF/persistence.xml
Annotating JPA actions with @Transactional
Using the play.db.jpa.JPA helper
public static Company findById(Long id){
return JPA.em().find(Company.class, id);
}
9 The Play Cache API
The default cache API uses EHCache. play.cache.Cache
Cache.set("item.key", frontPageNews);
News news = Cache.get("item.key");
Remove the cache, Cache.set("item.key", null, 0) Cache.remove("item.key")
Caching HTTP Responses
@Cached("homePage")
public static Result index(){
return ok("Hello world");
}
10. Calling WebService
play.libs.WS provides a way to make asynchronous HTTP calls.
We will use promise then.
11. Integration with Akka
12. Internationalization
13. Application Global Settings
The Global Object
We need to define a global object in the root package
import play.*;
public class Global extends GlobalSettings{
}
Intercepting application start-up and shutdown
public class Global extends GlobalSettings{
public void onStart(Application app){
Logger.info("Application has started");
}
public void onStop(Application app){
Logger.info("Application shutdown...");
}
}
Providing an application error page
When an exception occurs in my application, the onError operation will be called.
public class Global extends GlobalSettings{
public Result onError(Throwable t){
return internalSeverError(
views.html.errorPage(t)
);
}
}
Handling action not found
If the framework doesn't find an action method for a request, the onHandlerNotFound operation will be called:
public class Global extends GlobalSettings{
public Result onHandlerNotFound(String uri){
return notFound(
views.html.pageNotFound(uri)
);
}
}
The onBadRequest operation will be called if a route was found, but it was not possible to bind the request parameters.
public class Global extends GlobalSettings{
public Result onBadRequest(String uri, String error){
return badRequest("Don't try to hack the URI!");
}
}
Intercepting Requests
One important aspect of the GlobalSettings class is that it provides a way to intercept requests and execute business logic before a request is dispatched to an action.
public class Global extends GlobalSettings{
public Action onRequest(Request request, Method actionMethod){
System.out.println("before each request…" + request.toString());
return super.onRequest(request, actionMethod);
}
}
14. Testing Your Application
Using JUnit and Running a fake application
fakeApplication(inMemoryDatabase())
Writing functional tests
Testing a template
@Test
public void renderTemplate(){
Content html = views.html.index.render("Coco");
assertThat(contentType(html)).isEqualTo("text/html");
assertThat(ContentAsString(html)).contains("Coco");
}
Testing your controllers
@Test
public void callIndex(){
Result result = callAction(
controllers.routes.ref.Application.index("Kiko");
);
assertThat(status(result)).isEqualTo(OK);
assertThat(contentType(result)).isEqualTo("text/html");
assertThat(charset(result)).isEqualTo("utf-8");
assertThat(contentAsString(result)).contains("Hello Kiki");
}
Testing the router
Instead of calling the Action, we can let the Router do it.
@Test
public void badRoute(){
Result result = routeAndCall(fakeRequest(GET, "/xx/Kiki"));
assertThat(result).isNull();
}
Starting a real HTTP server
@Test
public void testInServer(){
running(testServe(3333), new Callback0(){
assertThat(
WS.url("http://localhot:3333").get().get().status
).isEqualTo(OK);
});
}
Testing from within a web browser
Selenium WebDriver
@Test
public void runInBrowser(){
running(testServer(3333), HTMLUNIT, new Callback<TestBrowser>(){
public void invoke(TestBrowser browser){
browser.goTo("http://localhost:3333");
assertThat(browser.$("#title").getTexts().get(0)).isEqualTo("Hello Guest");
browser.$("a").click();
assertThat(browser.url()).isEqualTo("http://localhost:3333/Coco");
assertThat(browser.$("#title", 0).getText()).isEqualTo("Hello Coco");
}
})
}
References:
http://www.playframework.org/documentation/2.0.4/JavaHome
http://www.playframework.org/documentation/2.0.4/JavaDatabase
发表评论
-
NodeJS12 and Zlib
2020-04-01 07:44 492NodeJS12 and Zlib It works as ... -
Traefik 2020(1)Introduction and Installation
2020-03-29 13:52 351Traefik 2020(1)Introduction and ... -
Private Registry 2020(1)No auth in registry Nginx AUTH for UI
2020-03-18 00:56 449Private Registry 2020(1)No auth ... -
Buffer in NodeJS 12 and NodeJS 8
2020-02-25 06:43 401Buffer in NodeJS 12 and NodeJS ... -
NodeJS ENV Similar to JENV and PyENV
2020-02-25 05:14 496NodeJS ENV Similar to JENV and ... -
Prometheus HA 2020(3)AlertManager Cluster
2020-02-24 01:47 438Prometheus HA 2020(3)AlertManag ... -
Serverless with NodeJS and TencentCloud 2020(5)CRON and Settings
2020-02-24 01:46 346Serverless with NodeJS and Tenc ... -
GraphQL 2019(3)Connect to MySQL
2020-02-24 01:48 262GraphQL 2019(3)Connect to MySQL ... -
GraphQL 2019(2)GraphQL and Deploy to Tencent Cloud
2020-02-24 01:48 463GraphQL 2019(2)GraphQL and Depl ... -
GraphQL 2019(1)Apollo Basic
2020-02-19 01:36 336GraphQL 2019(1)Apollo Basic Cl ... -
Serverless with NodeJS and TencentCloud 2020(4)Multiple Handlers and Running wit
2020-02-19 01:19 322Serverless with NodeJS and Tenc ... -
Serverless with NodeJS and TencentCloud 2020(3)Build Tree and Traverse Tree
2020-02-19 01:19 330Serverless with NodeJS and Tenc ... -
Serverless with NodeJS and TencentCloud 2020(2)Trigger SCF in SCF
2020-02-19 01:18 306Serverless with NodeJS and Tenc ... -
Serverless with NodeJS and TencentCloud 2020(1)Running with Component
2020-02-19 01:17 320Serverless with NodeJS and Tenc ... -
NodeJS MySQL Library and npmjs
2020-02-07 06:21 307NodeJS MySQL Library and npmjs ... -
Python Library 2019(1)requests and aiohttp
2019-12-18 01:12 272Python Library 2019(1)requests ... -
NodeJS Installation 2019
2019-10-20 02:57 586NodeJS Installation 2019 Insta ... -
Monitor Tool 2019(2)Monit on Multiple Instances and Email Alerts
2019-10-18 10:57 279Monitor Tool 2019(2)Monit on Mu ... -
Sqlite Database 2019(1)Sqlite3 Installation and Docker phpsqliteadmin
2019-09-05 11:24 388Sqlite Database 2019(1)Sqlite3 ... -
Supervisor 2019(2)Ubuntu and Multiple Services
2019-08-19 10:53 387Supervisor 2019(2)Ubuntu and Mu ...
相关推荐
5. 使用 Play 框架开发 Java 应用 5.1 HTTP编程 5.1.1 什么是 Action? 5.1.2 什么是 Result ? 5.1.3 什么是 Controller? 5.1.4 Session 和 Flash 5.2 异步 HTTP 编程 5.3 对 WebSocket 的支持 5.4 如何...
Play Framework框架是一种基于Java的软件框架,旨在提高开发效率和提供REST式的架构风格。该框架可以让开发者继续使用他们喜欢的开发环境或繻库,不需要切换到另一种语言、IDE或者其他繻库。 一、Play Framework...
playframework javaweb playframework javaweb
Play Framework 是一个开源的Web应用框架,主要针对Java和Scala开发者设计,它的核心理念是简化开发流程,提高开发效率,并且特别强调了RESTful架构风格。这个“playframework中文教程.zip”压缩包很可能是为了帮助...
- **框架简介**:Play Framework 是一个开源的 Web 开发框架,基于 Java 和 Scala 编程语言。它采用轻量级、非阻塞的服务端架构,特别适合开发高性能、可扩展的应用程序。Play Framework 通过其独特的设计理念简化了...
Play Framework 是一个开源的Web应用框架,用于构建现代、高性能的Java和Scala应用程序。它采用模型-视图-控制器(MVC)架构模式,并且强调简洁的代码和开发的即时反馈。Play Framework API 是开发者使用该框架进行...
- **定义与背景**:Play Framework 是一款基于 Java 和 Scala 的高性能、轻量级 Web 开发框架。它采用 RESTful 架构设计,支持热重载功能,能够显著提高开发效率。本书(《Play Framework Cookbook》)提供了超过 60...
PlayFramework是一个高性能的Java和Scala框架,它支持Web应用的快速开发,并且主要面向RESTful应用程序。在PlayFramework中,为了确保数据的准确性和合法性,通常会在数据保存到数据库之前,对HTTP请求中的参数进行...
5. **内置数据库支持**:Play Framework集成了JPA(Java Persistence API),并默认支持H2内存数据库,使得开发者可以快速进行原型开发。同时,它也支持其他关系型数据库,如MySQL、PostgreSQL等,通过简单的配置...
Play Framework 是一个基于Java的开源Web应用框架,它遵循MVC(模型-视图-控制器)架构模式,致力于简化Web应用程序的开发过程。这个资料大全包含了许多关于Play Framework的重要资源,帮助开发者深入理解和高效使用...
Play Framework是一款基于Java和Scala的开源Web应用框架,它遵循模型-视图-控制器(MVC)架构模式,旨在提供高效、简洁且可测试的开发环境。标题中的"v2.7.9"指的是该框架的特定版本,通常每个新版本会包含性能优化...
Play Framework是一个full-stack(全栈的)Java Web应用框架,包括一个简单的无状态MVC模型,具有Hibernate的对象持续,一个基于Groovy的模板引擎,以及建立一个现代Web应用所需的所有东西。 Play Framework的...
Play Framework 是一个基于Java和Scala的开源Web应用框架,它遵循模型-视图-控制器(MVC)架构模式。在“Playframework框架学习之路 1”中,我们可能要探讨这个框架的基础概念、安装过程以及如何创建一个简单的应用...
Play Framework 2.0 是一个开源的Web应用框架,它基于Scala和Java语言,遵循“模式-动作”(Action)架构,提供了一种轻量级、敏捷开发的方式。本篇文章将引导你通过创建一个简单的待办事项(Todo List)应用来了解...
Play Framework2是一个强大的Java和Scala应用开发框架,它以其简洁的API、快速的开发周期以及对Web标准的紧密集成而闻名。本教程旨在为初学者和有经验的开发者提供全面的指导,帮助他们掌握Play Framework2的核心...
Mastering Play Framework for Scala
Play Framework 是一个基于Java和Scala的开源Web应用框架,它遵循模型-视图-控制器(MVC)架构模式。在本教程中,我们将探讨如何利用Play Framework与MySQL数据库交互,实现基本的CRUD(创建、读取、更新、删除)...
Play Framework是一个强大的、基于Java和Scala的开源Web应用程序框架,它采用模型-视图-控制器(MVC)架构模式,以简洁的API和直观的开发体验受到开发者喜爱。本篇文章将详述如何在Windows环境下安装配置Play环境...
Play Framework 2.0 是一个基于Java和Scala的开源Web应用程序框架,以其“写后即运行”的特性而闻名。这个入门教程的第三部分是关于如何使用Play Framework构建一个简单的留言板应用。在这里,我们将深入探讨Play ...