简体   繁体   中英

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. 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? I'm using play 1.2.5.

You can use the @Before this way:

@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.

As @emt14 said, you can do this with the Play secure module more easily. Check out the forum apps samples in YOUR_PLAY_DIR/samples-and-tests/forum.

The Play secure module does exactly that out of the box. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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