本文整理汇总了Scala中play.api.mvc.Controller类的典型用法代码示例。如果您正苦于以下问题:Scala Controller类的具体用法?Scala Controller怎么用?Scala Controller使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Controller类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: TitleController
//设置package包名称以及导入依赖的类
package controllers.common.util.demographics
import domain.common.demographics.Title
import play.api.libs.json.Json
import play.api.mvc.{Action, Controller}
import services.common.demographics.TitleService
class TitleController extends Controller{
def createOrUpdate = Action.async(parse.json){
request => val input = request.body
println("THE INPUT IS ", input)
val entity = Json.fromJson[Title](input).get
val response = for {
result <- TitleService.apply.createOrUpdate(entity)
}yield result
response.map(ans=>Ok(Json.toJson(entity))).recover{
case e:Exception=>InternalServerError
}
}
def getTitle(titleId:String) = Action.async{
request => val response = for {
result <- TitleService.apply.getTitleById(titleId)
}yield result
response.map(ans=>Ok(Json.toJson(ans))).recover{
case e:Exception=>InternalServerError
}
}
}
示例2: VersionController
//设置package包名称以及导入依赖的类
package controllers
import git.GitInfo
import play.api.libs.json.Json
import play.api.mvc.{Action, Controller}
class VersionController extends Controller {
def index = Action {
Ok(
Json.obj(
"lastCommit" -> Json.obj(
"branch" -> GitInfo.currentBranch(),
"message" -> GitInfo.lastRevCommitMessage(),
"author" -> GitInfo.lastRevCommitAuthor(),
"hash" -> GitInfo.lastRevCommitName(),
"date" -> GitInfo.lastRevCommitTime()
))
)
}
}
示例3: StoryController
//设置package包名称以及导入依赖的类
package controllers
import controllers.StoryModel.StoryData
import javax.inject.Inject
import play.api.Configuration
import play.api.data.Form
import play.api.data.Forms._
import play.api.mvc.{Action, Controller}
import model.StoryDao
import model.DataModel.Story
import scala.collection.mutable.ListBuffer
class StoryController @Inject()(implicit storyDao:StoryDao,config:Configuration) extends Controller{
def index = Action {
val result = storyDao.create();
Ok(views.html.story("Welcome to StoryBoard !!",listStory))
}
def createStory = Action { implicit Request =>
var result = storyDao.insert(new Story(storyForm.bindFromRequest().get.title,storyForm.bindFromRequest().get.description))
Ok(views.html.story("Story Created:" + "(" + storyForm.bindFromRequest().get.title + "," + storyForm.bindFromRequest().get.description + ")",listStory))
}
def listStory:List[StoryData] = {
val stories:List[Story] = storyDao.list
var storiesData = new ListBuffer[StoryData]
for(s <- stories){
storiesData += (new StoryData(s.title,s.description))
}
storiesData.toList
}
val storyForm = Form(
mapping(
"title" -> text,
"description" -> text
)(StoryData.apply)(StoryData.unapply)
)
}
object StoryModel{
case class StoryData(
title:String,
description:String
)
}
示例4: Application
//设置package包名称以及导入依赖的类
package controllers
import javax.inject.Inject
import models.{ProjectRepo, TaskRepo}
import play.api.libs.concurrent.Execution.Implicits.defaultContext
import play.api.mvc.{Action, Controller}
class Application @Inject()( projectRepo: ProjectRepo, taskRepo: TaskRepo)
extends Controller {
def addTaskToProject(color: String, projectId: Long) = Action.async { implicit rs =>
projectRepo.addTask(color, projectId)
.map{ _ => Redirect(routes.Application.projects(projectId)) }
}
def modifyTask(taskId: Long, color: Option[String]) = Action.async { implicit rs =>
taskRepo.partialUpdate(taskId, color, None, None).map(i =>
Ok(s"Rows affected : $i"))
}
def createProject(name: String)= Action.async { implicit rs =>
projectRepo.create(name)
.map(id => Ok(s"project $id created") )
}
def listProjects = Action.async { implicit rs =>
projectRepo.all
.map(projects => Ok(views.html.projects(projects)))
}
def projects(id: Long) = Action.async { implicit rs =>
for {
Some(project) <- projectRepo.findById(id)
tasks <- taskRepo.findByProjectId(id)
} yield Ok(views.html.project(project, tasks))
}
def delete(name: String) = Action.async { implicit rs =>
projectRepo.delete(name).map(num => Ok(s"$num projects deleted"))
}
}
示例5: SignupController
//设置package包名称以及导入依赖的类
package controllers
import javax.inject.{Inject, Singleton}
import com.mohiva.play.silhouette.api.Silhouette
import forms.SignupForm
import play.api.i18n.{I18nSupport, Messages, MessagesApi}
import play.api.mvc.{Action, Controller, Flash}
import utils.auth.DefaultEnv
@Singleton
class SignupController @Inject()
(
val messagesApi: MessagesApi,
silhouette: Silhouette[DefaultEnv]
) extends Controller with I18nSupport {
def createUser = Action { implicit request =>
println("trying to create!")
SignupForm.form.bindFromRequest.fold(
hasErrors = { form =>
Redirect(routes.SignupController.registerPage())
.flashing(Flash(form.data) + ("error" -> Messages("validation.errors")))
},
success = { signupData =>
println(s"creating a new user $signupData")
Redirect(routes.BookmarkController.list())
}
)
}
def registerPage = silhouette.UnsecuredAction { implicit request =>
Ok(views.html.users.register(SignupForm.form))
}
}
示例6: ContactUsController
//设置package包名称以及导入依赖的类
package controllers
import javax.inject.Inject
import model.ContactFormTemplate
import play.api.data.Form
import play.api.data.Forms._
import play.api.mvc.{Action, Controller}
import play.api.Play.current
import play.api.data.validation._
import play.api.i18n.Messages.Implicits._
import services._
import scala.concurrent.Future
class ContactUsController @Inject()(validator: Validation) extends Controller {
val contactUsForm: Form[ContactFormTemplate] = Form(
mapping(
"name" -> nonEmptyText(maxLength = 20),
"email" -> nonEmptyText(maxLength = 30).verifying(validator.emailCheckConstraint),
"description" -> nonEmptyText(maxLength = 50)
)(ContactFormTemplate.apply)(ContactFormTemplate.unapply)
)
def entry = Action {
Ok(views.html.contact(contactUsForm))
}
def postForm = Action.async { implicit request =>
println(request.body)
contactUsForm.bindFromRequest.fold(
formWithErrors => {
Future.successful(BadRequest(views.html.contact(formWithErrors)))
},
UserData => {
Future.successful(Redirect(routes.ContactUsController.success(UserData.name, UserData.email, UserData.description)))
}
)
}
def success(name: String, email: String, description: String) = Action {
Ok(views.html.contactFormConfirmation(name, email, description))
}
}
示例7: ItemController
//设置package包名称以及导入依赖的类
package controllers
import javax.inject.Inject
import com.github.tototoshi.play2.json4s.native.Json4s
import models.{Item, ItemDetail}
import org.json4s.{DefaultFormats, Extraction}
import parsers.ItemParser
import play.api.mvc.{Action, Controller}
import requests.UploadZipItemForm
import scalikejdbc.DB
class ItemController @Inject()(json4s: Json4s) extends Controller {
import json4s._
import Responses._
import models.PersistItem.getItemId
implicit val formats = DefaultFormats
def list() = Action {
import models.Aliases.i
val items = Item.findAll(i.name :: Nil)
Ok(Extraction.decompose(items))
}
def show(itemId: Long) = Action {
Item.findById(itemId).fold(notFound(s"itemId = ${itemId}")) { item =>
Ok(Extraction.decompose(item))
}
}
def upload() = Action(parse.multipartFormData){ implicit req =>
UploadZipItemForm.fromReq(req).fold(BadRequest("Form error")){ form =>
DB localTx { implicit session =>
ZipUtil.inputStreams(form.file.ref.file).foreach{ is =>
ItemParser.parse(is).foreach{ item =>
val itemId = getItemId(item.name)
ItemDetail.deleteById(itemId)
ItemDetail.create(item.detail(itemId))
}
}
}
Redirect(routes.MyAssets.at("uploader.html"))
}
}
}
示例8: DummyController
//设置package包名称以及导入依赖的类
package controllers
import play.api.libs.json.Json
import play.api.mvc.{Action, Controller}
class DummyController extends Controller {
def dummy() = Action {
val json = Json.parse(
"""
|{
| "name" : "Play Ember Seed",
| "author" : "Dipayan Bhowmick",
| "email" : "[email protected]"
|}
""".stripMargin)
Ok(json)
}
}
示例9: Users
//设置package包名称以及导入依赖的类
package controllers
import javax.inject.Inject
import org.joda.time.DateTime
import play.api.libs.concurrent.Execution.Implicits.defaultContext
import play.api.libs.json._
import play.api.mvc.{Action, BodyParsers, Controller}
import play.modules.reactivemongo.{MongoController, ReactiveMongoApi, ReactiveMongoComponents}
import reactivemongo.bson.{BSONDocument, BSONObjectID}
import repos.UserRepoImpl
class Users @Inject()(val reactiveMongoApi: ReactiveMongoApi) extends Controller
with MongoController with ReactiveMongoComponents{
import models.UserFields._
def userRepo = new UserRepoImpl(reactiveMongoApi)
def create = Action.async(BodyParsers.parse.json) { // TODO: Prüfen dass name und email eindeutig sind beim Anlegen
implicit request =>
val name = (request.body \ Name).as[String]
val password = (request.body \ Password).as[String]
val email = (request.body \ EMail).as[String]
userRepo.save(BSONDocument(
Name -> name,
Password -> password,
EMail -> email,
CreatedAt -> DateTime.now.toString
)).map(result => Created("Created"))
}
def read(id: String) = Action.async{ implicit request =>
userRepo.select(BSONDocument(Id -> BSONObjectID(id))).map(exercise => Ok(Json.toJson(exercise)))
}
def update(id: String) = Action.async(BodyParsers.parse.json) { // TODO: Prüfen dass name und email eindeutig sind beim updaten
implicit request =>
val name = (request.body \ Name).asOpt[String]
val password = (request.body \ Password).asOpt[String]
val email = (request.body \ EMail).asOpt[String]
userRepo.update(BSONDocument( Id -> BSONObjectID(id)),
BSONDocument("$set" -> BSONDocument(
Name -> name,
Password -> password,
EMail -> EMail
))).map(result => Accepted)
}
def delete(id: String) = Action.async{
userRepo.remove(BSONDocument(Id -> BSONObjectID(id))).map(result => Accepted("Deleted: "+ id ))
}
}
示例10: CompanyController
//设置package包名称以及导入依赖的类
package controllers
import config.DBSchema
import models.{Company, User}
import org.squeryl.PrimitiveTypeMode._
import play.api.libs.json.Json
import play.api.mvc.{Action, Controller}
object CompanyController extends Controller{
def companyList = Action {
implicit val barWrites = Json.writes[Company]
implicit val barWrites2 = Json.writes[User]
val json = inTransaction {
val companys = from(DBSchema.companyTable)(
companyTable => select(companyTable)
)
for(i <- companys.toList){
val user = i.userList.toList
val temp = "chang"
}
Json.toJson(companys)
}
Ok(json)
}
}
示例11: InventoryLogController
//设置package包名称以及导入依赖的类
package controllers
import java.io.File
import play.api.http.ContentTypes
import play.api.mvc.{Action, Controller}
import service.InventoryLogService
import util.JsonUtil
import scala.util.{Failure, Success, Try}
object InventoryLogController extends Controller {
def create = Action {
InventoryLogService.createSchema
Ok("Schema Created")
}
def truncate = Action {
InventoryLogService.truncateData
Ok("Schema Truncated")
}
def upload = Action(parse.multipartFormData) { implicit request =>
val files = request.body.files
Try(files.map { file =>
val tmpFile = file.ref.moveTo(new File(s"/tmp/${file.filename}"))
InventoryLogService.populateSchema(tmpFile)
tmpFile.delete
}) match {
case Success(_) => if(files.size <= 0) BadRequest("File Not uploaded!!") else Ok("File Uploaded")
case Failure(x) => BadRequest(s"Upload Error!! ${x.getMessage}")
}
}
def track = Action { request =>
val trackRequest = request.body.asJson
Try(trackRequest.map { json =>
val objectId = (json \ "object_id").as[Int]
val objectType = (json \ "object_type").as[String]
val timestamp = (json \ "timestamp").as[Long]
InventoryLogService.trackStatus(objectId, objectType, timestamp)
}.getOrElse {
BadRequest("Expecting application/json request body")
}) match {
case Success(x: Some[Any]) => Ok(JsonUtil.toJson(x.getOrElse(Map.empty))).as(ContentTypes.JSON)
case Success(_) => Ok("No updates available")
case Failure(_) => BadRequest("Expecting all input parameters")
}
}
def details = Action {
Ok(JsonUtil.toJson(InventoryLogService.trackDetails)).as(ContentTypes.JSON)
}
}
示例12: UsersController
//设置package包名称以及导入依赖的类
package controllers
import play.api.libs.json._
import play.api.libs.functional.syntax._
import play.api.mvc.{Action, Controller}
import models.{User, Users}
class UsersController(userServices: Users) extends Controller {
implicit val userWrites: Writes[User] = Json.writes[User]
implicit val userReads: Reads[User] = (
Reads.pure(0L) and
(JsPath \ "name").read[String] and
(JsPath \ "isActive").read[Boolean]
)(User.apply _)
def get(id: Long) = Action { request =>
userServices.find(id) match {
case None => NotFound
case Some(user) => Ok(Json.toJson(user))
}
}
def create = Action(parse.json) { request =>
Json.fromJson[User](request.body).fold(
invalid => BadRequest,
user => {
val userCreated = userServices.create(user)
Created.withHeaders(LOCATION -> s"/users/${userCreated.id}")
}
)
}
def delete(id: Long) = Action { request =>
userServices.find(id) match {
case None => NotFound
case Some(user) =>
userServices.delete(user)
NoContent
}
}
def update(id: Long) = Action(parse.json) { request =>
Json.fromJson[User](request.body).fold(
invalid => BadRequest,
user => {
userServices.update(user.copy(id = id))
NoContent
}
)
}
}
示例13: Application
//设置package包名称以及导入依赖的类
package controllers
import javax.inject.{Inject, Singleton}
import play.api.Logger
import play.api.libs.concurrent.Execution.Implicits.defaultContext
import play.api.libs.json.Json
import play.api.mvc.{Action, Controller}
import play.modules.reactivemongo.json.collection.JSONCollection
import play.modules.reactivemongo.{MongoController, ReactiveMongoApi, ReactiveMongoComponents}
import reactivemongo.api.collections.bson.BSONCollection
import reactivemongo.api.commands.bson.BSONCountCommand.{Count, CountResult}
import reactivemongo.api.commands.bson.BSONCountCommandImplicits._
import reactivemongo.bson.BSONDocument
import scala.concurrent.Future
@Singleton
class Application @Inject()(val reactiveMongoApi: ReactiveMongoApi) extends Controller
with MongoController with ReactiveMongoComponents {
def index = Action {
Logger.info("Application startup...")
val posts = List(
Json.obj(
"name" -> "Widget One",
"description" -> "My first widget",
"author" -> "Justin"
),
Json.obj(
"name" -> "Widget Two: The Return",
"description" -> "My second widget",
"author" -> "Justin"
))
val query = BSONDocument("name" -> BSONDocument("$exists" -> true))
val command = Count(query)
val result: Future[CountResult] = bsonCollection.runCommand(command)
result.map { res =>
val numberOfDocs: Int = res.value
if (numberOfDocs < 1) {
jsonCollection.bulkInsert(posts.toStream, ordered = true).foreach(i => Logger.info("Record added."))
}
}
Ok("Your database is ready.")
}
def jsonCollection = reactiveMongoApi.db.collection[JSONCollection]("widgets")
def bsonCollection = reactiveMongoApi.db.collection[BSONCollection]("widgets")
def cleanup = Action {
jsonCollection.drop().onComplete {
case _ => Logger.info("Database collection dropped")
}
Ok("Your database is clean.")
}
}
示例14: Application
//设置package包名称以及导入依赖的类
package controllers
import javax.inject.Inject
import play.api.mvc.{ Action, Controller }
import play.api.libs.concurrent.Execution.Implicits.defaultContext
import play.api.libs.json._
import play.modules.reactivemongo.{MongoController, ReactiveMongoApi, ReactiveMongoComponents}
import reactivemongo.play.json._
import play.modules.reactivemongo.json.collection._
import models._
import models.JsonFormats._
class Application @Inject() (val reactiveMongoApi: ReactiveMongoApi)
extends Controller with MongoController with ReactiveMongoComponents {
def getHotels = Action.async {
db.collection("hotels").find(Json.obj()).cursor[Hotel]()
.collect[List]().map {hotels => Ok(Json.toJson(hotels))}
}
def findByCityName(cityName : String) = Action.async {
db.collection("hotels").find(Json.obj("city" -> cityName)).cursor[Hotel]()
.collect[List]().map (hotels => Ok(Json.toJson(hotels)))
}
}
示例15: PasswordSettingsData
//设置package包名称以及导入依赖的类
package controllers.my.settings
import controllers.{ HasConfig, HasUserService, Security }
import javax.inject.Inject
import jp.t2v.lab.play2.auth.AuthElement
import models.user.UserService
import models.user.Roles._
import play.api.Configuration
import play.api.data.Form
import play.api.data.Forms._
import play.api.data.validation._
import play.api.i18n.{ I18nSupport, MessagesApi }
import play.api.mvc.Controller
import scala.concurrent.{ ExecutionContext, Future }
case class PasswordSettingsData(currentPassword: String, newPassword: String, verifyPassword: String)
class PasswordSettingsController @Inject() (
val config: Configuration,
val users: UserService,
val messagesApi: MessagesApi,
implicit val ctx: ExecutionContext
) extends Controller with AuthElement with HasConfig with HasUserService with Security with I18nSupport {
private val matchingPasswords: Constraint[PasswordSettingsData] = Constraint("constraints.valid"){ d =>
if (d.newPassword == d.verifyPassword) Valid else Invalid("Passwords must match")
}
val passwordSettingsForm = Form(
mapping(
"current" -> nonEmptyText,
"new" -> nonEmptyText,
"verify" -> nonEmptyText
)(PasswordSettingsData.apply)(PasswordSettingsData.unapply).verifying(matchingPasswords)
)
def index() = StackAction(AuthorityKey -> Normal) { implicit request =>
Ok(views.html.my.settings.password(passwordSettingsForm, loggedIn.user))
}
def updatePassword() = AsyncStack(AuthorityKey -> Normal) { implicit request =>
passwordSettingsForm.bindFromRequest.fold(
formWithErrors =>
Future.successful(BadRequest(views.html.my.settings.password(formWithErrors, loggedIn.user))),
f => {
users.updatePassword(loggedIn.user.getUsername, f.currentPassword, f.newPassword)
.map { _ match {
case Right(_) =>
Redirect(routes.PasswordSettingsController.index).flashing("success" -> "Your password has been updated.")
case Left(errorMessage) =>
Redirect(routes.PasswordSettingsController.index).flashing("error" -> errorMessage)
}}.recover { case t:Throwable => {
t.printStackTrace()
Redirect(routes.PasswordSettingsController.index).flashing("error" -> "There was an error while updating your password.")
}}
}
)
}
}