Playframework with scala 入门

首先应当下载playframework,下载后解压缩,将play/play.bat文件所在目录加入到PATH环境变量中。

启动命令行, 输入 play install scala,过程中确保你的网络没有问题。你会看到控制台稀里哗啦的在下载。如果出现网络问题使自动安装失败,也别泄气,到这里找到源码,按说明build一个,之后拷贝到playframework目录下的modules目录中,貌似就可以了哦,未查证。

接下来使用下面的命令 play new bingle --with scala 创建一个新项目名为bingle,--with scala参数使得这个项目将具备scala模块的支持。几行控制台文字滚过之后,在运行下面这句

play run bingle, 就又有几行滚过去,其中应该有这句:Scala support is active. 还有这句:Listening for HTTP on port 9000 ...。ok, 打开浏览器地址栏,输入http://localhost:9000,你看到一个页面头部斗大字写着:

Your Scala application is ready!

这个视图是内建在scala之中的,接下来我们花店时间研究一下这个页面是怎么出来的。

第一个线索是conf/routes文件,其中一行是:

GET     /                                       Application.index

这行字配置了一个简单路由,意思是,http://localhost:9000/这个请求将有Application.index处理。 那么Application.index是啥呢? 打开controllers.scala文件我们看到这段

package controllers

import play._
import play.mvc._

object Application extends Controller {
    
    import views.Application._
    
    def index = {
        html.index("Your Scala application is ready!")
    }
    
}

  我们看到Application是一个object,也就是一个单例对象,大体相当于java中的一个静态类(这样说并不确切,只是为了便于理解)。index是这个对象的一个方法,它返回html.index("You Scala application is ready."),它表示将使用app/views/Application目录下的index.scala.html为模板来生成html返回给客户端。“Your Scala application is ready." 这个字符串显然是传递给模板的参数了。 我们来看一眼index.scala.html

@(title:String)

@main(title) {
    
    @views.defaults.html.welcome(title)
    
}

playframework的scala模板,它可以由scala代码段和html混合起来编写,scala负责填充内容,html负责页面布局。@符号后面的是scala代码。这相当于jsp中的<% %>,区别是,你不需要去使用闭合标签,模板自身会判断scala代码段的起始点。事实上这个模板最终会被翻译为一个函数,函数的参数列表需要在第一行声明。我们这里只有一个名为title的String型参数。那么到这里,差不多明了了,上面的controller Application.index中的 html.index,其实就是调用了views.Application.html包内的一个名为index的函数(好吧, 这么说其实不对,不过你可以暂时这样理解,真实的情况是调用了views.Application.html包下面的index单例对象的apply方法,这样说,我想大家都满意了),把一个串扔给它,然后这个函数生成了一个html文本,返回给客户端,于是为名看到了页面上那行醒目的字。

然后是这句

@main(title) {
    
    @views.defaults.html.welcome(title)
    
}

  举一反三我们就知道了,这是在找一个叫做main的.scala.html的模板了,没错。他就在app/views目录下面。

@(title:String = "")(body: => Html)

<!DOCTYPE html>
<html>
    <head>
        <title>@title</title>
        <link rel="stylesheet" media="screen" href="@asset("public/stylesheets/main.css")">
        <link rel="shortcut icon" type="image/png" href="@asset("public/images/favicon.png")">
        <script src="@asset("public/javascripts/jquery-1.5.2.min.js")" type="text/javascript"></script>
    </head>
    <body>
        @body
    </body>
</html>

  看到了,其实跟index.scala.html一样,第一行是参数列表声明,不过这里咋有两个参数呢?第一个title我们知道是从controller哪里一层层扔过来的,那后面的body是个啊? 好吧,这玩意儿其实就是scala语法中的curry化参数,恩,简单来说就是一个函数又俩参数,我们一般这样写 def function(a,b),那现在换个写法,def function(a)(b) ,其实一个意思,暂时先这样理解好了。那说到这,我想大家明白了,上面index.scala.html中的main(title){/*代码略*/}其实就是一个简单的函数调用嘛,传了两个参数进来,其中第二个参数是一个Html类型(这是play-scala提供的api了),并且这个参数被拿来替换掉body标签下的@body了,于是整个页面就渲染出来啦。{}里面那句

@views.defaults.html.welcome(title) 

  就是用来生成body中间的内容了。

实际上所有的模板都是先被翻译成scala文件,然后再编译成class的,项目运行时我们能找到tmp/generated目录,下面能找到所有的由.scala.html翻译成的scala文件。贴一个views.defaults.html.welcome.scala的代码在这里凑字数

                    package views.defaults.html

import play.templates._
import play.templates.TemplateMagic._
import views.html._

object welcome extends BaseScalaTemplate[Html,Format[Html]](HtmlFormat) {

def apply/*1.2*/(title:String):Html = {
try {
_display_ {

format.raw/*1.16*/("""

<link rel="stylesheet" href="""")+_display_(/*3.31*/asset("public/playmanual/manual.css"))+format.raw/*3.68*/("""" type="text/css" media="screen" charset="utf-8">
<link rel="stylesheet" href="""")+_display_(/*4.31*/asset("public/playmanual/wiki.css"))+format.raw/*4.66*/("""" type="text/css" media="screen" charset="utf-8">

<div class="wrapper">

<div id="docSidebar">

<div id="logo">
<img src="""")+_display_(/*11.24*/asset("public/playmanual/logo.png"))+format.raw/*11.59*/("""">
<h2 id="version">Play """)+_display_(/*12.36*/play/*12.40*/.Play.version)+format.raw/*12.53*/("""</h2>
</div>

<h2>Browse</h2>
<ul>
<li id="gotoc"><a href="/@documentation/home">Local documentation</a></li>
<li id="gotoc"><a href="/@documentation/modules/scala/home">Scala module documentation</a></li>
<li id="gotoc"><a href="/@api/index.html">Browse Java API</a></li>
</ul>

<h2>Contents</h2>
<div id="toc"></div>

<h2>Search</h2>
<p>Get help with google</p>
<div id="searchBox"><form action="http://www.google.com/cse" id="cse-search-box"><div><input type="hidden" name="cx" value="002614023023983855063:jn1mu_7bof0" /><input type="hidden" name="ie" value="UTF-8" /><input type="text" name="q" size="28" style="font-size:14px"/></div></form><script type="text/javascript" src="http://www.google.com/coop/cse/brand?form=cse-search-box&lang=en"></script></div>

</div>

<div id="pageContent">

<div class="wikistyle">
<h1>""")+_display_(/*34.18*/title)+format.raw/*34.23*/("""</h1>
<p>
Congratulation, you've just created a new Scala Play application. This page will help you in the few next steps.
</p>
<h2><a name="why">Why do you see this page?</a></h2>
<p>
The <strong>conf/routes</strong> file defines a route that tell play to invoke the <strong>Application.index</strong> action
when a browser requests the <strong>/</strong> URI using the <strong>GET</strong> method:
</p>
<pre><code># Application home page
GET / Application.index</code></pre>
<p>
So play has invoked the <strong>controllers&#46;Application&#46;index</strong> method:
</p>
<pre><code>package controllers

import play._
import play.mvc._

object Application extends Controller """)+format.raw("""{""")+format.raw/*53.40*/("""

import views.Application._

def index = """)+format.raw("""{""")+format.raw/*57.18*/("""
html.index("Your Scala application is ready!")
""")+format.raw("""}""")+format.raw/*59.6*/("""

""")+format.raw("""}""")+format.raw/*61.2*/("""</code></pre>
<p>
The action returns the HTML content generated by the <strong>views.Application.html.index</strong> template.
This template is defined in the <strong>app/views/Application/index.scala.html</strong> file:
</p>
<pre><code>@(title:String)

@main(title) """)+format.raw("""{""")+format.raw/*68.16*/("""

@views.defaults.html.welcome(title)

""")+format.raw("""}""")+format.raw/*72.2*/("""</code></pre>
<p>
This template extends the <strong>app/views/main.scala.html</strong> template, and call <strong>views.defaults.html.welcome</strong> to display this
welcome page.
</p>
<h2><a name="db">Need to connect to a database?</a></h2>
<p>
You can quickly set up a developement database (either in memory or written to the filesystem), by adding one of these
lines to the <strong>conf/application.conf</strong> file:
</p>
<pre><code># For a transient in memory database (H2 in memory)
db=mem

# for a simple file written database (H2 file stored)
db=fs</code></pre>
<p>
If you want to connect to an existing <strong>MySQL5 server</strong>, use:
</p>
<pre><code>db=mysql:user:pwd@database_name</code></pre>
<p>
If you need to connect to another JDBC compliant database, first add the corresponding driver library to the
<strong>lib/</strong> directory of your application, and add these lines to the <strong>conf/application.conf</strong> file:
</p>
<pre><code>db.url=jdbc:postgresql:database_name
db.driver=org.postgresql.Driver
db.user=root
db.pass=secret</code></pre>
<h2><a name="doc">Need more help?</a></h2>
<p>
When your application run in <strong>DEV</strong> mode, you can access directly the current documentation at the
<a href="/@documentation">/@documentation</a> URL or go to <a href="http://www.playframework.org">http://www.playframework.org</a>.
</p>
<p>
The Scala specific documentation is available at <a href="/@documentation/modules/scala/home">/@documentation/modules/scala/home</a>
</p>
<p>
The <a href="http://groups.google.com/group/play-framework">Play Google Group</a> is where Play users come to seek help, announce projects, and discuss.
If you don't have any google account, you can still join the mailing list sending an email to
<br/><strong>play-framework+subscribe@googlegroups.com</strong>.
</p>
</div>
</div>

</div>

</div>

</div>

<script type="text/javascript" src="""")+_display_(/*121.38*/asset("public/playmanual/jquery-1.3.2.min.js"))+format.raw/*121.84*/(""""></script>
<script type="text/javascript" src="""")+_display_(/*122.38*/asset("public/playmanual/navigation.js"))+format.raw/*122.78*/(""""></script>
""")}
} catch {
case e:TemplateExecutionError => throw e
case e => throw Reporter.toHumanException(e)
}
}

}


/*
-- GENERATED --
DATE: Sun Sep 25 22:33:08 CST 2011
SOURCE: /app/views/defaults/welcome.scala.html
HASH: 82f0ff4ad533d5473bed384fbba122fa8ca7b61d
MATRIX: 328->1|449->15|507->47|564->84|670->164|725->199|908->355|964->390|1045->444|1058->448|1092->461|2082->1427|2108->1432|3016->2293|3114->2344|3221->2405|3270->2408|3654->2747|3744->2792|6152->5178|6220->5224|6297->5273|6359->5313
LINES: 10->1|14->1|16->3|16->3|17->4|17->4|24->11|24->11|25->12|25->12|25->12|47->34|47->34|66->53|70->57|72->59|74->61|81->68|85->72|134->121|134->121|135->122|135->122
-- GENERATED --
*/



OK,到此为止,对于play-scala的模板机制,我想大家应该了然了。 先到这里,下一节会尝试修改页面布局,创建一个自己的页面,并重用其中的一些元素。

posted on 2011-09-26 22:40  nixil  阅读(2044)  评论(0)    收藏  举报