- 浏览: 2551104 次
- 性别:
- 来自: 成都
文章分类
最新评论
-
nation:
你好,在部署Mesos+Spark的运行环境时,出现一个现象, ...
Spark(4)Deal with Mesos -
sillycat:
AMAZON Relatedhttps://www.godad ...
AMAZON API Gateway(2)Client Side SSL with NGINX -
sillycat:
sudo usermod -aG docker ec2-use ...
Docker and VirtualBox(1)Set up Shared Disk for Virtual Box -
sillycat:
Every Half an Hour30 * * * * /u ...
Build Home NAS(3)Data Redundancy -
sillycat:
3 List the Cron Job I Have>c ...
Build Home NAS(3)Data Redundancy
Play framework and Validation
In our API, we handle JSON format request body, some path parameters, some query parameters.
In play framework, we use JSON implicit methods to validation the input JSON request body. For path parameters, I validate it in my actions in controllers.
Here is how I do it.
/* basic */
implicit val jodaDateWrites = Writes.dateWrites("yyyy-MM-dd'T'HH:mm:ssXXX")
implicit val jodaDateReads = Reads.dateReads("yyyy-MM-dd'T'HH:mm:ssXXX")
implicit val LocationWrites = Json.writes[Location]
implicit val LocationReads: Reads[Location] = (
(JsPath \ "addressLine1").readNullable[String] and
(JsPath \ "addressLine2").readNullable[String] and
(JsPath \ "city").readNullable[String] and
(JsPath \ "state").readNullable[String] and
(JsPath \ "country").readNullable[String] and
(JsPath \ "postalCode").readNullable[String] and
(JsPath \ "latitude").readNullable[String] and
(JsPath \ "longitude").readNullable[String]
)(Location.apply _)
implicit val JobPostBudgetRequestReads: Reads[JobPostBudgetRequest] = {
(
(JsPath \ "budget").read[BigDecimal] and
(JsPath \ "budgetType").read[String](Reads.minLength[String](1)) and
(JsPath \ "cpaPrice").read[BigDecimal](Reads.min(BigDecimal.apply(0.01)))
)(JobPostBudgetRequest.apply _)
}
implicit val JobPostDetailRequestReads: Reads[JobPostDetailRequest] = (
(JsPath \ "accountID").readNullable[String] and
(JsPath \ "referenceID").read[String](Reads.minLength[String](1)) and
(JsPath \ "title").read[String](Reads.minLength[String](1)) and
(JsPath \ "description").read[String](Reads.minLength[String](1)) and
(JsPath \ "companyName").readNullable[String] and
(JsPath \ "locations").read[Seq[Location]] and
(JsPath \ "startTime").readNullable[Date] and
(JsPath \ "stopTime").readNullable[Date] and
(JsPath \ "emailAddress").read[String](Reads.minLength[String](1)) and
(JsPath \ "hostedByJ2C").read[Boolean] and
(JsPath \ "applyURL").read[String](Reads.minLength[String](1)) and
(JsPath \ "requireResume").read[Boolean]
)(JobPostDetailRequest.apply _)
implicit val JobStatusRequestReads: Reads[JobStatusRequest] = (
(JsPath \ "status").read[String](Reads.minLength[String](4) keepAnd Reads.maxLength[String](7)).map(
JobStatusRequest.apply _)
)
implicit val JobPostRequestReads: Reads[JobPostRequest] = (
(JsPath \ "jobDetail").read[JobPostDetailRequest] and
(JsPath \ "jobBudget").read[JobPostBudgetRequest]
)(JobPostRequest.apply _)
First of all, when we define the scala case class to matching with the JSON format, Option make this parameter optional. And in this implicit file, we define something like Reads.minLength[String](4) or some other requirements. That is the validation when we doing the JSON parse.
In the controller, sometimes we handle the JSON parse validation like this and we do further validation as well.
val obj = request.body.validate[JobDetailUpdateRequest]
obj.fold(
errors => {
BadRequest(Json.toJson(new ErrorResponse("INVALID_JSON_REQUEST", "Bad JSON request parameters.", JsError.toJson(errors).toString())))
},
jobDetailUpdateRequest => {
logger.trace("Param validation success, param = " + jobDetailUpdateRequest)
jobDetailUpdateRequest.emailAddress match {
case Some(e) if !checkEmail(e)=> {
BadRequest(Json.toJson(new ErrorResponse("INVALID_EMAIL_ADDRESS", "emailAddress invalid " + e + " .", "")))
}
case _ => {
try{
val jobResponse = JobOldService.updateJob(campaignID, jobDetailUpdateRequest)
jobResponse match {
case Some(res) => Ok(Json.toJson(res))
case _ => { NotFound(Json.toJson(new ErrorResponse(
"RESOURCE_NOT_FIND",
"Can not find the resource with campaignID = " + campaignID + " referenceID = " + referenceID,
"")
))
}
}
}catch{
case ex:Exception => {
InternalServerError(Json.toJson(new ErrorResponse("SERVER_ERROR", "", ex.getMessage)))
}
}
}
}
}
)
checkEmail is the customized validation I implement myself.
References:
https://www.playframework.com/documentation/2.4.x/ScalaJsonCombinators
In our API, we handle JSON format request body, some path parameters, some query parameters.
In play framework, we use JSON implicit methods to validation the input JSON request body. For path parameters, I validate it in my actions in controllers.
Here is how I do it.
/* basic */
implicit val jodaDateWrites = Writes.dateWrites("yyyy-MM-dd'T'HH:mm:ssXXX")
implicit val jodaDateReads = Reads.dateReads("yyyy-MM-dd'T'HH:mm:ssXXX")
implicit val LocationWrites = Json.writes[Location]
implicit val LocationReads: Reads[Location] = (
(JsPath \ "addressLine1").readNullable[String] and
(JsPath \ "addressLine2").readNullable[String] and
(JsPath \ "city").readNullable[String] and
(JsPath \ "state").readNullable[String] and
(JsPath \ "country").readNullable[String] and
(JsPath \ "postalCode").readNullable[String] and
(JsPath \ "latitude").readNullable[String] and
(JsPath \ "longitude").readNullable[String]
)(Location.apply _)
implicit val JobPostBudgetRequestReads: Reads[JobPostBudgetRequest] = {
(
(JsPath \ "budget").read[BigDecimal] and
(JsPath \ "budgetType").read[String](Reads.minLength[String](1)) and
(JsPath \ "cpaPrice").read[BigDecimal](Reads.min(BigDecimal.apply(0.01)))
)(JobPostBudgetRequest.apply _)
}
implicit val JobPostDetailRequestReads: Reads[JobPostDetailRequest] = (
(JsPath \ "accountID").readNullable[String] and
(JsPath \ "referenceID").read[String](Reads.minLength[String](1)) and
(JsPath \ "title").read[String](Reads.minLength[String](1)) and
(JsPath \ "description").read[String](Reads.minLength[String](1)) and
(JsPath \ "companyName").readNullable[String] and
(JsPath \ "locations").read[Seq[Location]] and
(JsPath \ "startTime").readNullable[Date] and
(JsPath \ "stopTime").readNullable[Date] and
(JsPath \ "emailAddress").read[String](Reads.minLength[String](1)) and
(JsPath \ "hostedByJ2C").read[Boolean] and
(JsPath \ "applyURL").read[String](Reads.minLength[String](1)) and
(JsPath \ "requireResume").read[Boolean]
)(JobPostDetailRequest.apply _)
implicit val JobStatusRequestReads: Reads[JobStatusRequest] = (
(JsPath \ "status").read[String](Reads.minLength[String](4) keepAnd Reads.maxLength[String](7)).map(
JobStatusRequest.apply _)
)
implicit val JobPostRequestReads: Reads[JobPostRequest] = (
(JsPath \ "jobDetail").read[JobPostDetailRequest] and
(JsPath \ "jobBudget").read[JobPostBudgetRequest]
)(JobPostRequest.apply _)
First of all, when we define the scala case class to matching with the JSON format, Option make this parameter optional. And in this implicit file, we define something like Reads.minLength[String](4) or some other requirements. That is the validation when we doing the JSON parse.
In the controller, sometimes we handle the JSON parse validation like this and we do further validation as well.
val obj = request.body.validate[JobDetailUpdateRequest]
obj.fold(
errors => {
BadRequest(Json.toJson(new ErrorResponse("INVALID_JSON_REQUEST", "Bad JSON request parameters.", JsError.toJson(errors).toString())))
},
jobDetailUpdateRequest => {
logger.trace("Param validation success, param = " + jobDetailUpdateRequest)
jobDetailUpdateRequest.emailAddress match {
case Some(e) if !checkEmail(e)=> {
BadRequest(Json.toJson(new ErrorResponse("INVALID_EMAIL_ADDRESS", "emailAddress invalid " + e + " .", "")))
}
case _ => {
try{
val jobResponse = JobOldService.updateJob(campaignID, jobDetailUpdateRequest)
jobResponse match {
case Some(res) => Ok(Json.toJson(res))
case _ => { NotFound(Json.toJson(new ErrorResponse(
"RESOURCE_NOT_FIND",
"Can not find the resource with campaignID = " + campaignID + " referenceID = " + referenceID,
"")
))
}
}
}catch{
case ex:Exception => {
InternalServerError(Json.toJson(new ErrorResponse("SERVER_ERROR", "", ex.getMessage)))
}
}
}
}
}
)
checkEmail is the customized validation I implement myself.
References:
https://www.playframework.com/documentation/2.4.x/ScalaJsonCombinators
发表评论
-
Stop Update Here
2020-04-28 09:00 315I will stop update here, and mo ... -
NodeJS12 and Zlib
2020-04-01 07:44 475NodeJS12 and Zlib It works as ... -
Docker Swarm 2020(2)Docker Swarm and Portainer
2020-03-31 23:18 367Docker Swarm 2020(2)Docker Swar ... -
Docker Swarm 2020(1)Simply Install and Use Swarm
2020-03-31 07:58 368Docker Swarm 2020(1)Simply Inst ... -
Traefik 2020(1)Introduction and Installation
2020-03-29 13:52 335Traefik 2020(1)Introduction and ... -
Portainer 2020(4)Deploy Nginx and Others
2020-03-20 12:06 429Portainer 2020(4)Deploy Nginx a ... -
Private Registry 2020(1)No auth in registry Nginx AUTH for UI
2020-03-18 00:56 435Private Registry 2020(1)No auth ... -
Docker Compose 2020(1)Installation and Basic
2020-03-15 08:10 373Docker Compose 2020(1)Installat ... -
VPN Server 2020(2)Docker on CentOS in Ubuntu
2020-03-02 08:04 454VPN Server 2020(2)Docker on Cen ... -
Buffer in NodeJS 12 and NodeJS 8
2020-02-25 06:43 384Buffer in NodeJS 12 and NodeJS ... -
NodeJS ENV Similar to JENV and PyENV
2020-02-25 05:14 475NodeJS ENV Similar to JENV and ... -
Prometheus HA 2020(3)AlertManager Cluster
2020-02-24 01:47 421Prometheus HA 2020(3)AlertManag ... -
Serverless with NodeJS and TencentCloud 2020(5)CRON and Settings
2020-02-24 01:46 336Serverless with NodeJS and Tenc ... -
GraphQL 2019(3)Connect to MySQL
2020-02-24 01:48 246GraphQL 2019(3)Connect to MySQL ... -
GraphQL 2019(2)GraphQL and Deploy to Tencent Cloud
2020-02-24 01:48 450GraphQL 2019(2)GraphQL and Depl ... -
GraphQL 2019(1)Apollo Basic
2020-02-19 01:36 326GraphQL 2019(1)Apollo Basic Cl ... -
Serverless with NodeJS and TencentCloud 2020(4)Multiple Handlers and Running wit
2020-02-19 01:19 312Serverless with NodeJS and Tenc ... -
Serverless with NodeJS and TencentCloud 2020(3)Build Tree and Traverse Tree
2020-02-19 01:19 317Serverless with NodeJS and Tenc ... -
Serverless with NodeJS and TencentCloud 2020(2)Trigger SCF in SCF
2020-02-19 01:18 292Serverless with NodeJS and Tenc ... -
Serverless with NodeJS and TencentCloud 2020(1)Running with Component
2020-02-19 01:17 311Serverless with NodeJS and Tenc ...
相关推荐
PlayFramework的验证机制使用了play.data.validation包下的ValidationAPI来实现。开发者可以调用play.data.validation.Validation类的静态方法来对数据进行校验。当数据不符合验证规则时,ValidationAPI会生成一个...
Play Framework 是一个开源的Web应用框架,以Java和Scala为后盾,致力于提供简洁、高效、可测试的开发体验。本文将深入探讨Play Framework的基本概念、常用命令、Eclipse调试方法、模式、控制器、工具包、session...
Play Framework的验证机制允许开发者在多个层次上对数据进行验证,确保应用程序的数据质量和安全性。它可以轻松地集成到控制器和模型中,提供了丰富的验证规则和自定义验证的能力,使得开发更加高效且可控。通过这些...
Localised validation messages 局部验证消息 - 55 - 验证消息参数 - 55 - 定制局部验证消息 - 56 - 定制teral(非局部)验证消息 - 57 - 在模板里显示验证错误消息 - 57 - 验证注释 - 60 - 验证复杂对象 - 60 - 内...
Explains the role of Controllers in the MVC framework and what role models play in binding and data access strategies Demonstrates how to display and process forms Covers the new features added in ...
- **验证**:项目中的验证可能是使用Play的内置验证库,如`play.data.validation.Constraints`,对用户输入进行检查。 5. **运行与调试** - **启动应用**:在MyEclipse中右键项目,选择Run As > Play 2 ...
在IT领域,Play框架是一个非常受欢迎的开源Java和Scala Web应用程序框架,它基于MVC(模型-视图-控制器)架构模式。Play2-HTML5Tags是针对Play框架的一个扩展,专注于提供HTML5表单标签的支持,使得开发人员在构建...
3. **与Play Framework的集成**:作为Play框架的扩展,Scala-Validator无缝集成到了Play的请求处理流程中。这意味着你可以直接在控制器方法中使用它,无需额外的代码适配。 4. **类型安全**:Scala语言的静态类型...
4. **Validation Framework**:内置的验证框架可以帮助开发者实现数据验证,可以定义在Action类或者XML配置文件中,提供了丰富的错误处理机制。 5. **Internationalization (i18n)**:Struts2支持多语言,通过资源...
Struts经典教程:深入理解Struts框架 在Java Web开发领域,Struts框架作为三大架构之一,以...Struts虽然已经有些年代,但其设计理念和架构模式对于理解现代Web框架如Spring MVC、Play Framework等仍有重要参考价值。
10. **Validation Framework**:提供了表单验证功能,可以在服务器端对用户输入进行检查,确保数据的准确性和安全性。 在使用Struts 1.3.8时,开发者需要注意以下几点: - **依赖管理**:Struts 1.3.8可能依赖于...
Struts是一个开源的...然而,掌握Struts对于理解其他现代Web框架,如Spring MVC或Play Framework,都是非常有帮助的。实际操作项目和编写代码是学习的最佳方式,理论与实践相结合,才能更好地理解和运用Struts框架。
不过,值得注意的是,Struts 1.2.0已经是较旧的版本,现代的Web应用更倾向于使用更新的框架如Spring MVC或Play Framework。尽管如此,理解Struts 1.2.0的工作原理对于学习Web开发的历史和理解MVC架构仍然很有价值。
不过,随着Spring MVC和Play Framework等现代框架的崛起,Struts的市场份额逐渐被侵蚀,但其设计理念和模式仍然对Java Web开发有着深远的影响。理解和掌握Struts可以帮助开发者更好地理解MVC模式,为学习其他框架...
然而,随着技术的发展,Struts也面临一些挑战,如性能问题、安全漏洞(如Struts2的CVE-2017-5638漏洞),以及Spring MVC、Play Framework等现代框架的崛起,使得Struts在新的项目中可能不再是首选。尽管如此,了解和...
在学习Struts1的过程中,可以深入理解Web开发中的请求处理、数据验证、国际化、异常处理等关键概念,这对于后续学习其他现代框架,如Spring MVC、Struts2或Play Framework等,都将大有裨益。同时,熟悉Struts1的...
3. **替代框架**:随着Spring MVC和Play Framework等新型框架的崛起,Struts的市场份额逐渐被侵蚀。 Struts的发展也催生了Struts2,它吸取了Struts1的经验教训,提供了更强大的特性,如OGNL表达式语言、拦截器等,...
Struts2.0 是一个基于MVC(Model-View-Controller)设计模式的Java Web应用程序...随着技术的发展,虽然现在有许多其他框架如Spring MVC和Play Framework等,但Struts2.0的历史地位和其对Java Web开发的贡献不容忽视。
Struts2.0 是一款基于MVC(Model-View-Controller)设计模式的Java Web框架,用于构建可...尽管随着时间的推移,Spring MVC和Play Framework等其他框架逐渐崛起,但Struts2在许多现有的项目中仍然占据着重要的地位。