本文整理汇总了Scala中play.api.routing.Router类的典型用法代码示例。如果您正苦于以下问题:Scala Router类的具体用法?Scala Router怎么用?Scala Router使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Router类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: ErrorHandler
//设置package包名称以及导入依赖的类
package conf.util
import javax.inject._
import play.api._
import play.api.http.DefaultHttpErrorHandler
import play.api.mvc.Results._
import play.api.mvc._
import play.api.routing.Router
import scala.concurrent._
class ErrorHandler @Inject()(
env: Environment,
config: Configuration,
sourceMapper: OptionalSourceMapper,
router: Provider[Router])
extends DefaultHttpErrorHandler(env, config, sourceMapper, router) {
override def onProdServerError(request: RequestHeader, exception: UsefulException) = {
Future.successful(
InternalServerError("A server error occurred: " + exception.getMessage)
)
}
override protected def onNotFound(request: RequestHeader, message: String): Future[Result] = {
Future.successful(
InternalServerError("A server error occurred: " + message)
)
}
override def onForbidden(request: RequestHeader, message: String) = {
Future.successful(
Forbidden("You're not allowed to access this resource.")
)
}
override def onClientError(request: RequestHeader, statusCode: Int, message: String) = {
Future.successful(
Status(statusCode)("A client error occurred: " + message)
)
}
override def onServerError(request: RequestHeader, exception: Throwable) = {
Future.successful(
InternalServerError("A server error occurred: " + exception.getMessage)
)
}
override protected def onBadRequest(request: RequestHeader, message: String): Future[Result] = {
Future.successful(
InternalServerError("A server error occurred: " + message)
)
}
}
示例2: ErrorHandler
//设置package包名称以及导入依赖的类
package web
import play.api.http.DefaultHttpErrorHandler
import play.api._
import play.api.mvc._
import play.api.mvc.Results._
import play.api.i18n.{ I18nSupport, MessagesApi, Messages }
import play.api.routing.Router
import scala.concurrent._
import javax.inject._
class ErrorHandler @Inject() (
env: Environment,
config: Configuration,
sourceMapper: OptionalSourceMapper,
router: Provider[Router],
val messagesApi: MessagesApi) extends DefaultHttpErrorHandler(env, config, sourceMapper, router) with I18nSupport {
// 404 - page not found error
override def onNotFound(request: RequestHeader, message: String): Future[Result] = Future.successful {
NotFound(env.mode match {
case Mode.Prod => views.html.web.errors.notFound(request)(request2Messages(request))
case _ => views.html.defaultpages.devNotFound(request.method, request.uri, Some(router.get))
})
}
// 500 - internal server error
override def onProdServerError(request: RequestHeader, exception: UsefulException) = Future.successful {
InternalServerError(views.html.web.errors.error(request, exception)(request2Messages(request)))
}
}
示例3: RequestHandler
//设置package包名称以及导入依赖的类
import javax.inject.Inject
import play.api.http._
import play.api.mvc._
import play.api.mvc.request.{RequestFactory, RequestTarget}
import play.api.routing.Router
class RequestHandler @Inject()(router: Router,
errorHandler: HttpErrorHandler,
configuration: HttpConfiguration,
filters: HttpFilters)
extends DefaultHttpRequestHandler(router,
errorHandler,
configuration,
filters) {
override def handlerForRequest(request: RequestHeader): (RequestHeader, Handler) = {
super.handlerForRequest {
// ensures that REST API does not need a trailing "/"
if (isREST(request)) {
addTrailingSlash(request)
} else {
request
}
}
}
private def isREST(request: RequestHeader) = {
request.uri match {
case uri: String if uri.contains("post") => true
case _ => false
}
}
private def addTrailingSlash(origReq: RequestHeader): RequestHeader = {
if (!origReq.path.endsWith("/")) {
val path = origReq.path + "/"
if (origReq.rawQueryString.isEmpty) {
origReq.withTarget(
RequestTarget(path = path, uriString = path, queryString = Map())
)
} else {
origReq.withTarget(
RequestTarget(path = path,
uriString = origReq.uri,
queryString = origReq.queryString)
)
}
} else {
origReq
}
}
}
示例4: WebApp
//设置package包名称以及导入依赖的类
import org.culture.OrgId
import play.api.ApplicationLoader.Context
import play.api._
import play.api.mvc.Results._
import play.api.mvc._
import play.api.routing.Router
import play.api.routing.sird._
import wiring.Components
class WebApp extends ApplicationLoader {
private val components = new Components
import components._
def load(context: Context) =
new BuiltInComponentsFromContext(context) {
val router = Router.from {
case GET(p"/badge/${long(orgId)}.svg") =>
Action.async {
badgeBuilder.get(OrgId(orgId)).map { badge =>
Ok.chunked(badge.body).as("image/svg+xml;charset=utf-8")
}
}
}
}.application
}
示例5: AppLoader
//设置package包名称以及导入依赖的类
import models.{AuthorizeStoreCache, PendingContentStoreCache}
import play.api.ApplicationLoader.Context
import play.api.cache.EhCacheComponents
import play.api.mvc.EssentialFilter
import play.api.routing.Router
import play.api._
import play.filters.gzip.GzipFilter
import router.Routes
class AppLoader extends ApplicationLoader {
override def load(context: Context): Application = {
LoggerConfigurator(context.environment.classLoader)
.foreach(_.configure(context.environment))
new AppComponents(context).application
}
}
class AppComponents(context: Context)
extends BuiltInComponentsFromContext(context)
with EhCacheComponents {
implicit val executionContext =
play.api.libs.concurrent.Execution.Implicits.defaultContext
implicit lazy val authorizeStoreCache = AuthorizeStoreCache(
cacheApi("authorizeStore"))
implicit lazy val pendingConsentStoreCache = PendingContentStoreCache(
cacheApi("pendingConsentStore"))
implicit val config = configuration.underlying
lazy val applicationController = new controllers.Application
lazy val assets = new controllers.Assets(httpErrorHandler)
// Routes is a generated class
override def router: Router =
new Routes(httpErrorHandler, applicationController, assets)
val gzipFilter = new GzipFilter(shouldGzip = (request, response) => {
val contentType = response.header.headers.get("Content-Type")
contentType.exists(_.startsWith("text/html")) ||
request.path.endsWith("jsroutes.js")
})
override lazy val httpFilters: Seq[EssentialFilter] = Seq(gzipFilter)
}
示例6: AppLoader
//设置package包名称以及导入依赖的类
import java.io.Closeable
import javax.sql.DataSource
import controllers.UsersController
import io.getquill._
import play.api.ApplicationLoader.Context
import play.api._
import play.api.db.evolutions.Evolutions
import play.api.db.{DBComponents, HikariCPComponents}
import play.api.inject.{Injector, NewInstanceInjector, SimpleInjector}
import play.api.routing.Router
import play.api.routing.sird._
import models.{Users}
class AppLoader extends ApplicationLoader {
override def load(context: Context): Application = new BuiltInComponentsFromContext(context) with DBComponents with HikariCPComponents {
lazy val db = new H2JdbcContext[SnakeCase](dbApi.database("default").dataSource.asInstanceOf[DataSource with Closeable])
lazy val users = new Users(db)
lazy val usersController = new UsersController(users)
val router = Router.from {
case GET(p"/users/${long(id)}") => usersController.get(id)
case POST(p"/users") => usersController.create
case DELETE(p"/users/${long(id)}") => usersController.delete(id)
case PUT(p"/users/${long(id)}") => usersController.update(id)
}
override lazy val injector: Injector =
new SimpleInjector(NewInstanceInjector) + users + router + cookieSigner + csrfTokenSigner + httpConfiguration + tempFileCreator + global
Evolutions.applyEvolutions(dbApi.database("default"))
}.application
}
示例7: ErrorHandler
//设置package包名称以及导入依赖的类
package utils
import javax.inject.{Inject, Provider}
import com.mohiva.play.silhouette.api.actions.SecuredErrorHandler
import play.api.http.DefaultHttpErrorHandler
import play.api.i18n.{I18nSupport, Messages, MessagesApi}
import play.api.mvc.Results._
import play.api.mvc.{RequestHeader, Result}
import play.api.routing.Router
import play.api.{Configuration, OptionalSourceMapper}
import scala.concurrent.Future
import controllers.{WebJarAssets, routes}
class ErrorHandler @Inject() (
val messagesApi: MessagesApi,
env: play.api.Environment,
config: Configuration,
sourceMapper: OptionalSourceMapper,
router: javax.inject.Provider[Router],
p: Provider[WebJarAssets])
extends DefaultHttpErrorHandler(env, config, sourceMapper, router)
with SecuredErrorHandler with I18nSupport {
// https://www.playframework.com/documentation/2.5.x/Migration25#Handling-legacy-components
implicit lazy val webJarAssets = p.get()
override def onNotAuthenticated(implicit request: RequestHeader): Future[Result] =
Future.successful(Redirect(routes.Auth.signIn()))
override def onNotAuthorized(implicit request: RequestHeader): Future[Result] =
Future.successful(Redirect(routes.Auth.signIn()).flashing("error" -> Messages("error.accessDenied")))
override def onNotFound(request: RequestHeader, message: String): Future[Result] =
Future.successful(Ok(views.html.errors.notFound(request)))
override def onServerError(request:RequestHeader, exception:Throwable):Future[Result] =
Future.successful(Ok(views.html.errors.serverError(request, exception)))
}
示例8: AppLoader
//设置package包名称以及导入依赖的类
package org.andrewconner.spot
import _root_.controllers.Assets
import com.softwaremill.macwire._
import org.andrewconner.spot.core.time.Clock
import org.andrewconner.spot.modules._
import play.api.ApplicationLoader.Context
import play.api._
import play.api.libs.ws.WSClient
import play.api.libs.ws.ahc.AhcWSClient
import play.api.routing.Router
import scala.concurrent.ExecutionContext
class AppLoader extends ApplicationLoader {
def load(context: Context) = {
(new BuiltInComponentsFromContext(context) with AppComponents).application
}
}
trait AppComponents
extends BuiltInComponents
with PlayAppModule
with DatabaseModule // Database injection
with DaoModule
with ControllerModule // Application controllers
with CmdrModule
with CredentialsModule {
implicit val ec: ExecutionContext = play.api.libs.concurrent.Execution.defaultContext // scala.concurrent.ExecutionContext.Implicits.global
implicit val clock: Clock = new Clock()
lazy val assets: Assets = wire[Assets]
val prefix: String = "/"
lazy val router: Router = wire[_root_.router.Routes].withPrefix(prefix)
implicit val wsClient: WSClient = AhcWSClient()
appShutdown.onStopAsync(wsClient.close())
}
示例9: MyApplicationLoader
//设置package包名称以及导入依赖的类
package my.samples.core
import com.typesafe.config.ConfigFactory
import com.typesafe.scalalogging.{ LazyLogging, StrictLogging }
import controllers.Assets
import play.api.{ Application, BuiltInComponentsFromContext, Configuration, _ }
import play.api.libs.ws.ahc.AhcWSComponents
import my.samples.controllers.MyApplicationController
import play.api.ApplicationLoader.Context
import play.api.routing.Router
import router.Routes
import scala.concurrent.Future
// compile time DI for loading the play application
final class MyApplicationLoader extends ApplicationLoader with LazyLogging {
override def load(context: Context): Application = {
val configuration = Configuration(ConfigFactory.load())
val newContext = context.copy(initialConfiguration = configuration)
LoggerConfigurator(newContext.environment.classLoader)
.foreach(_.configure(newContext.environment))
new MyApp(newContext).application
}
}
class MyApp(context: Context)
extends BuiltInComponentsFromContext(context) with AhcWSComponents with StrictLogging {
implicit val s = monix.execution.Scheduler.Implicits.global
def stop(bindings: AppBindings) = {
logger.info("stopping application")
bindings.globalChannel.publishChannel.onComplete()
}
def start = {
logger.info("starting application")
AppBindings(actorSystem, materializer)
}
// 1. create the dependencies that will be injected
lazy val appBindings = start
// 2. inject the dependencies into the controllers
lazy val applicationController = new MyApplicationController(appBindings)
lazy val assets = new Assets(httpErrorHandler)
override def router: Router = new Routes(
httpErrorHandler, applicationController, assets
)
// 3. add the shutdown hook to properly dispose all connections
applicationLifecycle.addStopHook { () => Future(stop(appBindings)) }
}
示例10: RequestHandler
//设置package包名称以及导入依赖的类
import javax.inject.Inject
import play.api.http._
import play.api.mvc._
import play.api.routing.Router
class RequestHandler @Inject()(router: Router,
errorHandler: HttpErrorHandler,
configuration: HttpConfiguration,
filters: HttpFilters)
extends DefaultHttpRequestHandler(router,
errorHandler,
configuration,
filters) {
override def handlerForRequest(request: RequestHeader): (RequestHeader, Handler) = {
super.handlerForRequest {
// ensures that REST API does not need a trailing "/"
if (isREST(request)) {
addTrailingSlash(request)
} else {
request
}
}
}
private def isREST(request: RequestHeader) = {
request.uri match {
case uri: String if uri.contains("post") => true
case uri: String if uri.contains("news") => true
case _ => false
}
}
private def addTrailingSlash(origReq: RequestHeader): RequestHeader = {
if (!origReq.path.endsWith("/")) {
val path = origReq.path + "/"
if (origReq.rawQueryString.isEmpty) {
origReq.copy(path = path, uri = path)
} else {
origReq.copy(path = path, uri = path + s"?${origReq.rawQueryString}")
}
} else {
origReq
}
}
}
示例11: AppLoader
//设置package包名称以及导入依赖的类
import java.io.Closeable
import javax.sql.DataSource
import controllers.MainController
import io.getquill._
import models.Services
import unus.db._
import unus.helpers.Conf
import unus.model.FeatureBuilder
import unus.stage.{BlockerCacher, DatabaseBackup, PatientCacher, PatientDatabase}
import org.flywaydb.play.FlywayPlayComponents
import play.api.ApplicationLoader.Context
import play.api._
import play.api.db.{DBComponents, HikariCPComponents}
import play.api.inject.{Injector, NewInstanceInjector, SimpleInjector}
import play.api.routing.Router
import play.filters.csrf._
import router.Routes
class AppLoader extends ApplicationLoader {
override def load(context: Context): Application = new BuiltInComponentsFromContext(context)
with DBComponents with HikariCPComponents with CSRFComponents
with FlywayPlayComponents with play.filters.HttpFiltersComponents with _root_.controllers.AssetsComponents {
lazy val db = new PostgresJdbcContext[PostgresEscape](dbApi.database("default").dataSource.asInstanceOf[DataSource with Closeable])
lazy val services = new Services(db)
lazy val patientCacher = new PatientCacher
lazy val repo = new Repository(db)
lazy val blockerCachers = Conf.blockers.map(new BlockerCacher(repo, patientCacher.value, _))
lazy val features = Conf.features
lazy val controller = new MainController(services, repo, patientCacher, blockerCachers, features)(controllerComponents)
lazy val router: Router = new Routes(httpErrorHandler, controller)
override lazy val injector: Injector =
new SimpleInjector(NewInstanceInjector) + cookieSigner + csrfTokenSigner + httpConfiguration + tempFileCreator + router
override lazy val httpFilters = Seq(csrfFilter)
flywayPlayInitializer
new PatientDatabase(repo, patientCacher).run()
if(services.getLabelCount == 0) {
new DatabaseBackup[Label]("Label").load()
}
if(services.getBlockedRowCount == 0) {
new DatabaseBackup[BlockedRow]("BlockedRow").load()
}
}.application
}
示例12: ErrorHandler
//设置package包名称以及导入依赖的类
import play.api.http.DefaultHttpErrorHandler
import play.api._
import play.api.mvc._
import play.api.mvc.Results._
import play.api.routing.Router
import scala.concurrent.Future
import javax.inject._
class ErrorHandler @Inject() (
env: Environment,
config: Configuration,
sourceMapper: OptionalSourceMapper,
router: Provider[Router],
webErrorHandler: web.ErrorHandler,
adminErrorHandler: admin.ErrorHandler) extends DefaultHttpErrorHandler(env, config, sourceMapper, router) {
private def getSubdomain(request: RequestHeader) = request.domain.replaceFirst("[\\.]?[^\\.]+[\\.][^\\.]+$", "")
// 404 - page not found error
override def onNotFound(request: RequestHeader, message: String): Future[Result] = getSubdomain(request) match {
case "admin" => adminErrorHandler.onNotFound(request, message)
case _ => webErrorHandler.onNotFound(request, message)
}
// 500 - internal server error
override def onProdServerError(request: RequestHeader, exception: UsefulException) = getSubdomain(request) match {
case "admin" => adminErrorHandler.onProdServerError(request, exception)
case _ => webErrorHandler.onProdServerError(request, exception)
}
}
示例13: ErrorHandler
//设置package包名称以及导入依赖的类
package admin
import play.api.http.DefaultHttpErrorHandler
import play.api._
import play.api.mvc._
import play.api.mvc.Results._
import play.api.i18n.{ I18nSupport, MessagesApi, Messages }
import play.api.routing.Router
import scala.concurrent._
import javax.inject._
class ErrorHandler @Inject() (
env: Environment,
config: Configuration,
sourceMapper: OptionalSourceMapper,
router: Provider[Router],
val messagesApi: MessagesApi) extends DefaultHttpErrorHandler(env, config, sourceMapper, router) with I18nSupport {
// 404 - page not found error
override def onNotFound(request: RequestHeader, message: String): Future[Result] = Future.successful {
NotFound(env.mode match {
case Mode.Prod => views.html.admin.errors.notFound(request)(request2Messages(request))
case _ => views.html.defaultpages.devNotFound(request.method, request.uri, Some(router.get))
})
}
// 500 - internal server error
override def onProdServerError(request: RequestHeader, exception: UsefulException) = Future.successful {
InternalServerError(views.html.admin.errors.error(request, exception)(request2Messages(request)))
}
}
示例14: ErrorHandler
//设置package包名称以及导入依赖的类
import javax.inject._
import play.api._
import play.api.http.DefaultHttpErrorHandler
import play.api.mvc.Results._
import play.api.mvc._
import play.api.routing.Router
import scala.concurrent.Future
@Singleton
class ErrorHandler @Inject()(
env: Environment,
config: Configuration,
sourceMapper: OptionalSourceMapper,
router: Provider[Router]
) extends DefaultHttpErrorHandler(env, config, sourceMapper, router) {
override def onProdServerError(request: RequestHeader, exception: UsefulException): Future[Result] = Future.successful {
InternalServerError("A server error occurred: " + exception.getMessage)
}
override def onClientError(request: RequestHeader, statusCode: Int, message: String): Future[Result] = env.mode match {
case Mode.Prod => Future.successful(Results.Status(statusCode)(message))
case _ => super.onClientError(request, statusCode, message)
}
}
示例15: GriffinApiLoader
//设置package包名称以及导入依赖的类
import com.softwaremill.macwire._
import controllers.Assets
import filters.LoggingFilter
import play.api.ApplicationLoader.Context
import play.api._
import play.api.i18n._
import play.api.libs.ws.ahc.AhcWSComponents
import play.api.mvc.EssentialFilter
import play.api.routing.Router
import play.filters.cors.{CORSConfig, CORSFilter}
import router.Routes
import services.ServicesModule
class GriffinApiLoader extends ApplicationLoader {
def load(context: Context): Application = new GriffinComponents(context).application
}
class GriffinComponents(context: Context)
extends BuiltInComponentsFromContext(context)
with ServicesModule
with I18nComponents
with AhcWSComponents
{
// set up logger
LoggerConfigurator(context.environment.classLoader).foreach {
_.configure(context.environment)
}
lazy val assets: Assets = wire[Assets]
lazy val router: Router = {
// add the prefix string in local scope for the Routes constructor
val prefix: String = "/"
wire[Routes]
}
lazy val corsFilter = CORSFilter(CORSConfig.fromConfiguration(configuration))
lazy val loggingFilter = new LoggingFilter
lazy val filters = wire[Filters]
override lazy val httpFilters: Seq[EssentialFilter] =
Seq(loggingFilter,corsFilter)
}