DoradoContext

2024-03-07 18:37 更新

DoradoContext# 简介 DoradoContext是Dorado的上下文对象,在DoradoContext中,将上下文作用域区分为四种类型,分别为:

作用域中的数据存取

通过DoradoContext提供的相关方法我们可以存取相关作用域下的属性,这些方法有:

  1. public Object getAttribute(String scope, String key);
  2. public void setAttribute(String scope, String key, Object value);
  3. public void removeAttribute(String scope, String key);

例如我们可以通过以下代码访问HttpSession中的值:

  1. DoradoContext context = DoradoContext.getCurrent();
  2. String username = context.getAttribute(DoradoContext.SESSION, "username");

通过以下代码访问ServletContext中某一个attribute的值

  1. DoradoContext context = DoradoContext.getCurrent();
  2. Object securityData = context.getAttribute(DoradoContext.APPLICATION, "securityData");

当然了除了可以通过getAttribute获取指定作用域中的值,你也可以用setAttribute方法设置指定作用域指定属性的值,范例代码如: 

  1. public void authorization(String username, String password) throws Exception{
  2. if (StringUtils.isNotEmpty(username) && StringUtils.isNotEmpty(password)){
  3. DoradoContext context = DoradoContext.getCurrent();
  4. context.setAttribute(DoradoContext.SESSION, "username", username);
  5. }else{
  6. throw new Exception("用户名和密码不能为空!");
  7. }
  8. }

另外也提供了不指定作用域的相关方法,有:

  1. public Object getAttribute(String key);

在获取上下文对象的时候如果你不指定作用域的时候,如:

  1. DoradoContext context = DoradoContext.getCurrent();
  2. String username = context.getAttribute("username");

DoradoContext会依照如下的顺序挨个到不同的作用域中查找是否有指定的属性,如果找到就直接返回,不再继续查找:

关于VIEW作用域

VIEW作用域的数据可以在Dorado的AJAX请求中自动在客户端和服务器端同步。例如:你可以在Ajax请求中在服务器端设置变量,并在Ajax请求结束后,在客户端获取这个变量的值。 客户端JS获取Context中VIEW作用域的变量,参考代码:

  1. var username = view.get("context").get("username");

其它相关方法

  1. //获取Spring中的ApplicationContext
  2. public ApplicationContext getApplicationContext()
  3. //获取Spring中的WebApplicationContext
  4. public WebApplicationContext getWebApplicationContext()
  5. //获取当前web请求的ServletContext
  6. public static ServletContext getServletContext()
  7. //获取当前线程绑定的HttpServletRequest
  8. public static HttpServletRequest getRequest()
以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号