play for scala 实现SessionFilter 过滤未登录用户跳转到登录页面
程序员文章站
2024-03-11 22:50:19
一、编写sessionfilter.scala代码
package filters
import javax.inject.{inject, singleton...
一、编写sessionfilter.scala代码
package filters import javax.inject.{inject, singleton} import akka.stream.materializer import controllers.routes import play.api.mvc.{filter, requestheader, result, results} import scala.concurrent.future @singleton class sessionfilter @inject()(implicit val mat: materializer) extends filter { def apply(nextfilter: requestheader => future[result]) (requestheader: requestheader): future[result] = { if (!requestheader.session.get("user").isdefined && !requestheader.path.contains("/signin") && !requestheader.path.contains("/assets/")) { future.successful(results.redirect(routes.signcontroller.showsignin())) } else { nextfilter(requestheader) } } }
说明:
!requestheader.session.get("user").isdefined 是用来判断session中是否存在user
!requestheader.path.contains("/signin") 是用来排除登录页面,这个页面不登录也应该是可见的,防止出现死循环跳转
!requestheader.path.contains("/assets/") 是用来排除静态资源文件的,如图片、css、javascript等
二、在app目录下的filters.scala中使用sessionfilter
filters.scala这个文件是activator自动生成的模板,要使用sessionfilter只要在里面加上sessionfilter: sessionfilter和seq(sessionfilter)就可以了
import javax.inject._ import filters.{examplefilter, sessionfilter} import play.api._ import play.api.http.httpfilters import play.api.mvc._ /** * this class configures filters that run on every request. this * class is queried by play to get a list of filters. * * play will automatically use filters from any class called * `filters` that is placed the root package. you can load filters * from a different class by adding a `play.http.filters` setting to * the `application.conf` configuration file. * * @param env basic environment settings for the current application. * @param examplefilter a demonstration filter that adds a header to * each response. */ @singleton class filters @inject() ( env: environment, examplefilter: examplefilter, sessionfilter: sessionfilter) extends httpfilters { override val filters = { // use the example filter if we're running development mode. if // we're running in production or test mode then don't use any // filters at all. if (env.mode == mode.dev) seq(examplefilter) else seq.empty seq(sessionfilter) } }
以上所述是小编给大家介绍的play for scala 实现sessionfilter 过滤未登录用户跳转到登录页面,希望对大家有所帮助
上一篇: 浅谈文件读写——C#
下一篇: Java设计模式之策略模式详解