在 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;
}
 
 
from : http://www.blogjava.net/fancydeepin/archive/2013/03/31/java-ee-context.html

java context 讲解的更多相关文章

  1. [Spring Unit Testing] Spring Unit Testing with a Java Context

    For example, we want to test against a implemataion: package com.example.in28minutes.basic; import o ...

  2. java集合讲解

    java集合讲解 1.概述 集合类的顶级接口是Iterable,Collection继承了Iterable接口 常用的集合主要有 3 类,Set,List,Queue,他们都是接口,都继于Collec ...

  3. Java权限讲解

    Java访问权限就如同类和对象一样,在Java程序中随处可见. Java的访问权限,根据权限范围从大到小为:public > protected > package > privat ...

  4. Android Context讲解(转)

    博客出处 前言:本文是我读<Android内核剖析>第7章 后形成的读书笔记 ,在此向欲了解Android框架的书籍推荐此书. 大家好, 今天给大家介绍下我们在应用开发中最熟悉而陌生的朋友 ...

  5. hadoop中setup,cleanup,run和context讲解

    hadoop 执行中的setup run cleanup context的作用1.简介1) setup(),此方法被MapReduce框架仅且执行一次,在执行Map任务前,进行相关变量或者资源的集中初 ...

  6. java泛型讲解

    原文: https://blog.csdn.net/briblue/article/details/76736356 泛型,一个孤独的守门者. 大家可能会有疑问,我为什么叫做泛型是一个守门者.这其实是 ...

  7. Java 快速排序讲解

    快速排序由于排序效率在同为 O(nlogn) 的几种排序方法中效率最高,因此经常被采用.再加上快速排序思想——分治法也确实非常实用,所以 在各大厂的面试习题中,快排总是最耀眼的那个.要是你会的排序算法 ...

  8. Java 基础讲解

    Hello,老同学们,又见面啦,新同学们,你们好哦! 在看完本人的<数据结构与算法>专栏的博文的老同学,恭喜你们在学习本专栏时,你们将会发现好多知识点都讲解过,都易于理解,那么,没看过的同 ...

  9. 常用的JAVA集合讲解

    java.util包中包含了一系列重要的集合类,而对于集合类,主要需要掌握的就是它的内部结构,以及遍历集合的迭代模式. 接口:Collection Collection是最基本的集合接口,一个Coll ...

随机推荐

  1. Odoo Graph 指定默认 类型

    <graph string='Sale Paid Grapg' type="pivot"> <field name='section_id' type=" ...

  2. 错误信息:attempt to create saveOrUpdate event with null entity

    错误信息:attempt to create saveOrUpdate event with null entity; 这个错误网上答案比较多,我也不多说了. 我遇到的问题是在前台传过来的参数是nul ...

  3. The method getDispatcherType() is undefined for the type HttpServletRequest

    在使用百度的ueditor的时候,老是报错: The method getDispatcherType() is undefined for the type HttpServletRequest 原 ...

  4. 细说SaaS BI国际市场众生相,你准备好了么?

    SaaS商业智能(BI)历程 在笔者看来,SaaS BI(也有称SaaS 商业智能.云BI)算是一个慢热的概念.远在十几前年便已经提出并有公司践行.而随着SaaS服务从早期的CRM.ERP.HR等领域 ...

  5. Linq分组

    1.lin语句 int[] nums = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0, 3 }; DataTable table = new DataTable("Numb ...

  6. HTML:document.activeElement

    今天遇到一个很郁闷的问题: document.activeElement获取当前获得焦点的元素,在chrome总是得到body,后来经过试验得到结果如下: document.activeElement ...

  7. OC的类别(分类)和拓展

    一.分类: 1.适用范围      当你已经封装好了一个类(也可能是系统类.第三方库),不想在改动这个类了,可是随着程序功能的增加需要在类中增加一个方法,这时我们不必修改主类,只需要给你原来的类增加一 ...

  8. HTML标签marquee实现滚动效果

    html标签 - <marquee></marquee>可以实现多种滚动效果,无需js控制.使用marquee标记不仅可以移动文字,也可以移动图片,表格等.只需要在<ma ...

  9. spring boot + gradle[草稿]

    入门文档:https://github.com/qibaoguang/Spring-Boot-Reference-Guide 安装gradle 官方下载 https://gradle.org/grad ...

  10. asio制作使用ssl通信的证书

    1,生成ca的keyopenssl genrsa -out ca.key 1024/2048 (with out password protected) openssl genrsa -des3 -o ...