监听器Listener

监听器

6个事件类,均以event结尾
*某些操作,如启动/关闭容器,创建/销毁会话,都将触发一种事件发生,当发生了某种事件,容器将创建对应的事件类对象
8个监听接口,均以Listener结尾
监听器定义了监听方法,可以处理对应的事件

ServletAPI中的6个事件类:
ServletContextEvent:该类表示上下文(ServletContext)事件,当应用上下文对象发生变化,如创建或销毁上下文对象时,将触发上下文事件
ServletContextAttributeEvent:该类表示上下文(ServletContext)属性事件,当应用上下文属性改变,例如增加、删除、覆盖上下文中的属性时,将触发上下文属性事件
ServletRequestEvent:该类表示请求(ServletRequest)事件,当请求对象发生改变,例如创建或者销毁请求对象,将触发此事件
ServletRequestAttributeEvent:该类表示请求(ServletRequest)属性事件,当请求中的属性发生改变,触发该事件
HttpSessionEvent:该类表示会话(HttpSession)事件,当会话对象发生改变,例如创建或者销毁会话对象,活化或者钝化会话对象,将触发此事件
HttpSessionBindingEvent:该类表示会话(HttpSession)绑定事件,当会话中的属性发生变化,例如增加删除覆盖会话中

Servlet API针对每种事件类型,都定义了至少一种借口来处理该事件,这些接口都以Listener结尾,成为监听器接口,共有如下8种接口。
ServletConetxListener:上下文监听器,监听ServletContextEvent事件
ServletContextaAttributeListener:上下文属性监听器,用来监听ServletRequestAttributeEvent事件
ServletRequestListener:请求监听器,监听ServletRequestEvent事件。
ServletRequestAttributeListener:请求属性监听器,用来监听ServletRequestAttributeEvent事件
HttpSessionListener:会话监听器,监听HttpSessionEvent事件
HttpSessionActivationListener:会话活化监听器,监听HttpSessionEvent事件
HttpSessionAttributeListener:会话属性监听器,监听HttpSessionBindingEvent事件
HttpSessionBindingListener:会话绑定监听器,监听HttpSessionBindingEvent事件。

 

使用监听器的小例子:

计算登录次数: 

package cn.itcast.service;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

public class CounterListener implements ServletContextListener{

    public void contextDestroyed(ServletContextEvent arg0) {
        System.out.println("我是销毁方法");
        ServletContext context=arg0.getServletContext();
        CounterService countService=new CounterService();
        countService.saveNub((Integer) context.getAttribute("counter"));
    }

    public void contextInitialized(ServletContextEvent arg0) {
        ServletContext context=arg0.getServletContext();
        CounterService countService=new CounterService();
        context.setAttribute("counter",countService.getNub() );
    }

}
<listener>
      <listener-class>cn.itcast.service.CounterListener</listener-class>
  </listener>
View Code

 

使用监听器开发的步骤:

  1、根据实际情况,选择需要使用的监听器,如监听上下文对象创建或销毁的事件,则使用ServletContextListener

  2、创建新的类,实现选择的监听器接口,兵书写具体实现代码

  3、在web.xml中配置监听器

 

上面的例子全貌:

create table counter
(
       nub integer not null unique
)

package cn.itcast.dao;

import org.hibernate.Query;
import org.hibernate.Session;

import cn.itcast.domain.Counter;
import cn.itcast.utils.SessionFactoryUtil;

public class CounterDao {
    
    public Session getSession(){
        return SessionFactoryUtil.getSession();
    }
    
    public void saveNub(int nub){
        String hql="update Counter set nub=?";
        Query query=getSession().createQuery(hql);
        query.setParameter(0, nub);
        query.executeUpdate();
    }
    
    public int getNub(){
        String hql="from Counter";
        Query query=getSession().createQuery(hql);
        Counter count=(Counter) query.uniqueResult();
        return count.getNub();
    }

}

package cn.itcast.domain;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;

@Table
@Entity
public class Counter implements Serializable{
    
    private static final long serialVersionUID = 1L;
    private int nub;

    @Column
    public int getNub() {
        return nub;
    }

    public void setNub(int nub) {
        this.nub = nub;
    }
    
    public Counter(){
        
    }
    public Counter(int nub){
        this.nub=nub;
    }

}


<?xml version="1.0"?>  
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"  
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">  
  
<hibernate-mapping>  
    <class name="cn.itcast.domain.Counter"   
    table="COUNTER">  
        <composite-id>  
            <key-property name="nub" column="nub" type="java.lang.Integer"/>
        </composite-id>  
    </class>  
</hibernate-mapping>  


package cn.itcast.service;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

public class CounterListener implements ServletContextListener{

    public void contextDestroyed(ServletContextEvent arg0) {
        System.out.println("我是销毁方法");
        ServletContext context=arg0.getServletContext();
        CounterService countService=new CounterService();
        countService.saveNub((Integer) context.getAttribute("counter"));
    }

    public void contextInitialized(ServletContextEvent arg0) {
        ServletContext context=arg0.getServletContext();
        CounterService countService=new CounterService();
        context.setAttribute("counter",countService.getNub() );
    }

}


package cn.itcast.service;

import org.hibernate.Transaction;

import cn.itcast.dao.CounterDao;

public class CounterService {
    private CounterDao counterDao=new CounterDao();
    
    public int getNub(){
        return counterDao.getNub();
    }
    
    public void saveNub(int nub){
        Transaction transaction=counterDao.getSession().beginTransaction();
        try{
            counterDao.saveNub(nub);
            transaction.commit();
        }catch(Exception e){
            e.printStackTrace();
            transaction.rollback();
        }
    }
    
}


package cn.itcast.test;

import org.junit.Test;

import cn.itcast.service.CounterService;
import cn.itcast.utils.SessionFactoryUtil;

@SuppressWarnings("unused")
public class Test01 {
    
    @Test
    public void test1() {
        
        SessionFactoryUtil su=new SessionFactoryUtil();
    }
    
    @Test
    public void test2(){
        CounterService counterService=new CounterService();
        counterService.saveNub(-1);
        System.out.println(counterService.getNub());
        
    }    
    

}


package cn.itcast.utils;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

/**
 * 字符编码过滤器
 * @author Administrator
 *
 */
public class CharacterEncodingFilter implements Filter{
    private String encoding;
    public void destroy() {
        
    }

    public void doFilter(ServletRequest arg0, ServletResponse arg1,
            FilterChain arg2) throws IOException, ServletException {
        arg0.setCharacterEncoding(encoding);
        arg1.setCharacterEncoding(encoding);
        arg2.doFilter(arg0, arg1);
    }

    public void init(FilterConfig arg0) throws ServletException {
        this.encoding=arg0.getInitParameter("encoding");
    }

}


package cn.itcast.utils;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

public class SessionFactoryUtil {
    private static SessionFactory factory;
    private static ThreadLocal<Session> threadLocal=new ThreadLocal<Session>();
    
    static{
        Configuration config=new Configuration().configure();
        ServiceRegistry resgistry = new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry();
        factory=config.buildSessionFactory(resgistry);
    }
    
    public static Session getSession(){
        Session session=threadLocal.get();
        if(session==null){
            session=factory.openSession();
            threadLocal.set(session);
        }
        return session;
    }

}


package cn.itcast.utils;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;

import javax.imageio.ImageIO;

public class VerifyCode {
    private int w=70;
    private int h=35;
    private Random r=new Random();
    private String[] fontNames={"宋体","华文楷体","微软雅体","楷体_GB2312"};
    private String codes="23456789abdcefghjkmnopqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ";
    private Color bgColor=new Color(255,255,255);
    private String text;
    
    private Color randomColor(){
        int red=r.nextInt(150);
        int green=r.nextInt(150);
        int blue=r.nextInt(150);
        return new Color(red,green,blue);
    }
    
    public char randomChar(){
        return codes.charAt(r.nextInt(codes.length()));
    }
    
    private Font randomFont(){
        int index=r.nextInt(fontNames.length);
        String fontName=fontNames[index];
        int style=r.nextInt(4);
        int size=r.nextInt(5)+24;
        return new Font(fontName,style,size);
    }
    
    private void drawLine(BufferedImage image){
        int num=3;
        Graphics2D g2=(Graphics2D)image.getGraphics();
        for(int i=0;i<num;i++){
            int x1=r.nextInt(w);
            int y1=r.nextInt(h);
            int x2=r.nextInt(w);
            int y2=r.nextInt(h);
            g2.setStroke(new BasicStroke(1.5F));
            g2.setColor(Color.BLUE);
            g2.drawLine(x1, y1, x2, y2);
        }
    }
    
    private BufferedImage createImage(){
        BufferedImage bi=new BufferedImage(w,h,BufferedImage.TYPE_INT_RGB);
        Graphics2D g2=(Graphics2D)bi.createGraphics();
        g2.setColor(bgColor);
        g2.fillRect(0, 0, w, h);
        return bi;
    }
    
    private void setText(String text){
        this.text=text;
    }
    
    public String getText(){
        return text;
    }
    
    public BufferedImage getImage(){
        BufferedImage image=createImage();
        Graphics2D g2=(Graphics2D)image.createGraphics();
        StringBuilder sb=new StringBuilder();
        for(int i=0;i<4;i++){
            String s=randomChar()+"";
            sb.append(s);
            float x=i*1.0F*w/4;
            g2.setFont(randomFont());
            g2.setColor(randomColor());
            g2.drawString(s, x, h-5);
        }
        this.setText(sb.toString());
        drawLine(image);
        return image;
    }
    
    public static void output(BufferedImage image,OutputStream out){
        try {
            ImageIO.write(image, "JPEG", out);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}


package cn.itcast.web;

import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.itcast.utils.VerifyCode;

@SuppressWarnings("static-access")
public class CheckCodeServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request,response);
    }
    
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        VerifyCode verify=new VerifyCode();
        BufferedImage image=verify.getImage();
        String text=verify.getText();
        request.getSession().setAttribute("checkCode", text);
        verify.output(image, response.getOutputStream());
    }

}


package cn.itcast.web;

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 LoginServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

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

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        ServletContext context=this.getServletContext();
        String name=request.getParameter("username");
        String password=request.getParameter("password");
        String checkCode=request.getParameter("checkCode");
        String text=(String) request.getSession().getAttribute("checkCode");
        int x=(Integer) context.getAttribute("counter")+1;
        
        System.out.println(name+"  "+password+" "+checkCode+" "+text);
        
        context.setAttribute("counter", x);
        request.setAttribute("loginName",name);
        request.getRequestDispatcher("/success.jsp").forward(request, response);
    }

}

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

    <session-factory>

        <!-- Database connection settings -->
        <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
        <property name="connection.url">jdbc:oracle:thin:@localhost:1521:DB</property>
        <property name="connection.username">scott</property>
        <property name="connection.password">961012gz</property>
        
        
        <property name="dialect">org.hibernate.dialect.OracleDialect</property>
        <property name="show_sql">true</property>

        <!--  
            <mapping class="cn.itcast.domain.Counter"/>
        -->
        <mapping resource="cn/itcast/domain/Counter.hbm.xml"/>

    </session-factory>

</hibernate-configuration>


<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
    xmlns="http://java.sun.com/xml/ns/javaee" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <display-name></display-name>    
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  
  <servlet>
      <servlet-name>checkCodeServlet</servlet-name>
      <servlet-class>cn.itcast.web.CheckCodeServlet</servlet-class>
  </servlet>
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>LoginServlet</servlet-name>
    <servlet-class>cn.itcast.web.LoginServlet</servlet-class>
  </servlet>

  <servlet-mapping>
      <servlet-name>checkCodeServlet</servlet-name>
      <url-pattern>/checkCode</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>LoginServlet</servlet-name>
    <url-pattern>/login</url-pattern>
  </servlet-mapping>
  <filter>
      <filter-name>CharacterEncoding</filter-name>
      <filter-class>cn.itcast.utils.CharacterEncodingFilter</filter-class>
      <init-param>
          <param-name>encoding</param-name>
          <param-value>utf-8</param-value>
      </init-param>
  </filter>
  
  <filter-mapping>
      <filter-name>CharacterEncoding</filter-name>
      <url-pattern>/*</url-pattern>
  </filter-mapping>
  
  <listener>
      <listener-class>cn.itcast.service.CounterListener</listener-class>
  </listener>
</web-app>


<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'login.jsp' starting page</title>
    
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
    <script>
        function change(){
            var img=document.getElementsByName("img")[0];
            img.src="checkCode?date="+new Date().getTime();
        }
    </script>
  </head>
  
  <body>
    <form action="login" method="post">
        用户名:<input type="text" name="username"><br/>
        密码:<input type="password" name="password"><br/>
        验证码:<input type="text" size="5" name="checkCode"/><img src="checkCode" name="img"><a href="javascript:void(0)" onclick="change()">刊不清,换一张</a><br/>
        <input type="submit" value="登录">
    </form>
  </body>
</html>


<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'success.jsp' starting page</title>
    
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->

  </head>
  
  <body>
    欢迎${requestScope.loginName }莅临本系统<br/>
   <p align="right">访问量${applicationScope.counter }</p>
  </body>
</html>
View Code

 

Listener: 监听器
1、初次见面:AWT
2、二次见面:SAX

监听器:
它是一个接口,内容由我们来实现
它需要注册,例如注册在按钮上
监听器中的方法,会在特殊事件发生时被调用!

观察着:
事件源
小偷
事件
偷东西
监听器
警察
监听器中的方法:抓捕

javaWeb中的监听器
事件源:三大域
ServletContext
生命周期监听:ServletContextListener,它有两个方法,一个在出生时调用,一个在死亡时调用;
属性监听:ServletContextAttributeListener,它有三个方法,一个是在添加属性的时候调用,一个是在替换属性的时候调用,一个是在移除属性时调用

HttpSession
生命周期监听:HttpSessionListener,它有两个方法,一个在出生时调用,一个在死亡时调用;
属性监听:HttpSessionAttributeListener,它有三个方法,一个是在添加属性的时候调用,一个是在替换属性的时候调用,一个是在移除属性时调用

ServletRequest
生命周期监听:ServletRequestListener,它有两个方法,一个在出生时调用,一个在死亡时调用;
属性监听:ServletRequestAttributeListener,它有三个方法,一个是在添加属性的时候调用,一个是在替换属性的时候调用,一个是在移除属性时调用

javaWeb中完成编写监听器:
写一个监听器类:要求必须去实现某个监听器接口
注册,是在web.xml中配置来完成

一个生命周期监听和属性监听例子:

package cn.itcast.web.listener;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

/**
 * ServletContext生死监听
 * @author Administrator
 * 
 * 可以在这个监听器存放一些在tomcat启动时就要完成的代码!
 *
 */
public class Alistener implements ServletContextListener {

    public void contextDestroyed(ServletContextEvent arg0) {
        System.out.println("我还会再回来的!");
    }

    public void contextInitialized(ServletContextEvent arg0) {
        System.out.println("我胡汉三又回来了");
    }

}

package cn.itcast.web.listener;

import javax.servlet.ServletContextAttributeEvent;
import javax.servlet.ServletContextAttributeListener;

public class Blistener implements ServletContextAttributeListener{

    public void attributeAdded(ServletContextAttributeEvent arg0) {
        System.out.println("您向application中添加了一个名为"+arg0.getName()+",值为:"+arg0.getValue()+"的属性");
    }

    public void attributeRemoved(ServletContextAttributeEvent arg0) {
        System.out.println(arg0.getName()+"="+arg0.getValue());//最后一次相见
    }

    public void attributeReplaced(ServletContextAttributeEvent arg0) {
        System.out.println(arg0.getName()+ "="+arg0.getValue()+","+arg0.getServletContext().getAttribute(arg0.getName()));//返回的是之前的值,最后一次相见
    }

}



 <listener>
      <listener-class>cn.itcast.web.listener.Alistener</listener-class>
  </listener>

<listener>
      <listener-class>cn.itcast.web.listener.Blistener</listener-class>
  </listener>

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'index.jsp' starting page</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
  </head>
  
  <body>
      <% 
          application.setAttribute("xxx", "XXX");
      %>
    This is my JSP page. <br>
  </body>
</html>

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'remove.jsp' starting page</title>
    
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->

  </head>
  
  <body>
      <% 
          application.removeAttribute("xxx");
      %>
    This is my JSP page. <br>
  </body>
</html>

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'repeat.jsp' starting page</title>
    
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->

  </head>
  
  <body>
    <% 
          application.setAttribute("xxx", "YYY");
      %>
  </body>
</html>
View Code

 



另外两个监听:感知监听(与HttpSession相关)
它用来添加到javaBean上,而不是添加到三大域
无需在web.xml注册
HttpSessionBindingListener:添加到javabean上,javabean就知道自己是否添加到session中了

监听bean添加到session的例子:

package cn.itcast.web.listener;

import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionBindingListener;

public class User implements HttpSessionBindingListener {
    private String username;
    private String password;
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public User() {
        super();
        // TODO Auto-generated constructor stub
    }
    public User(String username, String password) {
        super();
        this.username = username;
        this.password = password;
    }
    public void valueBound(HttpSessionBindingEvent arg0) {
        System.out.println("啊,session添加了我!");
    }
    public void valueUnbound(HttpSessionBindingEvent arg0) {
        System.out.println("啊,无情的session抛弃了我!");
    }
    

}


<%@ page language="java" import="java.util.*,cn.itcast.web.listener.User" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'add.jsp' starting page</title>
    
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->

  </head>
  
  <body>
    <% 
    User user=new User("gz","6545");
    session.setAttribute("user", user);
    %>
  </body>
</html>


<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'remove.jsp' starting page</title>
    
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->

  </head>
  
  <body>
    <% 
        session.removeAttribute("user");
    %>
  </body>
</html>
View Code

 


session的序列化:
程序有session的时候,意外关闭程序,会自动将session的序列化文件保存起来。重启项目,序列化文件消失,之前的session加载回服务器
存放文件夹例子:E:\anzhuang\tomcat7\apache-tomcat-7.0.70-windows-x86\apache-tomcat-7.0.70\work\Catalina\localhost\8-2_2
文件例子:SESSIONS.ser
废弃session的序列化:
在context.xml中的<Context>标签体内加上
<Manager pathname="" />
Session的钝化和活化:
在一些比较大的网站的时候,访问量过多的话,可能会导致系统占用内存过多。一中利用session钝化优化的手段,就是在context中设置session自动钝化,也就是说在一段时间内,
如果session没有被访问,session就被序列化到硬盘上,再次使用该session的时候,session自动从硬盘上反序列化到内存中。
在Context中设置:
<Manager className="org.apache.catalina.session.PersistentManager" maxIdleSwap="1"><!-- maxIdleSwap代表session的钝化周期,单位分钟 -->
<Store CLASSnAME="org.apache.catalina.session.FileStore" directory="mysession"/><!-- session的序列化文件的存放路径 -->
</manager>

HttpSessionActivationListener:添加到javabean上,监听bean随着session的钝化活化的过程

最后一个监听,监听bean的钝化和活化过程:

package cn.itcast;

import java.io.Serializable;

import javax.servlet.http.HttpSessionActivationListener;
import javax.servlet.http.HttpSessionEvent;

public class User implements HttpSessionActivationListener,Serializable {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    /**
     * 注意:这个User必须实现序列化接口,否则无法写入硬盘
     */
    public void sessionDidActivate(HttpSessionEvent arg0) {
        System.out.println("啊,~我和session一起重返地球了!");
    }

    public void sessionWillPassivate(HttpSessionEvent arg0) {
        System.out.print("啊,~我陪session去火星了,地球已经不安全了!");
    }

}

<%@ page language="java" import="java.util.*,cn.itcast.User" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'a.jsp' starting page</title>
    
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->

  </head>
  
  <body>
    <h1>向session中保存数据</h1>
    <% 
        session.setAttribute("xxx", "我是一只快乐的小session");
        session.setAttribute("yyy",new User());
    %>
  </body>
</html>

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'b.jsp' starting page</title>
    
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->

  </head>
  
  <body>
    <h2>获取session中的数据</h2>
    <%  
        /* out.print(session.getAttribute("xxx")); */
        out.println(session.getAttribute("yyy"));
    %>
  </body>
</html>

context中的配置:
<Manager className="org.apache.catalina.session.PersistentManager" maxIdleSwap="1">
                <Store className="org.apache.catalina.session.FileStore" directory="mysession"/>
    </Manager>
View Code

 

posted @ 2016-07-26 13:59  guodaxia  阅读(548)  评论(0编辑  收藏  举报