30th Day: Play Framework-java Developer's dream frame-Baihua Palace

Source: Internet
Author: User
Tags tojson java spring framework

Objective

On the last day of the 30-day challenge, I decided to learn the Play Framework. I wanted to write Sacla, but after a few hours of research, I found it impossible to just evaluate Scala within a day and spend some time next month to learn and share experiences. In this paper, we first look at the Play Framework Foundation, and then develop a program.

What is a play frame?

Play is an open-source, modern web framework that writes extensible Web programs in Java and Scala. It can automatically load updates to maximize productivity. Play design stateless, non-blocking architecture, which makes it easy to develop a Web program horizontally using the play framework.

Why do I care about play?

The reason I study play:

    1. Efficient: I've been using Java for 8 years, but a few months ago I paid more attention to Python and JavaScript (node. js). What surprises me most is that it's so fast to use the Dynamic language development program. Both Java EE and spring frameworks are not ideal for rapid prototyping, but with the play frame, refresh the page with the update, and look! You can see the update directly. It supports hot loading of all Java code, templates, etc., allowing you to proceed quickly.
    1. Natural response: The play framework is built on Netty, so it supports non-blocking I/O and can be easily and cost-effective for horizontal remote invocation, which is important for a service-oriented architecture to work efficiently.
    1. Supporting both Java and scala:play frameworks is a truly multilingual web framework that developers can use both in Java and Scala in their projects.
    1. The first support Rest JSON class: Play makes it easy to write restful programs, supports HTTP routing, HTTP routing translates HTTP requests into specific actions, JSON marshalling/unmarshalling API in the core API, So there is no need to add libraries to complete.
Program Use Cases

In this article, we have developed a web-based pick-up program that allows users to post and share links, and you can see the online program on the OpenShift. This is the same procedure we developed on the 22nd day, so you can get a better understanding of the previous use cases.

Install play

Please refer to the documentation to learn how to install the play frame.

Developing the Play Program

After introducing the basics, let's start writing programs.

Run the following command on your machine.

$ playNew Getbookmarks _ __ | | __ _ _  _|' _ \| |/_ ' | | |  ||            __/|_|\____|\__ /|_| |__/Play2.2.1 built with Scala 2.10.2 (Running Java 1.7.0_25", Http:// Www.playframework.com the new application would be created in/users/ Shekhargulati/dev/challenges/30days30technologies/day30/blog/getbookmarkswhat is the application name? [Getbookmarks]>which template do you want to use for this new application? 1-create a simple Scala application 2-create a simple Java application> Span class= "Number" >2ok, application getbookmarks is created. Have fun!                 
View Code

As above, after entering the command, the play frame asks a few questions. The first is the name of the program, and then whether we want to create a Scala program or Java program. By default, the folder name is used as the program name, and we choose the second option to create the Java program.

The above command creates a new directory getbookmarks, creating files and directories.

    1. The app directory contains program-specific code such as controllers, views, and modules. The controller package contains Java code to respond to URL routing. The views directory contains the server-side template, models directory contains the program domain module, in this program, the domain is a story class.
    1. The Conf directory contains the program configuration and route definition files.
    2. The project directory contains build scripts, which are based on SBT.
    3. Public contains common resources, such as CSS, JavaScript, and image catalogs.
    4. Test contains program tests.

Now we can run the default program created by play, open the play console, run the play command, and then use the Run command.

$ cd getbookmarks$ Play[info] Loading project definitionfrom/users/shekhargulati/dev/challenges/30days30technologies/day30/blog/getbookmarks/project[info] Set current project to Getbookmarks (In Build file:/users/shekhargulati/dev/challenges/30days30technologies/day30/blog/getbookmarks/) _ __ | | __ _ _  _|' _ \| |/_ ' | | |  ||            __/|_|\____|\__ /|_| |__/play2.2.1 builtWith Scala2.10.2 (Running Java1.7.0_25), http://www.playframework.com > Type"Help Play"Or"License"For more information.> Type"Exit" or use ctrl+d to leave the this console. [Getbookmarks] $ run[info] Updating {file:/users/shekhargulati/dev/challenges/30days30technologies/day30/blog/ Getbookmarks/}getbookmarks ... [INFO] Resolving Org.fusesource.jansi#jansi;  1.4 ... [INFO] Done updating. ---(Running the application from SBT, auto-reloading are enabled)---[info] play-listening for HTTP on/  0:0:0:0:0:0:0:0:9000 (Server started, use ctrl+d-stop and go back to the Co Nsole ...)                 
View Code

You can now see the program http://localhost:9000.

Create a Story field class

This program, we have only one domain class, story. Create a new package module and create a new Java class.

Package models;Import Play.db.ebean.Model;Import javax.persistence.Entity;Import Javax.persistence.Id;Import Java.util.Date;@EntityPublicClass StoryExtendsmodel{@IdPrivate String ID;Private String URL;private String fullname; private date Submittedon = new date (); private String title; private String text; private String image; public story () {} public story (string URL, string fullname) {this.url = URL; this.fullname = fullname;} public story (string URL, string fullname, string image, String text, string title) {this.url = URL; this.fullname = fullname; this.title = title; this.text = text; this.image = image;} // Getter and Setter removed for brevity}      
View Code

The code above defines a simple JPA entity with @entity and ID JPA annotations, play with its own ORM layer Ebean, and each entity class extends the Base module class.

Ebean default is not activated, to activate it, open the program conf, uncomment the following line.

Ebean. default="models.*" 
Activating the database

Now to activate the program's database, the play framework provides built-in support for the H2 database, to activate it, open the program conf file, and uncomment the following two lines.

Db. Default.driver=org.h2.driverdb. default.url="Jdbc:h2:mem:play"  

Now refresh the browser to see the following exception.

Click Apply this script now to make the SQL update effective.

Defining program Routes

In this article, we developed the same program as the 22nd day, which has the Angularjs backend and rest backend, we use the play framework to write the rest backend, re-use the Angularjs back end, in the Conf/routes file, copy and paste the code.

# Routes# This file defines all application Routes (higher priority Routes first)# Home Pageget         /                           controll ERs. assets.at (path="/public", file=static resources from The/public folder to The/assets URL pathget/assets/*< C12>file controllers. assets.at (path= "/public", file)     
View Code

The above code:

    1. When the user issues a GET request to the '/' URL, the index.html is loaded.
    2. When a user issues a GET request to '/api/v1/stories ', it gets all the JSON-formatted articles.
    3. When a user issues a POST request to '/api/v1/stories ', a new article is created.
    4. When the user issues a GET request to '/api/v1/stories/123 ', the ID is 123 for the article to be loaded.
Create Storycontroller

Now create a new Java class in the controller package, copy and paste the following code into the Storycontroller.java file.

Package controllers;Import Com.fasterxml.jackson.databind.JsonNode;Import models. story;Import Play.api.libs.ws.Response;Import Play.api.libs.ws.WS;Import Play.db.ebean.Model;Import Play.libs.Json;Import Play.mvc.BodyParser;Import Play.mvc.Controller;Import Play.mvc.Result;Import Play.mvc.Results;Import scala.concurrent.Await;Import Scala.concurrent.Future;Import scala.concurrent.duration.Duration;Import java.util.List;Import Java.util.concurrent.TimeUnit;PublicClass Storycontroller {PublicStatic Result allstories () {list<story> stories =New model.finder<string, story> (String.class, Story.class). all ();Return Results.ok (Json.tojson (stories)); }@BodyParser. of (BodyParser.Json.class)PublicStatic Result Submitstory () {Jsonnode Jsonnode = controller.request (). Body (). Asjson (); String URL = Jsonnode.findpath ("url"). Astext (); String fullname = Jsonnode.findpath ("FullName"). Astext (); Jsonnode response = fetchinformation (URL); Story stories =Nullif (response = =NULL) {story =New Story (Url,fullname); }else{String image = Response.findpath ("image"). TextValue (); String Text = Response.findpath ("Text"). TextValue (); String title = Response.findpath ("title"). TextValue (); Story =New Story (Url,fullname, image, text, title); } story.save ();return results.created (); }PublicStatic Result getstory (String storyID) {Story story =New model.finder<string, story> (String.class, Story.class). Byid (storyID);if (story = null) { return Results.notfound ("No story found with storyID" + storyID);} return Results.ok (Json.tojson (story));} private static Jsonnode fetchinformation (string url) {string restserviceurl = "/http/ Gooseextractor-t20.rhcloud.com/api/v1/extract?url= "+url; future<response> future = Ws.url (Restserviceurl). get (); try {Response result = Await.result (future, duration.apply (timeunit.seconds)); Jsonnode Jsonnode = Json.parse (Result.json (). toString ()); return jsonnode;} catch (Exception e) {e.printstacktrace (); return null;}} }
View Code

The above code:

    1. Defines the Allstories () method, which is used to find the article in the database, which is done with the Model.finder API, and then we convert the list into JSON format and return the result. The return HTTP status code 200 represents OK.
    1. The Submitstory () method first reads the URL and the full name from JSON, then issues a GET request to ' Http://gooseextractor-t20.rhcloud.com/api/v1/extract?url ', looking for the title from the given URL, Summary and main image. With all of this information, a new article is saved to the database, and an HTTP status code of 201 is returned to represent the created.
    1. The Getstory () method gets the article from the given article ID, and we convert the article called JSON format and then return in the response.
Angularjs Front End

I decided to re-use the Angularjs front end of the 22nd day, and the 22nd day showed us how to use the Angularjs and Java Spring Framework, the best part is to use JavaScript mv* framework, if your program is still using the rest interface client requirements, You can use the front-end code again. Refer to the 22nd day article for details.

Now refresh the browser access program Http://localhost:9000/

This is the content of today, I hope you like this series.

Original: Https://www.openshift.com/blogs/day-30-play-framework-a-java-developer-dream-framework

30th Day: Play Framework-java Developer's dream frame-Baihua Palace

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.