日期:2014-05-20  浏览次数:20857 次

Play! Framework 学习笔记 — 注解
Interceptions拦截器注解:
@Before
所有访问的Action执行之前调用该方法,比如:
public class Admin extends Application {
 
    @Before
    static void checkAuthentification() {
        if(session.get("user") == null) login();
    }
 
    public static void index() {
        List<User> users = User.findAll();
        render(users);
    }
 
    ...
 
}


如果需要忽略某一个请求路径,可以添加unless参数:
public class Admin extends Application {
 
    @Before(unless="login")
    static void checkAuthentification() {
        if(session.get("user") == null) login();
    }
 
    public static void index() {
        List<User> users = User.findAll();
        render(users);
    }
 
    ...
 
}


如果只希望截获某些请求路径,可以添加only参数:
public class Admin extends Application {
 
    @Before(only={"login","logout"})
    static void doSomething() {  
		...  
	}
	
   	...
}


当希望夸类实现多个拦截器,可以通过@With注解实现:
先定义第一个拦截器:
public class Secure extends Controller {
    
    @Before
    static void checkAuthenticated() {
        if(!session.containsKey("user")) {
            unAuthorized();
        }
    }
} 


接着在另一个类再定义一个拦截器:
@With(Secure.class)
public class Admin extends Application {
    
    ...
     
}


如果希望对Controller的每个方法执行完时进行拦截:
public class Admin extends Application {
 
    @After
    static void log() {
        Logger.info("Action executed ...");
    }
 
    public static void index() {
        List<User> users = User.findAll();
        render(users);
    }
 
    ...
 
}


如果希望当Controller的每个Action抛出异常时进行拦截,可以使用@Catch:
public class Admin extends Application {
	
    @Catch(IllegalStateException.class)
    public static void logIllegalState(Throwable throwable) {
        Logger.error("Illegal state %s…", throwable);
    }
    
    public static void index() {
        List<User> users = User.findAll();
        if (users.size() == 0) {
            throw new IllegalStateException("Invalid database - 0 users");
        }
        render(users);
    }
}


如果希望当Controller的每个Action结果都产生后进行拦截,可以使用@Finally:
public class Admin extends Application {
 
    @Finally
    static void log() {
        Logger.info("Response contains : " + response.out);
    }
 
    public static void index() {
        List<User> users = User.findAll();
        render(users);
    }
 
    ...
 
}