表单的基本操作
play Framwork 中表单的使用包括表单可视化和表单数据的读取
表单可视化
方式一:直接使用html书写表单
@(loginmessage:String)
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>login</title>
</head>
<body>
<h2>@loginmessage</h2>
<form method="post" name="login">
用户名:<input type="text" name="username1">
密码:<input type="password" name="password" maxlength="16" minlength="6">
<input type="submit" value="提交">
</form>
</body>
</html>
方式2:通过Form类生成表单
这种方法较为麻烦
首先要在controller类中接入play.api.i18n.I18nSupport 特性
class LoginController @Inject()(cc:ControllerComponents) extends AbstractController (cc) with play.api.i18n.I18nSupport{
val userForm = Form(
mapping(
"username" -> text,
"password" -> text
)(UserData.apply)(UserData.unapply)
)
另外还要使用模板生成html(注意<都没有写因为与markdown格式定义冲突)
@(userForm: Form[UserData],loginMessage:String)(implicit request: RequestHeader, messagesProvider: MessagesProvider)
!DOCTYPE html>
html>
head lang=”en”>
meta charset=”UTF-8”>
title>login
/head>
body>
h2>@loginMessage/h2>
@helper.form(action = routes.LoginController.loginPost()){
@helper.CSRF.formField
@helper.inputText(userForm(“username”))
@helper.inputPassword(userForm(“password”))
input type=”submit” value=”提交”>
}
@form method=”post” name=”login”>@
@用户名:input type=”text” name=”username”>@
@密码:input type=”password” name=”password”>@
@input type=”submit” value=”提交”>@
@/form>@
/body>
/html>
form数据读取
val userForm = Form(
mapping(
"username" -> text,
"password" -> text
)(UserData.apply)(UserData.unapply)
)
def login = Action{implicit request=>
Ok(views.html.login2(userForm,"请登陆"))
}
def loginPost = Action {implicit request: Request[AnyContent] =>
val userData = userForm.bindFromRequest().get
val result_succeed = Json.obj("result"->"登陆成功")
if(userData.password == "950730"&&userData.username=="zhangchi") {
Ok(result_succeed)
}
else {
Ok(views.html.login2(userForm,"登陆失败,用户名或密码错误"))
}
}