我一直在开发一个在每个页面上显示用户信息的网站。目前我正在检索用户详细信息(使用存储在会话中的Id),然后将User对象传递给每个页面的render方法。
有没有办法从多个页面中检索对象而不将其作为渲染参数添加到每个方法?
或者这是唯一/最好的方法吗?
答案 0 :(得分:5)
您可以将@Before方法添加到控制器:
public class UserController extends Controller {
@Before
public static void prepareUser() {
String id = session.get("userId");
if (null == id) Secure.login();
User user = User.findById(id);
if (null == user) Secure.login();
renderArgs.put("user", user);
}
}
现在所有其他操作方法都会在renderArgs中自动拥有一个用户对象。
如果要将此功能添加到其他控制器类,那么在该类中必须具有@With:
@With(UserController.class)
public class ProfileController extends Controller {...}
您还可以使用@Before注释的“除非”参数从@Before fitler中排除某些操作方法。查看Play online documentation about controller interception以了解更多详情