熟悉的Hello World
新创建一个工程,了解下重要文件的结构
.\app
controllers\models\views
目前比较流行的MVC架构
.\conf
application.conf 工程配置,包括数据库连接等
routes 路由配置,用于解析URL
找到.\app\views\application\index.html
修改页面内容,添加一个输入框和一个按钮
#{extends 'main.html' /}
#{set title:'Home' /} <form action="@{Application.sayHello()}" method="Get">
<input type="text" name="myName" />
<input type="submit" value="Say Hello" />
</form>
#{extends 'main.html' /} 表示页面继承自 main.html
#{set title:'Home' /} 设置页面标题
运行程序,进入页面 localhost:9000, 会提示错误,No route able to invoke action Application.sayHello was found
在Application.java中添加sayHello方法
public static void sayHello(String myName) {
render(myName);
}
添加sayHello页面,在.\app\views\application 下添加sayHello.html
#{extends 'main.html' /}
#{set title:'Home' /} <h1>Hello ${myName?: 'guest'}!</h1>
<a href="@{Application.index()}">Back to form</a>
运行效果如下:
对URL进行优化 http://localhost:9000/application/sayhello?myName=Alex
配置路由 .\conf\routes
在 * /{controller}/{action} {controller}.{action} 后添加:
GET /hello Application.sayHello
可以使用新的URL访问页面 http://localhost:9000/hello?myName=Alex
自定义Layout
Layout是所有页面的公共部分,修改.\app\views\main.html
<body>
Hello World APP
<hr /> #{doLayout /}
</body>
#{doLayout /} 会替换sayHello.html中的内容
添加验证
修改sayHello方法
import play.data.validation.Required; public static void sayHello(@Required String myName) {
if(validation.hasErrors())
{
flash.error("Oops, please enter your name!");
index();
}
render(myName);
}
修改index.html,添加以下代码
#{if flash.error}
<p style="color:#c00">
${flash.error}
</p>
#{/if}
。。