Packages

p

play.api

mvc

package mvc

Contains the Controller/Action/Result API to handle HTTP requests.

For example, a typical controller:

class HomeController @Inject() (val controllerComponents: ControllerComponents) extends BaseController {

  def index = Action {
    Ok("It works!")
  }

}
Source
package.scala
Linear Supertypes
AnyRef, Any
Ordering
  1. Alphabetic
  2. By Inheritance
Inherited
  1. mvc
  2. AnyRef
  3. Any
  1. Hide All
  2. Show All
Visibility
  1. Public
  2. All

Type Members

  1. abstract class AbstractController extends BaseController

    An abstract implementation of BaseController to make it slightly easier to use.

  2. trait AcceptExtractors extends AnyRef

    Define a set of extractors allowing to pattern match on the Accept HTTP header of a request

  3. case class Accepting(mimeType: String) extends Product with Serializable

    Convenient class to generate extractors checking if a given mime type matches the Accept header of a request.

    Convenient class to generate extractors checking if a given mime type matches the Accept header of a request. Example of use:

    val AcceptsMp3 = Accepting("audio/mp3")

    Then:

    request match {
      case AcceptsMp3() => ...
    }
  4. trait Action[A] extends EssentialAction

    An action is essentially a (Request[A] => Result) function that handles a request and generates a result to be sent to the client.

    An action is essentially a (Request[A] => Result) function that handles a request and generates a result to be sent to the client.

    For example,

    val echo = Action { request =>
      Ok("Got request [" + request + "]")
    }
    A

    the type of the request body

  5. trait ActionBuilder[+R[_], B] extends ActionFunction[Request, R]

    Provides helpers for creating Action values.

  6. class ActionBuilderImpl[B] extends ActionBuilder[Request, B]
  7. trait ActionFilter[R[_]] extends ActionRefiner[R, R]

    A simple kind of ActionRefiner which, given a request (of type R), may either immediately produce a Result (for example, an error), or continue its Action block with the same request.

    A simple kind of ActionRefiner which, given a request (of type R), may either immediately produce a Result (for example, an error), or continue its Action block with the same request. The critical (abstract) function is filter.

  8. trait ActionFunction[-R[_], +P[_]] extends AnyRef

    A builder for generic Actions that generalizes over the type of requests.

    A builder for generic Actions that generalizes over the type of requests. An ActionFunction[R,P] may be chained onto an existing ActionBuilder[R] to produce a new ActionBuilder[P] using andThen. The critical (abstract) function is invokeBlock. Most users will want to use ActionBuilder instead.

    R

    the type of the request on which this is invoked (input)

    P

    the parameter type which blocks executed by this builder take (output)

  9. trait ActionRefiner[-R[_], +P[_]] extends ActionFunction[R, P]

    A simple kind of ActionFunction which, given a request (of type R), may either immediately produce a Result (for example, an error), or call its Action block with a parameter (of type P).

    A simple kind of ActionFunction which, given a request (of type R), may either immediately produce a Result (for example, an error), or call its Action block with a parameter (of type P). The critical (abstract) function is refine.

  10. trait ActionTransformer[-R[_], +P[_]] extends ActionRefiner[R, P]

    A simple kind of ActionRefiner which, given a request (of type R), unconditionally transforms it to a new parameter type (P) to be passed to its Action block.

    A simple kind of ActionRefiner which, given a request (of type R), unconditionally transforms it to a new parameter type (P) to be passed to its Action block. The critical (abstract) function is transform.

  11. sealed trait AnyContent extends AnyRef

    A request body that adapts automatically according the request Content-Type.

  12. case class AnyContentAsFormUrlEncoded(data: Map[String, Seq[String]]) extends AnyContent with Product with Serializable

    AnyContent - Form url encoded body

  13. case class AnyContentAsJson(json: JsValue) extends AnyContent with Product with Serializable

    AnyContent - Json body

  14. case class AnyContentAsMultipartFormData(mfd: MultipartFormData[TemporaryFile]) extends AnyContent with Product with Serializable

    AnyContent - Multipart form data body

  15. case class AnyContentAsRaw(raw: RawBuffer) extends AnyContent with Product with Serializable

    AnyContent - Raw body (give access to the raw data as bytes).

  16. case class AnyContentAsText(txt: String) extends AnyContent with Product with Serializable

    AnyContent - Text body

  17. case class AnyContentAsXml(xml: NodeSeq) extends AnyContent with Product with Serializable

    AnyContent - XML body

  18. trait BaseController extends BaseControllerHelpers

    Defines utility methods to generate Action and Results types.

    Defines utility methods to generate Action and Results types.

    For example:

    class HomeController @Inject() (val controllerComponents: ControllerComponents) extends BaseController {
    
      def hello(name:String) = Action { request =>
        Ok("Hello " + name)
      }
    
    }

    This is intended to provide the idiomatic Play API for actions, allowing you to use "Action" for the default action builder and "parse" to access Play's default body parsers. You may want to extend this to provide your own base controller class, or write your own version with similar code.

  19. trait BaseControllerHelpers extends ControllerHelpers

    Useful prewired mixins for controller components, assuming an available ControllerComponents.

    Useful prewired mixins for controller components, assuming an available ControllerComponents.

    If you want to extend your own AbstractController but want to use a different base "Action", you can mix in this trait.

  20. trait BodyParser[+A] extends (RequestHeader) ⇒ Accumulator[ByteString, Either[Result, A]]

    A body parser parses the HTTP request body content.

    A body parser parses the HTTP request body content.

    A

    the body content type

  21. trait BodyParserUtils extends AnyRef

    A set of reusable body parsers and utilities that do not require configuration.

  22. trait BodyParsers extends AnyRef

    Legacy body parsers trait.

    Legacy body parsers trait. Basically all this does is define a "parse" member with a PlayBodyParsers instance constructed from the running app's settings. If no app is running, we create parsers using default settings and an internally-created materializer. This is done to support legacy behavior. Instead of using this trait, we suggest injecting an instance of PlayBodyParsers (either directly or through BaseController or one of its subclasses).

  23. case class Call(method: String, url: String, fragment: String = null) extends mvc.Call with Product with Serializable

    Defines a Call, which describes an HTTP request and can be used to create links or fill redirect data.

    Defines a Call, which describes an HTTP request and can be used to create links or fill redirect data.

    These values are usually generated by the reverse router.

    method

    the request HTTP method

    url

    the request URL

  24. case class Codec(charset: String)(encode: (String) ⇒ ByteString, decode: (ByteString) ⇒ String) extends Product with Serializable

    A Codec handle the conversion of String to Byte arrays.

    A Codec handle the conversion of String to Byte arrays.

    charset

    The charset to be sent to the client.

    encode

    The transformation function.

  25. trait ControllerComponents extends AnyRef

    The base controller components dependencies that most controllers rely on.

  26. trait ControllerHelpers extends Results with HttpProtocol with Status with HeaderNames with ContentTypes with RequestExtractors with Rendering with RequestImplicits

    Useful mixins for controller classes.

    Useful mixins for controller classes.

    If you wish to write a controller with minimal dependencies, you can mix in this trait, which includes helpers and useful constants.

    class MyController @Inject() (action: DefaultActionBuilder, parse: PlayBodyParsers) extends ControllerHelpers {
      def index = action(parse.text) {
        Ok
      }
    }
  27. case class Cookie(name: String, value: String, maxAge: Option[Int] = None, path: String = "/", domain: Option[String] = None, secure: Boolean = false, httpOnly: Boolean = true, sameSite: Option[SameSite] = None) extends Product with Serializable

    An HTTP cookie.

    An HTTP cookie.

    name

    the cookie name

    value

    the cookie value

    maxAge

    the cookie expiration date in seconds, None for a transient cookie, or a value 0 or less to expire a cookie now

    path

    the cookie path, defaulting to the root path /

    domain

    the cookie domain

    secure

    whether this cookie is secured, sent only for HTTPS requests

    httpOnly

    whether this cookie is HTTP only, i.e. not accessible from client-side JavaScript code

    sameSite

    defines cookie access restriction: first-party or same-site context

  28. trait CookieBaker[T <: AnyRef] extends AnyRef

    Trait that should be extended by the Cookie helpers.

  29. trait CookieDataCodec extends AnyRef

    This trait encodes and decodes data to a string used as cookie value.

  30. trait CookieHeaderEncoding extends AnyRef

    Logic for encoding and decoding Cookie and Set-Cookie headers.

  31. trait Cookies extends Traversable[Cookie]

    The HTTP cookies set.

  32. class CookiesModule extends SimpleModule

    A cookie module that uses JWT as the cookie encoding, falling back to URL encoding.

  33. trait DefaultActionBuilder extends ActionBuilder[Request, AnyContent]

    A trait representing the default action builder used by Play's controllers.

    A trait representing the default action builder used by Play's controllers.

    This trait is used for binding, since some dependency injection frameworks doesn't deal with types very well.

  34. class DefaultActionBuilderImpl extends ActionBuilderImpl[AnyContent] with DefaultActionBuilder
  35. case class DefaultControllerComponents(actionBuilder: DefaultActionBuilder, parsers: PlayBodyParsers, messagesApi: MessagesApi, langs: Langs, fileMimeTypes: FileMimeTypes, executionContext: ExecutionContext) extends ControllerComponents with Product with Serializable
  36. class DefaultCookieHeaderEncoding extends CookieHeaderEncoding

    The default implementation of CookieHeaders.

  37. class DefaultFlashCookieBaker extends FlashCookieBaker with FallbackCookieDataCodec
  38. case class DefaultJWTCookieDataCodec(secretConfiguration: SecretConfiguration, jwtConfiguration: JWTConfiguration) extends JWTCookieDataCodec with Product with Serializable
  39. class DefaultMessagesActionBuilderImpl extends MessagesActionBuilderImpl[AnyContent] with MessagesActionBuilder
  40. case class DefaultMessagesControllerComponents(messagesActionBuilder: MessagesActionBuilder, actionBuilder: DefaultActionBuilder, parsers: PlayBodyParsers, messagesApi: MessagesApi, langs: Langs, fileMimeTypes: FileMimeTypes, executionContext: ExecutionContext) extends MessagesControllerComponents with Product with Serializable
  41. class DefaultPlayBodyParsers extends PlayBodyParsers
  42. class DefaultSessionCookieBaker extends SessionCookieBaker with FallbackCookieDataCodec

    A session cookie that reads in both signed and JWT cookies, and writes out JWT cookies.

  43. case class DefaultUrlEncodedCookieDataCodec(isSigned: Boolean, cookieSigner: CookieSigner) extends UrlEncodedCookieDataCodec with Product with Serializable
  44. case class DiscardingCookie(name: String, path: String = "/", domain: Option[String] = None, secure: Boolean = false) extends Product with Serializable

    A cookie to be discarded.

    A cookie to be discarded. This contains only the data necessary for discarding a cookie.

    name

    the name of the cookie to discard

    path

    the path of the cookie, defaults to the root path

    domain

    the cookie domain

    secure

    whether this cookie is secured

  45. trait EssentialAction extends (RequestHeader) ⇒ Accumulator[ByteString, Result] with Handler

    An EssentialAction underlies every Action.

    An EssentialAction underlies every Action. Given a RequestHeader, an EssentialAction consumes the request body (an ByteString) and returns a Result.

    An EssentialAction is a Handler, which means it is one of the objects that Play uses to handle requests.

  46. trait EssentialFilter extends AnyRef
  47. trait FallbackCookieDataCodec extends CookieDataCodec

    A trait that identifies the cookie encoding and uses the appropriate codec, for upgrading from a signed cookie encoding to a JWT cookie encoding.

  48. trait Filter extends EssentialFilter

    Implement this interface if you want to add a Filter to your application

    Implement this interface if you want to add a Filter to your application

    object AccessLog extends Filter {
      override def apply(next: RequestHeader => Future[Result])(request: RequestHeader): Future[Result] = {
    		 val result = next(request)
    		 result.map { r => play.Logger.info(request + "\n\t => " + r; r }
    	 }
    }
  49. case class Flash(data: Map[String, String] = Map.empty[String, String]) extends Product with Serializable

    HTTP Flash scope.

    HTTP Flash scope.

    Flash data are encoded into an HTTP cookie, and can only contain simple String values.

  50. trait FlashCookieBaker extends CookieBaker[Flash] with CookieDataCodec

    Helper utilities to manage the Flash cookie.

  51. trait Handler extends AnyRef

    An Handler handles a request.

    An Handler handles a request. Play understands several types of handlers, for example EssentialActions and WebSockets.

    The Handler used to handle the request is controlled by GlobalSettings's onRequestReceived method. The default implementation of onRequestReceived delegates to onRouteRequest which calls the default Router.

  52. class Headers extends AnyRef

    The HTTP headers set.

  53. trait InjectedController extends BaseController

    A variation of BaseController that gets its components via method injection.

  54. trait JWTCookieDataCodec extends CookieDataCodec

    JWT cookie encoding and decoding functionality

  55. trait JavascriptLiteral[A] extends AnyRef

    Transform a value to a Javascript literal.

    Transform a value to a Javascript literal.

    Annotations
    @implicitNotFound( ... )
  56. class LegacyCookiesModule extends SimpleModule

    A cookie module that uses the urlencoded cookie encoding.

  57. class LegacyFlashCookieBaker extends FlashCookieBaker with UrlEncodedCookieDataCodec
  58. trait LegacyI18nSupport extends AnyRef
  59. class LegacySessionCookieBaker extends SessionCookieBaker with UrlEncodedCookieDataCodec

    A session cookie baker that signs the session cookie in the Play 2.5.x style.

  60. case class MaxSizeExceeded(length: Long) extends MaxSizeStatus with Product with Serializable

    Signal a max content size exceeded.

  61. sealed trait MaxSizeStatus extends AnyRef

    The status of a max size flow.

  62. abstract class MessagesAbstractController extends MessagesBaseController

    An abstract controller class that returns a MessagesRequest as the default Action.

    An abstract controller class that returns a MessagesRequest as the default Action.

    An abstract implementation of MessagesBaseController to make it slightly easier to use.

    class MyController @Inject()(cc: MessagesControllerComponents) extends MessagesAbstractController(cc) {
      def index = Action { implicit request: MessagesRequest[AnyContent] =>
        Ok(views.html.formTemplate(form)) // twirl template with form builders
      }
    }
  63. trait MessagesActionBuilder extends ActionBuilder[MessagesRequest, AnyContent]

    This trait is an ActionBuilder that provides a MessagesRequest to the block:

    This trait is an ActionBuilder that provides a MessagesRequest to the block:

    class MyController @Inject()(
      messagesAction: MessagesActionBuilder,
      cc: ControllerComponents
    ) extends AbstractController(cc) {
      def index = messagesAction { implicit request: MessagesRequest[AnyContent] =>
         Ok(views.html.formTemplate(form)) // twirl template with form builders
      }
    }

    This is useful when you don't want to have to add play.api.i18n.I18nSupport to a controller for form processing.

  64. class MessagesActionBuilderImpl[B] extends ActionBuilder[MessagesRequest, B]
  65. trait MessagesBaseController extends BaseControllerHelpers

    A base controller that returns a MessagesRequest as the base Action.

  66. trait MessagesControllerComponents extends ControllerComponents

    Controller components with a MessagesActionBuilder.

  67. trait MessagesInjectedController extends MessagesBaseController

    A variation of MessagesAbstractController that gets its components via method injection.

  68. class MessagesRequest[+A] extends WrappedRequest[A] with PreferredMessagesProvider with MessagesRequestHeader

    This class is a wrapped Request that is "i18n-aware" and can return the preferred messages associated with the request.

    This class is a wrapped Request that is "i18n-aware" and can return the preferred messages associated with the request.

    A

    the body type of the request

  69. trait MessagesRequestHeader extends RequestHeader with MessagesProvider

    This trait is a RequestHeader that can provide a play.api.i18n.Messages instance.

    This trait is a RequestHeader that can provide a play.api.i18n.Messages instance.

    This is very useful with when used for forms processing, as the form helpers defined in views.helper (e.g. inputText.scala.html) take a MessagesProvider.

  70. case class MultipartFormData[A](dataParts: Map[String, Seq[String]], files: Seq[FilePart[A]], badParts: Seq[BadPart]) extends Product with Serializable

    Multipart form data body.

  71. trait PathBindable[A] extends AnyRef

    Binder for URL path parameters.

    Binder for URL path parameters.

    You can provide an implementation of PathBindable[A] for any type A you want to be able to bind directly from the request path.

    For example, given this class definition:

    case class User(id: Int, name: String, age: Int)

    You can define a binder retrieving a User instance from its id, useable like the following:

    // In your routes:
    // GET  /show/:user      controllers.Application.show(user)
    // For example: /show/42
    
    class HomeController @Inject() (val controllerComponents: ControllerComponents) extends BaseController {
      def show(user: User) = Action {
        ...
      }
    }

    The definition of binder can look like the following:

    object User {
      implicit def pathBinder(implicit intBinder: PathBindable[Int]) = new PathBindable[User] {
        override def bind(key: String, value: String): Either[String, User] = {
          for {
            id <- intBinder.bind(key, value).right
            user <- User.findById(id).toRight("User not found").right
          } yield user
        }
        override def unbind(key: String, user: User): String = {
          intBinder.unbind(key, user.id)
        }
      }
    }
    Annotations
    @implicitNotFound( ... )
  72. trait PlayBodyParsers extends BodyParserUtils

    Body parsers officially supported by Play (i.e.

    Body parsers officially supported by Play (i.e. built-in to Play)

  73. trait PreferredMessagesProvider extends MessagesProvider

    This trait is a play.api.i18n.MessagesProvider that can be applied to a RequestHeader, and uses messagesApi.preferred(requestHeader) to return the messages.

  74. trait QueryStringBindable[A] extends AnyRef

    Binder for query string parameters.

    Binder for query string parameters.

    You can provide an implementation of QueryStringBindable[A] for any type A you want to be able to bind directly from the request query string.

    For example, if you have the following type to encode pagination:

    /**
     * @param index Current page index
     * @param size Number of items in a page
     */
    case class Pager(index: Int, size: Int)

    Play will create a Pager(5, 42) value from a query string looking like /foo?p.index=5&p.size=42 if you define an instance of QueryStringBindable[Pager] available in the implicit scope.

    For example:

    object Pager {
      implicit def queryStringBinder(implicit intBinder: QueryStringBindable[Int]) = new QueryStringBindable[Pager] {
        override def bind(key: String, params: Map[String, Seq[String]]): Option[Either[String, Pager]] = {
          for {
            index <- intBinder.bind(key + ".index", params)
            size <- intBinder.bind(key + ".size", params)
          } yield {
            (index, size) match {
              case (Right(index), Right(size)) => Right(Pager(index, size))
              case _ => Left("Unable to bind a Pager")
            }
          }
        }
        override def unbind(key: String, pager: Pager): String = {
          intBinder.unbind(key + ".index", pager.index) + "&" + intBinder.unbind(key + ".size", pager.size)
        }
      }
    }

    To use it in a route, just write a type annotation aside the parameter you want to bind:

    GET  /foo        controllers.foo(p: Pager)
    Annotations
    @implicitNotFound( ... )
  75. case class RawBuffer(memoryThreshold: Long, temporaryFileCreator: TemporaryFileCreator, initialData: ByteString = ByteString.empty) extends Product with Serializable

    Handle the request body a raw bytes data.

    Handle the request body a raw bytes data.

    memoryThreshold

    If the content size is bigger than this limit, the content is stored as file.

    temporaryFileCreator

    the temporary file creator to store the content as file.

    initialData

    the initial data, ByteString.empty by default.

  76. trait Rendering extends AnyRef
  77. trait Request[+A] extends RequestHeader

    The complete HTTP request.

    The complete HTTP request.

    A

    the body content type.

    Annotations
    @implicitNotFound( "Cannot find any HTTP Request here" )
  78. trait RequestExtractors extends AcceptExtractors
  79. trait RequestHeader extends AnyRef

    The HTTP request header.

    The HTTP request header. Note that it doesn’t contain the request body yet.

    Annotations
    @implicitNotFound( ... )
  80. trait RequestImplicits extends AnyRef

    Useful mixin for methods that do implicit transformations of a request

  81. final class ResponseHeader extends AnyRef

    A simple HTTP response header, used for standard responses.

  82. case class Result(header: ResponseHeader, body: HttpEntity, newSession: Option[Session] = None, newFlash: Option[Flash] = None, newCookies: Seq[Cookie] = Seq.empty) extends Product with Serializable

    A simple result, which defines the response header and a body ready to send to the client.

    A simple result, which defines the response header and a body ready to send to the client.

    header

    the response header, which contains status code and HTTP headers

    body

    the response body

  83. trait Results extends AnyRef

    Helper utilities to generate results.

  84. case class Session(data: Map[String, String] = Map.empty) extends Product with Serializable

    HTTP Session.

    HTTP Session.

    Session data are encoded into an HTTP cookie, and can only contain simple String values.

  85. trait SessionCookieBaker extends CookieBaker[Session] with CookieDataCodec

    Helper utilities to manage the Session cookie.

  86. trait UrlEncodedCookieDataCodec extends CookieDataCodec

    This trait writes out cookies as url encoded safe text format, optionally prefixed with a signed code.

  87. trait WebSocket extends Handler

    A WebSocket handler.

  88. class WrappedRequest[+A] extends Request[A]

    Wrap an existing request.

    Wrap an existing request. Useful to extend a request.

    If you need to add extra values to a request, you could consider using request attributes instead. See the attr, withAttr, etc methods.

  89. trait Controller extends ControllerHelpers with BodyParsers

    Implements deprecated controller functionality.

    Implements deprecated controller functionality. We recommend moving away from this and using one of the classes or traits extending BaseController instead.

    Annotations
    @deprecated
    Deprecated

    (Since version 2.6.0) Your controller should extend AbstractController, BaseController, or InjectedController instead.

Value Members

  1. object ActionBuilder
  2. object AnyContent

    Factory object for creating an AnyContent instance.

    Factory object for creating an AnyContent instance. Useful for unit testing.

  3. object AnyContentAsEmpty extends AnyContent with Product with Serializable

    AnyContent - Empty request body

  4. object BodyParser

    Helper object to construct BodyParser values.

  5. object BodyParsers extends BodyParsers

    Default BodyParsers.

  6. object Codec extends Serializable

    Default Codec support.

  7. object ControllerHelpers extends ControllerHelpers
  8. object Cookie extends Serializable
  9. object CookieHeaderMerging

    Utilities for merging individual cookie values in HTTP cookie headers.

  10. object Cookies extends CookieHeaderEncoding

    Helper utilities to encode Cookies.

  11. object DefaultActionBuilder
  12. object EssentialAction

    Helper for creating EssentialActions.

  13. object Filter
  14. object FilterChain

    Compose the action and the Filters to create a new Action

  15. object Filters

    Compose the action and the Filters to create a new Action

  16. object Flash extends CookieBaker[Flash] with UrlEncodedCookieDataCodec with Serializable
  17. object Handler
  18. object Headers
  19. object JWTCookieDataCodec
  20. object JavascriptLiteral

    Default JavaScript literals converters.

  21. object MaxSizeNotExceeded extends MaxSizeStatus with Product with Serializable

    Signal max size is not exceeded.

  22. object MultipartFormData extends Serializable

    Defines parts handled by Multipart form data.

  23. object PathBindable

    Default binders for URL path part.

  24. object PlayBodyParsers
  25. object QueryStringBindable

    Default binders for Query String

  26. object RangeResult
  27. object Request
  28. object RequestHeader
  29. object ResponseHeader
  30. object Result extends Serializable
  31. object Results extends Results with LegacyI18nSupport

    Helper utilities to generate results.

  32. object Security

    Helpers to create secure actions.

  33. object Session extends CookieBaker[Session] with FallbackCookieDataCodec with Serializable
  34. object WebSocket

    Helper utilities to generate WebSocket results.

Deprecated Value Members

  1. object Action extends DefaultActionBuilder

    Helper object to create Action values.

    Helper object to create Action values.

    Annotations
    @deprecated
    Deprecated

    (Since version 2.6.0)

Inherited from AnyRef

Inherited from Any

Ungrouped