Play Framework介绍:Hello World(1)(3)
分享于 点击 9125 次 点评:178
自定义布局
可以修改模板更改布局。编辑helloworld/app/views/main.html文件:
添加验证
给form添加一个验证,要求name字段必填。我们通过Play validation实现。编辑helloworld/app/controllers/Application.java,在sayHello action处:
- public static void sayHello(@Required String myName) {
- if (validation.hasErrors()) {
- flash.error("Oops, please enter your name!");
- index();
- }
- render(myName);
- }
并import play.data.validation.*。@Required告诉Play自动检查myName字段是否填写。如果验证失败,我们加入一条消息到flash scope中并重定向到index动作。flash scope允许在重定向时保持消息。
编辑helloworld/app/views/Application/index.html显示错误消息
- #{extends 'main.html' /}
- #{set title:'Home' /}
- #{if flash.error}
- <p style="color:#c00">
- ${flash.error}
- </p>
- #{/if}
- <form action="@{Application.sayHello()}" method="GET">
- <input type="text" name="myName" />
- <input type="submit" value="Say hello!" />
- </form>
输入空参数并提交,OK起作用了。
自动化测试
Selenium Test
在测试模式下运行应用。在cmd中输入play test helloworld。
打开浏览器,输入http://localhost:9000/@tests启动测试器。
执行测试
Selenium测试用例通常写成一个html文件。Play使用Play模板引擎生成这些文件。helloworld/test/Application.test.html文件:
- *{ You can use plain selenium command using the selenium tag }*
- #{selenium}
- // Open the home page, and check that no error occured
- open('/')
- assertNotTitle('Application error')
- #{/selenium}
此测试打开home页,确认响应中没有“Application error”。
让我们来编写自己的测试。编辑测试内容:
- *{ You can use plain selenium command using the selenium tag }*
- #{selenium}
- // Open the home page, and check that no error occurred
- open('/')
- assertNotTitle('Application error')
- // Check that it is the form
- assertTextPresent('The Hello world app.')
- // Submit the form
- clickAndWait('css=input[type=submit]')
- // Check the error
- assertTextPresent('Oops, please enter your name!')
- // Type the name and submit
- type('css=input[type=text]', 'bob')
- clickAndWait('css=input[type=submit]')
- // Check the result
- assertTextPresent('Hello bob!')
- assertTextPresent('The Hello world app.')
- // Check the back link
- clickAndWait('link=Back to form')
- // Home page?
- assertTextNotPresent('Hello bob!')
- #{/selenium}
重新执行
用户点评