play for scala 实现SessionFilter 过滤未登录用户跳转到登录页面

网友投稿 232 2023-06-28


play for scala 实现SessionFilter 过滤未登录用户跳转到登录页面

一、编写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")http:// && !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

* chttp://lass 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 过滤未登录用户跳转到登录页面,希望对大家有所帮助,如果大家有任何疑问请给我留言,会及时回复大家的。在此也非常感谢大家对我们网站的支持!


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:eoLinker AMS免费版 V2.1.1更新日志
下一篇:Mybatis 开发注解快速入门
相关文章

 发表评论

暂时没有评论,来抢沙发吧~