简体   繁体   English

在播放1.2.5中使用@before注释?

[英]use @before annotation in play 1.2.5?

I want the session to be checked before sending a user to the login - whereby each URL request results in checking whether this is from a valid session - if not, send them to the login page, else process as normal. 我希望在将用户发送到登录名之前检查会话-从而每个URL请求都将检查是否来自有效会话-如果不是,请将其发送到登录页面,否则按常规进行处理。 If the user already has an active session, we will not show them the login page but take them to a pre-defined main page. 如果用户已经有一个活动会话,我们将不向他们显示登录页面,而是将他们带到预定义的主页。

I searched on google related to it, and come to know that it will done by using @Before annotaion in controller but dont know about @Before working and how to use? 我在Google上搜索了与此相关的信息,并知道它将通过在控制器中使用@Before注解来完成,但不了解@Before工作方式以及如何使用? I'm using play 1.2.5. 我正在使用播放1.2.5。

You can use the @Before this way: 您可以使用@Before这样:

@Before
static void addUser() {
    User user = connected();
    if(user != null) {
        renderArgs.put("user", user);
    }
}

static User connected() {
    if(renderArgs.get("user") != null) {
        return renderArgs.get("user", User.class);
    }
    // Find your user from session
    String username = session.get("user");
    if(username != null) {
        return User.find("byUsername", username).first();
    } 
    return null;
}

// ~~render your login if the user is not finded in session

public static void index() {
    if(connected() != null) {
         render();
    }
    login();
}

You can find this sample code in YOUR_PLAY_DIR/samples-and-tests/booking. 您可以在YOUR_PLAY_DIR /示例和测试/预订中找到此示例代码。

As @emt14 said, you can do this with the Play secure module more easily. 正如@ emt14所说,您可以使用Play安全模块更轻松地完成此操作。 Check out the forum apps samples in YOUR_PLAY_DIR/samples-and-tests/forum. 在YOUR_PLAY_DIR / samples-and-tests / forum中查看论坛应用示例。

The Play secure module does exactly that out of the box. Play安全模块开箱即用。 It is used by most applications and integrates with different plugins as well. 大多数应用程序都使用它,并且还与其他插件集成。 Check out the documentation here . 此处查看文档。

If you still want to implement it yourself you can use the secure code as an example. 如果仍要自己实现,则可以使用安全代码作为示例。

Otherwise @Before can be used on any of your controller static methods and has access to all the scope Objects, including session. 否则, @ Before可以在您的任何控制器静态方法上使用,并且可以访问所有作用域对象,包括会话。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM