在 java 中, 常见的 Context 有很多,

像: ServletContext, ActionContext, ServletActionContext, ApplicationContext, PageContext, SessionContext ...

那么, Context 究竟是什么东西呢? 直译是上下文、环境的意思。比如像: "今天我收到了一束花, 男朋友送的!" 又或者 "今天我收到了一束花, 送花的人送错了的!"

同样是收到一束花, 在不同的上下文环境中表达的意义是不一样的。

同样的, Context 其实也是一样, 它离不开所在的上下文环境, 否则就是断章取义了。

另外, 在网络上也有些人把 Context 看成是一些公用信息或者把它看做是一个容器的, 个人觉得这种解释稍好。

接下来说说 ServletContext, ActionContext, ServletActionContext。
 
 1> ServletContext

一个 WEB 运用程序只有一个 ServletContext 实例, 它是在容器(包括 JBoss, Tomcat 等)完全启动 WEB 项目之前被创建, 生命周期伴随整个 WEB 运用。

当在编写一个 Servlet 类的时候, 首先是要去继承一个抽象类 HttpServlet, 然后可以直接通过 getServletContext() 方法来获得 ServletContext 对象。

这是因为 HttpServlet 类中实现了 ServletConfig 接口, 而 ServletConfig 接口中维护了一个 ServletContext 的对象的引用。

利用 ServletContext 能够获得 WEB 运用的配置信息, 实现在多个 Servlet 之间共享数据等。

eg:

<?xml version="1.0" encoding="UTF-8"?>

<context-param>
    <param-name>url</param-name>
    <param-value>jdbc:oracle:thin:@localhost:1521:ORC</param-value>
  </context-param>
  <context-param>
    <param-name>username</param-name>
    <param-value>scott</param-value>
  </context-param>
  <context-param>
    <param-name>password</param-name>
    <param-value>tigger</param-value>
  </context-param>
  
  <servlet>
    <servlet-name>ConnectionServlet</servlet-name>
    <servlet-class>net.yeah.fancydeepin.servlet.ConnectionServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>ConnectionServlet</servlet-name>
    <url-pattern>/ConnectionServlet.action</url-pattern>
  </servlet-mapping>
  
  <servlet>
    <servlet-name>PrepareConnectionServlet</servlet-name>
    <servlet-class>net.yeah.fancydeepin.servlet.PrepareConnectionServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>PrepareConnectionServlet</servlet-name>
    <url-pattern>/PrepareConnectionServlet.action</url-pattern>
  </servlet-mapping>

</web-app>

package net.yeah.fancydeepin.servlet;

import java.io.IOException;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class PrepareConnectionServlet extends HttpServlet {

private static final long serialVersionUID = 1L;

public void init() throws ServletException {
        
        ServletContext context = getServletContext();
        String url = context.getInitParameter("url");
        String username = context.getInitParameter("username");
        String password = context.getInitParameter("password");
        context.setAttribute("url", url);
        context.setAttribute("username", username);
        context.setAttribute("password", password);
    }

protected void doGet(HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException{
        
        doPost(request, response);
    }

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
        response.sendRedirect("ConnectionServlet.action");
    }
}

package net.yeah.fancydeepin.servlet;

import java.io.IOException;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;

public class ConnectionServlet extends HttpServlet {

private static final long serialVersionUID = 1L;

public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException {
        
        ServletContext context = getServletContext();
        System.out.println("***************************************");
        System.out.println("URL: " + context.getAttribute("url"));
        System.out.println("Username: " + context.getAttribute("username"));
        System.out.println("Password: " + context.getAttribute("password"));
        System.out.println("***************************************");
        super.service(request, response);
    }
}

当访问 PrepareConnectionServlet.action 时, 后台打印输出:

***********************************************
URL:  jdbc:oracle:thin:@localhost:1521:ORC
Username:  scott
Password:  tigger
***********************************************

2> ActionContext
 
 ActionContext 是当前 Action 执行时的上下文环境, ActionContext 中维护了一些与当前 Action 相关的对象的引用,

如: Parameters (参数), Session (会话), ValueStack (值栈), Locale (本地化信息) 等。
 
 在 Struts1 时期, Struts1 的 Action 与 Servlet API 和 JSP 技术的耦合度都很紧密, 属于一个侵入式框架:

public ActionForward execute(ActionMapping mapping,ActionForm form,HttpServletRequest request,HttpServletResponse response){
    // TODO Auto-generated method stub
    return null;
}

到了 Struts2 时期, Struts2 的体系结构与 Struts1 之间存在很大的不同。Struts2 在 Struts1 的基础上与 WebWork 进行了整合, 成为了一个全新的框架。

在 Struts2 里面, 则是通过 WebWork 来将与 Servlet 相关的数据信息转换成了与 Servlet API 无关的对象, 即 ActionContext 对象。

这样就使得了业务逻辑控制器能够与 Servlet API 分离开来。另外, 由于 Struts2 的 Action 是每一次用户请求都产生一个新的实例, 因此,

ActionContext 不存在线程安全问题, 可以放心使用。

package net.yeah.fancydeepin.action;

import java.util.Map;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.util.ValueStack;

public class ContextAction extends ActionSupport {

private static final long serialVersionUID = 1L;
    private String username;
    private String password;

public String execute(){
        
        ActionContext context = ActionContext.getContext();
        ValueStack value = context.getValueStack();
        value.set("username", username);
        value.set("password", password);
        Map<String, Object> session = context.getSession();
        session.put("url", "http://www.blogjava.net/fancydeepin");
        return SUCCESS;
    }

public void setUsername(String username) {
        this.username = username;
    }

public void setPassword(String password) {
        this.password = password;
    }
}

<s:property value="username"/><BR>
<s:property value="password"/><BR>
<s:property value="#session.url"/><BR>

当访问 context.action 并传给相应的参数的时候, 在浏览器中会输出相应的信息。

留意到上面 Struts2 的 Action 中并有没添加属性的 getting 方法, 而是手动的将参数值放到值栈(ValueStack)中的, 否则页面是得不到参数来输出的。

3> ServletActionContext

首先, ServletActionContext 是 ActionContext 的一个子类。ServletActionContext 从名字上来看, 意味着它与 Servlet API 紧密耦合。

ServletActionContext 的构造子是私有的, 主要是提供了一些静态的方法, 可以用来获取: ActionContext, ActionMapping, PageContext,

HttpServletRequest, HttpServletResponse, ServletContext, ValueStack, HttpSession 对象的引用。

public String execute(){
        
    //或 implements ServletRequestAware
    HttpServletRequest request = ServletActionContext.getRequest();
    //或 implements ServletResponseAware
    HttpServletResponse response = ServletActionContext.getResponse();
    //或 implements SessionAware
    HttpSession session = request.getSession();
    //或 implements ServletContextAware
    ServletContext context = ServletActionContext.getServletContext();
        
    return SUCCESS;
}

spring context对象的更多相关文章

  1. 基于Spring DM管理的Bundle获取Spring上下文对象及指定Bean对象

    在讲述服务注册与引用的随笔中,有提到context.getServiceReferences()方法,通过该方法可以获取到OSGI框架容器中的指定类型的服务引用,从而获取到对应的服务对象.同时该方法还 ...

  2. Spring 代理对象,cglib,jdk的问题思考,AOP 配置注解拦截 的一些问题.为什么不要注解在接口,以及抽象方法.

    可以被继承 首先注解在类上是可以被继承的 在注解上用@Inherited /** * Created by laizhenwei on 17:49 2017-10-14 */ @Target({Ele ...

  3. Spring普通类/工具类获取并调用Spring service对象的方法

    参考<Spring普通类获取并调用Spring service方法>,网址:https://blog.csdn.net/jiayi_0803/article/details/6892455 ...

  4. 【初识Spring】对象(Bean)实例化及属性注入(xml方式)

    title: [初识Spring]对象(Bean)实例化及属性注入(xml方式) date: 2018-08-29 17:35:15 tags: [Java,Web,Spring] --- #初识S ...

  5. [转载]vs2012中使用Spring.NET报错:Spring.Context.Support.ContextRegistry 的类型初始值设定项引发异常

    学习使用Spring.NET中的时候,写了一个Demo,在运行时报了一个错误:Spring.Context.Support.ContextRegistry 的类型初始值设定项引发异常. 重新整理思绪, ...

  6. 【转】关于spring集合对象的补充

    <span style="font-size:18px;">关于spring集合对象的补充 spring2.0中对集合对象有了改进,新增了一个<util>标 ...

  7. Spring context:component-scan中使用context:include-filter和context:exclude-filter

    Spring context:component-scan中使用context:include-filter和context:exclude-filter XML: <?xml version= ...

  8. Spring context:component-scan代替context:annotation-config

    Spring context:component-scan代替context:annotation-config XML: <?xml version="1.0" encod ...

  9. SpringBoot CGLIB AOP解决Spring事务,对象调用自己方法事务失效.

    对于像我这种喜欢滥用AOP的程序员,遇到坑也是习惯了,不仅仅是事务,其实只要脱离了Spring容器管理的所有对象,对于SpringAOP的注解都会失效,因为他们不是Spring容器的代理类,Sprin ...

随机推荐

  1. ES线程池设置

    每个Elasticsearch节点内部都维护着多个线程池,如index.search.get.bulk等,用户可以修改线程池的类型和大小,线程池默认大小跟CPU逻辑一致 一.查看当前线程组状态 cur ...

  2. Elasticsearch yellow 意味着主分片可用,副本不可用

    摘自:http://unasm.com/2016/11/644/ 在通过 /_cluster/state 命令查看es 状态的时候,发现es 处于一个yellow的状态, 这个很奇怪,按照官方的解释, ...

  3. Ubuntu14.04下Mongodb官网安装部署步骤(图文详解)(博主推荐)

    不多说,直接上干货! 在这篇博客里,我采用了非官网的安装步骤,来进行安装.走了弯路,同时,也是不建议.因为在大数据领域和实际生产里,还是要走正规的为好. Ubuntu14.04下Mongodb(离线安 ...

  4. SpringBoot(一) 基础入门

    SpringBoot简要 简化Spring应用开发的一个框架: 整个Spring技术栈的一个大整合: J2EE开发的一站式解决方案: 自动配置:针对很多Spring应用程序常见的应用功能,Spring ...

  5. No mapping found for HTTP request with URI [/spring_liu/hello.do] in DispatcherServlet with name 'SpringMVC'

    控制台一直报No mapping found for HTTP request with URI [/spring_liu/hello.do] in DispatcherServlet with na ...

  6. luogu P2252 取石子游戏(威佐夫博弈)

    题意 题解 对于像我这种不知道威佐夫博弈的人来说,拿到题就开始打表了. 然而打完后并没有发现什么. 然后才知道是威佐夫博弈. 结论是当(int)((b-a)*((sqrt(5.0)+1.0)/2.0) ...

  7. CF1029E Tree with Small Distances (贪心)

    题目大意:给你一棵边权为1的树,让你加入一些边,使得根节点(1号节点)到其他节点的最短距离不大于2 并没有想到贪心...... 正解的贪心思路是这样的 用一个堆维护当前距离最远的点,然后把根节点和它的 ...

  8. macOS seria 10.12升级到macOS Mojave的报错:xcrun: error: invalid active developer path, missing xcrun

    今天升级mac系统到macOS mojave后,在终端操作gitlab时遇到一行莫名其妙的错误: xcrun: error: invalid active developer path (/Libra ...

  9. Maven项目的坐标GroupId和ArtifactId

    GroupId和ArtifactId被统称为“坐标”是为了保证项目唯一性而提出的,如果你要把你项目弄到maven本地仓库去,你想要找到你的项目就必须根据这两个id去查找.       GroupId一 ...

  10. hadoop-07-ntp服务检查

    hadoop-07-ntp服务检查 cd /etc/more /etc/ntp.conf里面进行了server的配置 service ntpd status / stop/ start 安装ntpd ...