分享

ServletContextListener

 孙中熙——路 2011-05-31

ServletContextListener

(2009-08-17 18:24:35)

    public interface javax.servlet.ServletContextListener extends java.util.EventListener,

Implementations of this interface receive notifications about changes to the servlet context

of the web application they are part of. To receive notification events, the implementation

class must be configured in the deployment descriptor for the web application.

    ServletContextListenerServletContext的监听者,它能够监听ServletContext对象的生命周期,也就是监听Web应用的生命周期;Servlet容器启动或终止Web应用时,会触发ServletContextEvent事件,该事件由 ServletContextListener 来处理。在 ServletContextListener 接口中定义了处理ServletContextEvent事件的两个方法:

contextInitialized(ServletContextEvent sce)

Servlet容器启动Web应用时调用该方法;在调用完该方法之后,容器再对Filter初始化,

并且对那些在Web应用启动时就需要被初始化的Servlet进行初始化。

contextDestroyed(ServletContextEvent sce):当Servlet容器终止Web应用时调用该方法;

在调用该方法之前,容器会先销毁所有的ServletFilter过滤器。

 

使用:

(1)自定义上下文监听

public class MyContextListener implements ServletContextListener{

    private java.util.Timer timer = null;

    public void contextInitialized(ServletContextEvent event) {

        timer = new java.util.Timer(true);

        event.getServletContext().log("timer start");

        timer.schedule(xxTask, 0, 60*60*1000);//每隔1小时

        event.getServletContext().log("task timed");

    }

   

    public void contextDestroyed(ServletContextEvent event){

        timer.cancel();

        event.getServletContext().log("timer destroyed");

    }

}

(2)web.xml 注册监听

监听器的部署在web.xml文件中配置,在配置文件中,它的位置应该在过滤器的后面Servlet的前面 ,

<listener>

        <listener-class>xx.MyContextListener</listener-class>

</listener>

 

附录:

1.获取Web配置文件参数值的常用方式:
例1:
<context-param>       
   <param-name>context/param</param-name>       
   <param-value>xxxxx</param-value>       
</context-param>
 
getServletContext().getInitParameter("context/param");


例2:
<servlet>
<init-param>     
<param-name>pname</param-name>     
<param-value>xxxx</param-value>   
</init-param> 
</servlet>

getServletConfig().getInitParameter("pname");

 

2.web.xml各元素加载顺序

context-param -> listener -> filter -> servlet

 

3.用户身份权限验证(Web客户端HTTP基本认证)
(1)身份验证窗口
<%
response.addHeader("WWW-Authenticate","Basic realm="Tomcat Manager Application"");
response.sendError(401,"Unauthorized");
%>
(2)Request Header:
当一个客户端(通常是浏览器)向Web服务器发送一个请求是,它要发送一个请求的命令行,一般是GET或POST命令,当发送POST命令时,
它还必须向服务器发送一个叫"Content-Length”的请求头(Request Header) 用以指明请求数据的长度,除了Content-Length之外,
它还可以向服务器发送其它一些Headers,如:
Accept 浏览器可接受的MIME类型
Accept-Charset 浏览器支持的字符编码
Accept-Encoding 浏览器知道如何解码的数据编码类型(如 gzip)。Servlets 可以预先检查浏览器是否支持gzip并可以对支持gzip的浏览器返回gzipped的HTML页面,并设置Content-Encoding回应头(response header)来指出发送的内容是已经gzipped的。在大多数情况下,这样做可以加快网页下载的速度。
Accept-Language 浏览器指定的语言,当Server支持多语种时起作用。
Authorization 认证信息,一般是对服务器发出的WWW-Authenticate头的回应。
Connection 是否使用持续连接。如果servlet发现这个字段的值是Keep-Alive,或者由发出请求的命令行发现浏览器支持 HTTP 1.1 (持续连接是它的默认选项),使用持续连接可以使保护很多小文件的页面的下载时间减少。
Content-Length (使用POST方法提交时,传递数据的字节数)
Cookie (很重要的一个Header,用来进行和Cookie有关的操作,详细的信息将在后面的教程中介绍)
Host (主机和端口)
If-Modified-Since (只返回比指定日期新的文档,如果没有,将会反回304 "Not Modified")
Referer (URL)
User-Agent (客户端的类型,一般用来区分不同的浏览器)
(3)认证过程:
<%
sun.misc.BASE64Decoder decoder = new sun.misc.BASE64Decoder();
boolean authenticated = false;
//认证头"authorization"是加密的,要用Base64方法解密,取得明文的用户名和密码
String authorization = request.getHeader("authorization");

if (authorization != null) {
  if (authorization.startsWith("Basic")){
    authorization = authorization.substring(authorization.indexOf(' ')+1);
    byte[] bytes = decoder.decodeBuffer(authorization);
    authorization = new String(bytes);
    String userName = authorization.substring(0,authorization.indexOf(':'));
    String password = authorization.substring(authorization.indexOf(':')+1);
    authenticated =userName.equals("abc") && password.equals("abc");
   }else if (authorization.startsWith("Digest")){
       String userName = authorization.substring(authorization.indexOf("username="));
       userName = userName.substring("username="".length());
       userName = userName.substring(0,userName.indexOf('"'));
       String password = authorization.substring(authorization.indexOf("response="));
       password = password.substring("response="".length());
       password = password.substring(0,password.indexOf('"'));
       authenticated =userName.equals("abc") && password.equals("3cf1135d3b8e20dd9272d06288569a56");
  }
}
if (!authenticated){

//response.addHeader("WWW-Authenticate","Digest realm="Tomcat Manager Application"");
response.addHeader("WWW-Authenticate","Basic realm="Tomcat Manager Application"");
response.sendError(401,"Unauthorized");
}else{
out.println("pass authertication!");
}
%>

 

4.Tomcat Server的ClassLoader结构如下:
Bootstrap-->System -->Common-->Catalina/Shared-->WebApp
其中:
Bootstrap:载入JVM自带的类和$JAVA_HOME/jre/lib/ext/*.jar
System:载入$CLASSPATH/*.class
Common:载入$CATALINA_HOME/common/...,它们对TOMCAT和所有的WEB APP都可见
Catalina:载入$CATALINA_HOME/server/...,它们仅对TOMCAT可见,对所有的WEB APP都不可见
Shared:载入$CATALINA_HOME/shared/...,它们仅对所有WEB APP可见,对TOMCAT不可见(也不必见)
WebApp?:载入ContextBase?/WEB-INF/...,它们仅对该WEB APP可见 

 

5.tomcat app:java.lang.OutOfMemoryError: PermGen space
1、设置tomcat6w.exe
在Java Options添加:
-XX:PermSize=256m
-XX:MaxPermSize=512m
2、在环境变量里面配置:
环境变量:-Xms512m -Xmx1024m -XX:PermSize=256m -XX:MaxPermSize=512m
环境变量名:JAVA_OPTS
3、非安装版设置如下:
修改TOMCAT_HOME/bin/catalina.sh
在“echo "Using CATALINA_BASE:   $CATALINA_BASE"”上面加入以下行:JAVA_OPTS="-server -XX:PermSize=256M -XX:MaxPermSize=512m"
或解决方法:手动设置Heap size 修改TOMCAT_HOME/bin/catalina.sh
在“echo "Using CATALINA_BASE: $CATALINA_BASE"”上面加入以下行: JAVA_OPTS="-server -Xms800m -Xmx800m -XX:MaxNewSize=256m"

可以使用命令java -X查看非标准(non-standard)的程序运行选项
-Xms        set initial Java heap size
-Xmx        set maximum Java heap size(应用程序(不是jvm)能够使用的最大内存数)
-Xss        set java thread stack size

JAVA_OPTS="-server -Xms800m -Xmx800m -XX:PermSize=64M -XX:MaxNewSize=256m -XX:MaxPermSize=128m -Djava.awt.headless=true "

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多