Play之Scala-Web项目运行流程-简单分析(2)

为了方便开发,咱们将此工程转化为Eclipse项目,而后经过sftp下载到本地并导入到Eclipse里分析! html

若是您的项目还在运行,就关了(经过Ctr+C吧)它,而后进入play命令行下: java

[root@centos6-vb eee]# ls
app  build.sbt  conf  logs  project  public  README  target  test
[root@centos6-vb eee]# /opt/play/play-2.2.2/play 
[info] Loading project definition from /data/workspace/eee/project
[info] Set current project to eee (in build file:/data/workspace/eee/)
       _
 _ __ | | __ _ _  _
| '_ \| |/ _' | || |
|  __/|_|\____|\__ /
|_|            |__/

play 2.2.2 built with Scala 2.10.3 (running Java 1.7.0_17), http://www.playframework.com

> Type "help play" or "license" for more information.
> Type "exit" or use Ctrl+D to leave this console.

[eee] $ eclipse
[info] About to create Eclipse project files for your project(s).
[info] Successfully created Eclipse project files for project(s):
[info] eee
[eee] $

导出到本地Windows开发环境下(不会的看我另外一篇博客:SecureCRT与sftp) 编程

--------------------------------------------------------------------------------------------------- centos

下面是咱们导入到Eclipse后的项目结构:(若是导入不成功的话,就在Eclipse里新建工程,名字和那个工程一致,就能行了) api

1、路由 浏览器

有过Rails编程经验的人都知道路由这个概念,路由的功能就是寻路--用户发起一个请求怎么能被正确处理?就靠它了!咱们看看路由配置信息: mvc

# Routes
# This file defines all application routes (Higher priority routes first)
# ~~~~

# Home page
GET     /                           controllers.Application.index

# Map static resources from the /public folder to the /assets URL path
GET     /assets/*file               controllers.Assets.at(path="/public", file)

只关注:  GET     /       controllers.Application.index   这条信息就行了,指明了在默认缺省状况下,经过get命令所指向的处理Controller处理 app

controllers.Application的逻辑: 框架

package controllers

import play.api._
import play.api.mvc._

object Application extends Controller {

  def index = Action {
    Ok(views.html.index("Your new application is ready."))
  }

}

index是Controller "Application" 的一个action(action的概念不说了),只有一条语句: eclipse

Ok(views.html.index("Your new application is ready."))

看经典介绍:
任何Action对象必须得到反返回的Result对象
Ok继承于Result对象,因此返回Ok表示其包含的内容为HTTP 200 OK状态(在Scala里默认返回最后一行)

咱们如今无论上面的OK里的内容,咱们先从最简单的开始学习,把那行改成:

Ok("欢迎使用Play!")

上传后运行查看浏览器结果:

由于此时传入Ok中对象类型为String,Ok将其Content-type做为text/plain输出

再改一下:

import play.api.templates._

Ok(Html("<strong>欢迎使用Play!</strong>"))

运行效果:

此须要返回并告知Ok这是段Html格式内容而非纯文本。

到此,咱们暂时先这么总结:

浏览器 ( http://localhost:9000/ )-> Play 框架 (conf/routes) -> 对应的Controller代码 (app/controllers/Application.scala) -> 对应的返回Action (def index = Action {...}) 的方法 -> 对应的可返回Result的代码 (OK(...)) -> 要返回的正文内容 ( "..." 纯文本 或 Html("...) HTML格式)

参考博客:

Scala语言与Play框架入门教程 (初稿)http://cn.tanshuai.com/a/getting-started-scala-play

相关文章
相关标签/搜索