Play Framework Framework Learning Document
Play Framework Framework Learning Document 1
First, what is Playframework 3
Ii. advantages of the Playframework framework 4
III. Introduction to Play Framework Development 5
1. Preparation Work 5
2. New Project 5
3. Environment variable Configuration 7
4. MVC Model 8
App/controllers 9
App/models 9
App/views 9
5. Application Layout 9
App Catalog 9
Where is the. class file? 9
Public directory 10
CONF Catalogue 10
LIB Directory 10
6, create a simple HelloWorld program 10
Run the App 11
Create Form 15
Provides a better URL 18
customizing layouts 19
Add Validation 19
Automated Testing 21
First, what is Playframework
The Play framework is a full-featured Java Web Development framework. Simple and flexible design with restful architecture. The play framework uses the MVC pattern as the Web layer, integrates Hibernate management persistence layer, and the play framework uses a groovy-based template engine.
· The Play framework lets developers debug apps without having to recompile a packaged release app to see the effects of the changes.
· The play framework is a stateless model, a truly "no-share" system that can deploy multiple instances of the play framework across multiple servers without interfering with each other.
· The Play framework uses groovy as the template engine, enabling the presentation layer to be truly development-efficient and concise
· The Play framework has a precise error-locating mechanism that can pinpoint the location of the error code when an error occurs.
· The Play framework is fast, quick to start, and fast to run.
Note: RESTful Architecture: REST (Representation State Transfer) describes a schema-style network system, such as a Web application. It first appeared in 2000 with Roy Fielding's doctoral dissertation, one of the main authors of the HTTP specification.
REST refers to a set of schema constraints and principles. Applications or designs that meet these constraints and principles are RESTful
The most important REST principle of a WEB application is that the interaction between the client and the server is stateless between requests. Each request from the client to the server must contain the information necessary to understand the request. If the server restarts at any point in time between requests, the client will not be notified. In addition, stateless requests can be answered by any available server, which is ideal for environments such as cloud computing. Clients can cache data to improve performance.
Another important REST principle is a hierarchical system, which means that a component cannot understand a component outside the middle tier it interacts with. By restricting system knowledge to a single layer, you can limit the complexity of the entire system and promote the underlying independence.
When the constraints of the REST schema are applied as a whole, an application is generated that can be scaled to a large number of clients. It also reduces the interaction latency between the client and the server. The unified interface simplifies the entire system architecture and improves the visibility of interactions between subsystems. REST simplifies the implementation of clients and servers.
Detailed Description: http://baike.baidu.com/view/5798116.htm
Groovy Module Engine: Groovy is an emerging Java 2 platform language. Groovy code can be well combined with Java code and can be used to extend existing code. The current Groovy version is 1.6.3 and can be used on both Java 1.4 and Java 5 platforms, as well as Java 6.
Groovy is an alternative language for the JVM-the alternative is that Java programming can be done on the Java platform with groovy in the same way that Java code is used. Note: Instead of groovy replacing Java, it means groovy and Java are well-integrated programming
is an agile dynamic language based on a Java virtual machine.
Built on the powerful Java language and added many features learned from languages such as Python,ruby and Smalltalk.
Provides Java developers with modern, most popular programming language features and low learning costs (almost 0).
Support DSL (Domain specific languages domain definition language) and other concise syntax to make your code easier to read and maintain.
Groovy has processing native types, object-oriented, and an ant DSL, making it very easy to create shell scripts.
The developer's efficiency is greatly improved by the reduction of Framework code when developing Web,gui, database or console programs.
Unit Tests and simulations (objects) are supported to simplify testing.
Seamlessly integrates all existing Java objects and class libraries.
Compile directly into Java bytecode, so you can use groovy anywhere you use Java.
One of the benefits of Groovy is that its syntax is similar to the syntax of the Java language. While Groovy's syntax stems from the idea of a language such as Smalltalk and Ruby, it can be imagined as a simpler, more expressive variant of the Java language. (At this point, Ruby differs from Groovy because its syntax differs greatly from Java syntax.) )
Many Java developers love the similarity between Groovy code and Java code. From a learning perspective, if you know how to write Java code, you already know Groovy. The main difference between groovy and the Java language is that the groovy code required to accomplish the same task is less than the Java code. (Sometimes it's a lot less!) )
Ii. advantages of the Playframework framework
1) Change the code to take effect in time!
Edit the Java file, save, refresh the browser, you can see the effect! No need to compile, deploy, restart the server.
2) Full-stack
Integrated hibernate,openid,memcached ... There's also a powerful plug-in system that provides everything you need to create a cool web app.
3) Stateless mode
4) play is a real "Share nothing" system. For rest, capacity expansion can be easily achieved by running multiple instances of the same application across multiple servers.
5) Quick resolution of errors
When an error occurs, play will show you exactly the line of code that generated the problem in the source code, even if it happened in the template.
6) Modular System of universities
A simple modular system based on groovy as the expression language. It provides the functionality of the module inheritance, inclusion and labeling.
7) Interesting & University
Help you save time waiting for your Java app to restart, increase productivity, and get the project done faster.
8) asynchronous
Based on a non-blocking IO model, modern Web applications based on long polling and WebSockets are allowed to be created in modern websockets.
9) Pure Java
Use Java to encode, you can use any Java library, you can use your favorite IDE, can be combined with eclipse or NetBeans gracefully.
III. Introduction to Play Framework Development 1, preparation
Official website: www.playframework.com Download the latest version of the Play-1.2.3.zip Development kit. Unpack the downloaded package, the extracted path is best not to include spaces, Chinese and the like, will cause the play command can not perform the problem.
2. New Project
Unzip the downloaded Play-1.2.3.zip development package and configure the environment variable (or do not need to configure environment variables, but to complete the absolute path at run time)
Open the CMD Command window, type the CD play compression directory, then enter the play new new project name,
Run the project by entering the play run project name.
If the project can run without an error, then enter the play Eclipsify project name to import the project to eclipse,
The play eclipsify here can be simplified to play EC
Open Eclipse and import the project you just created.
3. Environment variable Configuration
Path:c:\program Files\java\jdk1.6.0_21\bin;
CLASSPATH:.; %java_home%\lib\dt.jar;%java_home%\lib\tools.jar;
JAVA_HOME:C:\JDK (JDK installation path)
4. MVC model
The Play app follows the MVC schema pattern used by the Web schema.
It separates the application into different layers: the presentation layer (Presentation) and the model layer. The presentation layer is further divided into views (view) and controller (controllers).
· Model is the domain representation (domain-specific representation) of the information being processed by the application. The vast majority of applications use persistence mechanisms such as databases to store data. But MVC does not specifically mention the data access layer because it belongs to the lower tier and is encapsulated by the model.
· View renders the model as a form for interaction, usually a user interface. A model can have multiple views of different purposes. In Web applications, view is usually rendered in html,xml or JSON, or it may be a binary chart.
· The controller handles events (usually user actions) and changes the model accordingly. In Web applications, events are typically HTTP requests: The controller listens for HTTP requests, extracts data from them, such as query string parameters, request headers, and then alters the underlying model object.
Play will divide this three tiers into different package in the app directory.
App/controllers
A controller is a Java class, and its static public method is an action (action). An action is a Java processing entry point after receiving an HTTP request. The controller class is actually process-oriented, non-OO. The action extracts data from an HTTP request, reads or updates the model object, and returns a result wrapped in an HTTP response (HTTP Response).
App/models
Model is a set of Java classes with all OO attributes. Contains data structures and actions that the app can use. (That is, the congestion model). Supports persistence through JPA.
App/views
The view of the app is generated by the play's template system. The controller obtains the data from the model and then renders it using a template. This package contains template files such as Html,xml, which are used as representations of dynamically generated models (representation).
5. Application Layout App Directory
Contains all the executable artifacts: Java source code and view templates. There are three standard package, each representing the first layer of MVC. You can also add your own package, such as an example of a utils package.
View pacakge can be used in molecular packages:
· Tags store the app's TA. such as reusable template fragments.
· A controller is a view directory, which, by convention, stores the relevant templates for each controller in its own subdirectory.
Where is the. class file?
Play compiles the Java source code at run time and caches the compiled class in the Tmp\bytecode directory. The executable artifact of the play app. Java source files, not compiled. Class (including jar files).
Public directory
Stores static resources that are processed directly by the Web server. Divided into three sub-directories: Images,stylesheets and JavaScripts, respectively, put pictures, CSS and JS.
Conf Directory
Contains all the configuration files for the app. Both of the required files are:
· Application.conf: Applies the master profile, which contains all the standard configuration options.
· Routes:url The routing rule definition file.
This directory is included in the Java classpath.
Lib Directory
A standard Java class library that holds application dependencies. This directory is automatically added to the Java classpath.
6, create a simple HelloWorld program
Open cmd, execute:
Play New HelloWorld
The Play new command creates a HelloWorld directory under the current path, which contains a series of files and directories, which are important as follows:
app/contains the application core, divided into models,controllers and views directory: The place where Java lives ^_^
conf/contains all the configurations for your app. application.conf Apply the master configuration. Routes defines the URL routing rules, messages internationalization.
The lib/contains the standard. jar files that the application relies on.
The public/contains all externally accessible resources: JS,CSS and image.
test/contains the test programs for all applications. The test program is based on JUnit or selenium.
Note: Play requires that all files must be UTF-8 encoded.
Wait, where is the. class file for your application? Well, play does not use the class file but reads the Java source files directly and compiles them using Eclipse compiler.
This leads to two important things. The first time you run the play will check your changes to the source files and load them automatically. Second, when an exception occurs, play creates a better error report and attaches the relevant
Run the App
Type play run Helloworld,play in cmd to start Web server and listen on port 9000
Open the browser type http://localhost:9000/, the app displays a default welcome page
Now, look at how this page is displayed.
The main entry point of the app is configured in the Conf/routes file. It defines all accessible URLs for the app. When you open a routes file, you see the first route:
Get/application.index
It tells play that the Application.indexjava method is called when the/path receives a GET request. It is controllers. Application.index is abbreviated because the controllers package is implicitly attached.
When you create a standard Java application, you typically use an entry point that is the main method. The Play app has multiple, one URL. These methods are called action methods. The class that defines the action method is called a controller.
Open Helloworld/app/controllers/application.java:
Package controllers;
Import play.*;
Import play.mvc.*;
Import java.util.*;
Import models.*;
public class Application extends Controller {
public static void index () {
Render ();
}
}
See application extends the Play.mvccontroller class. It provides the methods that all controllers need to use, such as the Render method used in the index action.
The index method is defined as public static void because the controller never needs to instantiate and return a value. To prevent the user from introducing the state and making the controller natural, clean and so designed. But the side effect is that render can only throw out the result by throw, with the exception when Goto, it is a conspiracy way).
The default index action calls the Render method, notifying play to render a template. The template is a simple text file under the App/views directory. Use application/index.html here
Open helloworld/app/views/application/index.html File:
#{extends ' main.html '/}
#{set title: ' Home '/}
#{welcome/}
The content is the play tag, similar to JSP Taglib.#{welcome/}tag generated the welcome message that was previously seen. #{extends/}tags tells play this template integrates another main.html template. Template inheritance can be used to create complex web and also to reuse public parts.
Open the helloworld/app/views/main.html template
<! DOCTYPE html>
<title>#{get ' title '/}</title>
<meta http-equiv= "Content-type" content= "text/html; Charset=utf-8 ">
<link rel= "stylesheet" type= "text/css" media= "screen" href= "@{'/public/stylesheets/main.css '}" >
#{get ' Morestyles '/}
<link rel= "shortcut icon" type= "Image/png" href= "@{'/public/images/favicon.png '}" >
<script src= "@{'/public/javascripts/jquery-1.4.2.min.js '}" type= "Text/javascript" charset= "Utf-8" ></ Script>
#{get ' morescripts '/}
<body>
#{dolayout/}
</body>
You see #{dolayout/}tag? is the location where the application/index.html is inserted.
Create a form
Edit helloworld/app/views/application/index.html Template
#{extends ' main.html '/}
#{set title: ' Home '/}
<form action= "@{application.sayhello ()}" method= "GET" >
<input type= "text" name= "MyName"/>
<input type= "Submit" value= "Say hello!"/>
</form>
We use @{...} The symbol request play automatically generates a method to invoke the Application.sayhello action. Refreshes the browser.
Oops, something went wrong. Because it refers to a non-existent action. Need to be created in Helloworld/app/controllers/application.java:
Package controllers;
Import play.mvc.*;
public class Application extends Controller {
public static void index () {
Render ();
}
public static void SayHello (String myName) {
Render (MyName);
}
}
We declare the myname parameter, which is automatically mapped to the MyName parameter of the HTTP request submitted by the form. Refreshes the browser.
Enter name submission, and another error occurs.
Because play renders the default template for this action, it is not found. We create files helloworld/app/views/application/sayhello.html
#{extends ' main.html '/}
#{set title: ' Home '/}
<a href= "@{application.index ()}" >back to Form</a>
Then refresh:
Provide a better URL
Look at the URL of the submission:
Http://localhost:9000/application/sayhello?myName=chaos
It's not restful enough. Because play captures this URL by default rules
*/{controller}/{action} {controller}. {Action}
You can edit the Helloworld/conf/routes file to add a rule before the default rule, providing a more natural Hello URL
Get/hello Application.sayhello
Custom Layouts
You can modify the template to change the layout. Edit helloworld/app/views/main.html File:
Add validation
Add a validation to the form that requires the Name field to be filled. We implement it via play validation. Edit Helloworld/app/controllers/application.java, at SayHello action:
public static void SayHello (@Required String myName) {
if (Validation.haserrors ()) {
Flash.error ("Oops, please enter your name!");
Index ();
}
Render (MyName);
}
and import play.data.validation.*. @Required tell play to automatically check if the MyName field is filled in. If the validation fails, we add a message to flash scope and redirect to the index action. Flash scope allows messages to be persisted when redirected.
Edit helloworld/app/views/application/index.html Display error message
#{extends ' main.html '/}
#{set title: ' Home '/}
#{if Flash.error}
<p style= "color: #c00" >
${flash.error}
</p>
#{/if}
<form action= "@{application.sayhello ()}" method= "GET" >
<input type= "text" name= "MyName"/>
<input type= "Submit" value= "Say hello!"/>
</form>
Enter an empty parameter and submit, OK is working.
Automated testing
Selenium Test
Run the app in test mode. Enter the play Test HelloWorld in CMD.
Open the browser, enter Http://localhost:9000/@tests start the tester.
Perform tests
Selenium test cases are usually written as an HTML file. Play uses the play template engine to generate these files. helloworld/test/application.test.html file:
*{You can use plain Selenium command using the selenium tag}*
#{selenium}
Open the home page, and check that no error occured
Open ('/')
Assertnottitle (' Application error ')
#{/selenium}
This test opens the home page, confirming that there is no "application error" in the response.
Let's write our own tests. To edit the test content:
*{You can use plain Selenium command using the selenium tag}*
#{selenium}
Open the home page, and check that no error occurred
Open ('/')
Assertnottitle (' Application error ')
Check The It is the form
Asserttextpresent (' The Hello World app. ')
Submit the form
Clickandwait (' css=input[type=submit] ')
Check the error
Asserttextpresent (' Oops, please enter your name! ')
Type the name and submit
Type (' Css=input[type=text] ', ' Bob ')
Clickandwait (' css=input[type=submit] ')
Check the result
Asserttextpresent (' Hello bob! ')
Asserttextpresent (' The Hello World app. ')
Check the back link
Clickandwait (' Link=back to form ')
Home page?
Asserttextnotpresent (' Hello bob! ')
#{/selenium}
Re-execute
See: Http://www.playframework.com/documentation/1.2.3/firstapp
Note: All the. java files in the controllers in the app must have the same method name as all the. html file names in the view file, or you would specify an HTML file name, such as render ("user/userlist.html", PageObject);p Roobject is the name of the object.
2013 Latest play Web framework version 1.2.3 Framework Learning document Collation