The Play Framework ditches the traditional Java Web framework model in favor of “Reactive” programming. The Play framework has the following features:
- Resposive: Responds quickly to user behavior.
- Scalable: In terms of load, Play scales well horizontally.
- Event-driven: Implementation of HTTP Server based on the Action model.
Play is a fast development tool that follows the ROR (Ruby on Rails) development style, supports Scala and Java development, and is suitable for small, personal projects.
π for more features. | Play2 (Java/Scala) technical framework (wisdomfish.org)
This article demonstrates the configuration and installation of SBT, MongoDB, and Play2.
1. Development environment requirements
- Requires JDK version 1.8+.
- Installation of SBT.
- Intellij IDEA 2018+ requires the Scala plug-in.
- The MongoDB version must be 3.6 or later.
- The project SDK should not exceed version 2.13. (Some plugins are not updated)
2. Development language and version selection
tool | version |
---|---|
The development environment | Windows 10 |
jdk | 1.8.0 comes with _241 |
SDK (for the project) | 2.12.1 |
MongoDB | X 3.6. |
sbt | 1.3.10 |
Play framework | X 2.8. |
Development of language | scala |
Play Scala does not currently provide better support for Mysql, so it means developing based on native JDBC components, so this project is developing with MongDB instead.
3. Basic pattern of Play project
2. app β project source directory β controllers β control layer β Models β Business layer β views β template layer build. SBT β project build script conf β configuration file (on classpath Application. Conf β main configuration file β routes β Route configuration public β Static file directory β stylesheets β CSS files β Javascript files β images β Image file project β SBT configuration file β build.properties β configure SBT version of the prokaryote. SBT plugin lib β third-party jar package dependencies logs β log directory Ext ext ext ext ext ext ext ext ext ext ext ext ext ext ext ext ext ext ext ext ext ext ext ext ext ext ext ext ext ext ext ext ext ext The compiled class file β routes - from the routes file generated by the source β twirl - from the template file generated source β universal - package directory test - test directory. Gitignore - > configure git ignore listCopy the code
Note that SBT does not actively compile third-party dependent jar packages. If you want to use an internally developed JAR package, you need to query the usage of the Assembly command online.
4. Install and configure the domestic SBT image
Create a repo.properties file in the /conf directory and change the image address. Some forums also carry a maven-central line, which causes SBT to still download files from the Maven repository first, so this line needs to be removed. When SBT looks for dependencies, it downloads them from the mirror in the order of configuration.
[repositories]
local
huaweicloud-maven: https://repo.huaweicloud.com/repository/maven/
aliyun: https://maven.aliyun.com/nexus/content/groups/public/
mvn: https://repo1.maven.org/maven2/
sbt-plugin-repo: https://repo.scala-sbt.org/scalasbt/sbt-plugin-releases, [organization]/[module]/(scala_[scalaVersion]/)(sbt_[sbtVersion]/)[revision]/[type]s/[artifact](-[classifier]).[ext]
Copy the code
Windows environment is required in the $SBT_PATH/SBT/conf/sbtconfig. TXT for additional configuration, specify the download path of SBT. C:/ SBT needs to be replaced by the actual installation path, and then include the image configuration with the -dsbt.repository. Config option:
# sbt configuration file for Windows
# Set the java args
#-mem 1024 was added in sbt.bat as default
#-Xms1024m
#-Xmx1024m
#-Xss4M
#-XX:ReservedCodeCacheSize=128m
# Set the extra sbt options
-Dsbt.log.format=true
-Dsbt.boot.directory=C:/sbt/.sbt/boot
-Dsbt.ivy.home=C:/sbt/.ivy2
-Dsbt.global.base=C:/sbt/.sbt
-Dsbt.repository.config=C:/sbt/conf/repository.properties
Copy the code
Configure these -DSBT parameter lines in IntelliJ IDEA.
5. Create Play2 project in IntelliJ IDEA
LightBend Project Starter is recommended to quickly generate a fully structured Play framework.
Note that as of May 2020, the default version of Scala used for this seed is 2.13.1. Many of the dependency tools did not adapt to Scala 2.13, so you need to reduce the version to 2.12.x in build.sbt.
6. About Play2
6.1 Basic Principles of Mapping Requests
Enter a URL in your browser to request the Play2 service on a server (the default is port 9000). The program will go to the routes file and execute the specified Controller method based on the URL mapped to the Controllers folder. (Note: Follow the conventional project structure when building the SBT project)
GET /doLogin controllers.LoginController.doLogin
Copy the code
Example: the user to enter localhost: 9000 / the doLogin, the request has been forwarded to the controllers. The LoginController. The doLogin to deal with. Depending on the business logic, you can return a simple content or an HTML view. And this behavior is called an Action.
6.2 Play Processes requests based on Action
The Action returned by the Controller is actually a function that handles the Http request. This function describes an abstract process of receiving and processing a Request: receiving a Request, processing the Request, and returning a Response.
Action{Request= >//process this request.
Response
}
Copy the code
Response can be divided into the following types, with the corresponding HTTP request status code denoted after the comment:
Ok(response) / / 200
Redirect(url) / / 302
BadRequest(response) / / 400
Unauthorized(response) / / 401
Forbidden(response) / / 403
NotFound(response) / / 404
InternalServerError(response) / / 500
ServiceUnavailable(response) / / 503
Copy the code
6.3 Twirl templates are mapped to template functions
Below the views folder is a file named XXx.scala.html, called a template file, which is rendered using Play’s built-in Twirl engine. They are mapped to views.html.xxx functions of the same name (Scala treats functions as first-class citizens).
When the Controller returns the login.scala.html template after processing the business, it assemses some variables (such as title) into the template (such as login.scala.html) and returns it to the browser to display:
def login() = Action {
//=>login.scala.html and assign "please login" to the title variable.
Ok(views.html.login(title = "Please log in"))}Copy the code
This template file, in turn, contains two types: parameter values to be dynamically inserted (passed in by the Controller when called), and an HTML document. The @ corresponds to the argument list of views.html.login. However, the return value of this function is special: it returns a rendered HTML file. You can understand its workflow the same way you understand JSPS.
@(title :String)
<! doctypehtml>
<html lang="en">
<head>.</head>
<body>.</body>
</html>
Copy the code
6.4 Referencing the Play-JSON package
According to the official documentation, cite the play-JSON package: π¦Github Link
Add dependencies to the built-in. SBT file and Refresh the Refresh Project:
libraryDependencies += "com.typesafe.play"% %"play-json" % "2.8.1"
Copy the code
Here’s a simple example of Json:
//play-json creates a JSON object.
val returnJson: JsObject = Json.obj(
"name" -> "Lijunhu"."emails" -> "[email protected]"."address" -> Json.obj(
"province" -> "HeiLongJiang"."city" -> "Herbin"))Copy the code
Extract the emails field from this variable:
val emails :String = (returnJson \ "emails")
.getOrElse(Json.obj("ERR-EMAILS-VALUE"->"null")).toString()
Copy the code
6.5 Try converting between Case classes and JsonObj
/ / namespace | namespace
import play.api.libs.json._
// Create a case Class instance. | create an instance of User object.
val userObj = User("."."Kate"."JavaScript")
// Create Json in case class format. | create an instance of Json object in User format.
val userJson = Json.obj("_id"->"3"."userName"->"Tim"."department"->"Java")
// Convert userJson to User instance. | convert a User obj to User Json.
val objValue: JsResult[User] = Json.fromJson[User](userJson)
/ / in line with the type of User can be converted to Json. | convert a User Json to the User object.
val jsValue: JsValue = Json.toJson[User](userObj)
Copy the code
7. Use MongoDB as database (Windows platform)
π¦ official link: MongoDB
Downloading the.msi file saves you the need to configure environment variables yourself. Note that if you have an older version of the MongoDB database loaded on your machine, pay extra attention to the environment variables.
The play-Mongo component used in this framework requires MongoDB version to be at least 3.6. During the installation process, you can also choose to install an additional interface management tool, MongoDBCompassCommunity.
7.1 Running the MongoDB Service In Two Modes
7.1.2 Starting from the CLI
Specify the data storage path when starting the service.
C:\mongodb\bin\mongod --dbpath c:\data\db
Copy the code
7.1.3 Starting as a Service (Recommended)
A. Create a mongodb. CFG file and configure the path for storing logs and data.
systemLog:
destination: file
path: c:\data\log\mongod.log
storage:
dbPath: c:\data\db
Copy the code
- Do not use this parameter in the configuration file
Tab
Symbol, using Spaces. :
Behind the symbolsThe space.- The systemLog entry requires a configuration file, not a directory.
B. Then run CMD as administrator and type:
C:\mongodb\bin\mongod.exe --config C:\mongodb\mongod.cfg --install
Copy the code
- –config Specifies an absolute path. The file name depends on the actual configuration.
C. Run the following commands as an administrator (non-administrators will be denied access: 5) :
>net start MongoDB # Enable service
>net stop MongoDB # Stop service
>mongod --remove Remove this installed service.
Copy the code
7.2 Checking whether MongoDB is started Successfully
Enter http://127.0.0.1:27017/ in your browser. The default MongoDB port is 27017. If the service is started normally, the following information is displayed on the browser page:
It looks like you are trying to access MongoDB over HTTP on the native driver port.
7.3 Connecting the local MongoDB
Simply run the following command:
mongo
Copy the code
If the connection is successful, the command line window displays:
MongoDB shell version: x.x.x connecting to: test
7.4 Creating a MongoDB User
Create a root level user admin and a database user STD, and grant dbOwner read/write permissions to the database.
> db.createUser({user:"admin".pwd:"ljh20176714",roles:["root"]})
Successfully added user: { "user" : "admin"."roles" : [ "root" ] }
> db.createUser({user:"std".pwd:"ljh20176714",roles:[{role:"dbOwner".db:"studentDB"}]})
Successfully added user: {
"user" : "std"."roles": [{"role" : "dbOwner"."db" : "studentDB"}}] >Copy the code
8. Use Play mongo to build the MongDB driver
π¦Github website: Github Tutorial
Add the following dependencies to build.sbt:
LibraryDependencies += "cn. Playscala "% "play-mongo_2.12" % "0.3.0" addCompilerPlugin("org.scalamacros" % "paradise" % "2.1.0" cross CrossVersion. Full)Copy the code
Note: When SBT repeatedly prompts a not found error, in addition to switching images, consider whether the plug-in version does not match the current Scala version. To check this, view the supported versions by clicking on the RePO1 mirror repository link displayed on the console, and then adjust as appropriate.
Next, in the conf/application.conf file, add the MongoDB Settings.
# configuration dataBase connection | config your own dataBase source here. The mongo. Uri = "mongo: / / localhost: 27017 / studentDB"Copy the code
8.1 Using the annotation injection model
For details about this section, see the Play Mongo official tutorial.
Create module. scala in app/ directory, and configure the directory where all models are located in app/ Models.
import cn.playscala.mongo.Mongo
import com.google.inject.AbstractModule
class Module extends AbstractModule{
override def configure() :Unit= {
Mongo.setModelsPackage("models")}}Copy the code
Inject each model. Common-person in the annotation corresponds to collection in the MongoDB database. Person is every Document in that set.
-
Use case to declare the associated class as a template class, and the underlying layer provides the associated methods such as Apply, unapply, and so on.
-
Note that it is recommended to define the _ID for each Model. This field is used as the primary key for MongDB. If not, then MongoDB generates a random string.
package models
import cn.playscala.mongo.annotations.Entity
@Entity("common-person")
case class Person(_id :String,name:String,sno :String)
Copy the code
8.2 Modeling -Json conversion
Create package objects under app/ Models, provide Json -> template class ** inside (only works under the Models package) ** implicit conversion:
package object models {
implicit val personFormat = Json.format[Person]}Copy the code
9. Concurrent programming for Play
The concurrency mechanism of the Play 2.x framework depends on Akka (as does Spark’s underlying communication mechanism). When you use the Mongo driver to execute a query, it returns a Future[T]. It’s kind of like a view, and we only get the internal T if the thread actually executes the statement.
So to wait for a thread to return the result for us, we use await.result (..) To block it,
val maxAwaitTime = Duration(10000."millis")
def studentList = Action {
/ / attention! It returns a Future[List].
/ / for details please refer to the Scala asynchronous programming related content: Akka, Duration, and the Future. Await.
val eventualObjects: Future[List[JsObject]] = mongo.collection[Student].find[JsObject]().list()
// Block and wait, and return the final result.
val studentList: List[JsObject] = Await.result(eventualObjects, maxAwaitTime)
//Ok(JsArray(studentList))
Ok(views.html.students(studentList))
}
Copy the code
Deploy the Play2 framework
The Play framework can be packaged as a WAR package via plug-ins and deployed under a Tomcat server. But here we practice how to deploy with the SBT tool. To do that, we first need to configure The Play2 framework’s Secret. If this item is not configured, the Play 2 framework will fail to launch in the deployment environment.
Why configure it? The official website explains that it is a token used to defend against CSRF attacks, or used in encryption tools. There are two ways to do this. One is to add it directly to conf/application.conf in the project file (but this is not officially recommended), and the other is to add it as a parameter at startup. See the link attached to this section for details.
Configure the following lines in application.conf and set the password value by yourself.
play.http.secret.key = "Your own secret"
Copy the code
Additionally, for Windows users, it’s a good idea to add the LauncherJarPlugin to your project at build.sbt. Otherwise, the service may fail to start because the *. Bat parameters are too long.
lazy val root = (project in file(".")).enablePlugins(PlayScala,LauncherJarPlugin)
Copy the code
Simply run the SBT dist command at the project root and SBT will automatically package the Play2 project into a *.zip zip package. (I used IntelliJ IDEA, which provides a terminal window below. SBT will put the compressed package into.. \target\universal).
We just need to extract the compressed package, and then go to the /bin directory, you can directly find two startup scripts: for Windows environment, we just need to open the.bat batch file; For Linux, we can CD it to the bin directory and execute it (both script files are the same as your project name) :
$ sudo ./{scalaProject}
Copy the code
One additional note: if you encounter the not in gzip format problem when unpacking this package on Linux, do not use -z as the unpacking parameter.
$ sudo tar -xvf {yourZip} -C {path}
Copy the code
π¦ has official instructions for configuring Play Secret
π¦Play 2 is a full stack framework
π¦ Error gzip: stdin: not in gzip format is displayed when decompressing the JDK on Linux
11. Simplified version of Github links
The author generated the most “portable” version of the Play-mongodb project based on the Play Scala Seed, without any additional model layer, only MongoDBController based on a simple MongoDB configuration.
π¦ Play scala mongo seed
12. References
- OSCHINA:Play 2.0 user guide
- Blog Garden: Play2.6-Scala Guide
- Code cloud: a backend program based on PlayFramework2.5.4
- Playframework official
- IntelliJ IDEA several ways to create Play2 projects
- The PlayScala community in China
- Play For Scala Development Guide (2.6.x)
- Cross-domain issues that may arise in the future
- Dependency injection
- eBooks:Play for Scala
- OnlineView:Play for Scala
- Install the MongoDB service on the Windows operating system
- Problems encountered while installing MongoDB
- PlayFrameWork column
- MvnRepository
- Jnuit Class not found…
- CSRF protection
- Convert Json to Txt