public void attributeReplaced(ServletContextAttributeEvent arg0) {
System.out.println(\替换的application的属性名为:}
\值为:\ }
}
Web.xml
别的文件中新建修改删除application
//建立application
ServletContext application= getServletContext();
//添加
application.setAttribute(\, password);
//修改
application.setAttribute(\, \);
//移除
application.removeAttribute(\);
结果:
添加的application的属性名为:password值为:admin 替换的application的属性名为:password值为:admin 移除的application的属性名为:password值为:replace
3、HttpSessionListener接口
HttpSessonListener接口用来实现session的初始化和销
毁的监听。该接口中包括两个方法,sessionCreated() 用来监听session的创建和初始化,另一个是sessionDestroyed()方法用来监听session的销毁。这两个方法还包括一个参数se,其类型为HttpSessionEvent,可以通过HttpSessionEvent对象的getSession()方法获得session对象 DEMO:
package cn.servlet;
import javax.servlet.http.HttpSession; import javax.servlet.http.HttpSessionEvent; import javax.servlet.http.HttpSessionListener;
public class HttpSessionListenerDemo implements HttpSessionListener { }
public void sessionDestroyed(HttpSessionEvent arg0) { }
System.out.println(\销毁的session \);
}
public void sessionCreated(HttpSessionEvent arg0) {
HttpSession session = arg0.getSession();
System.out.println(\新创建的session的id为\+session.getId());
Web.xml
别的文件中://销毁session session.invalidate();
结果:新创建的session的id为37A0BF336A6E9894BA90395E4B9104D5 4.HttpSessionAttributeListener接口 本接口用来实现session范围属性变化的监听,该接口中 包括三个方法:attributeAdded(), attributeReplaced(), attributeRemove(),可用其参数的方法getName()以及getValue方法 DEMO: package cn.servlet; import javax.servlet.http.HttpSessionAttributeListener; import javax.servlet.http.HttpSessionBindingEvent; public class HttpSessionAttributeListenerDemo implements public void attributeAdded(HttpSessionBindingEvent arg0) { System.out.println(\添加的session名\值为:\ public void attributeRemoved(HttpSessionBindingEvent arg0) { System.out.println(\移除的session名\值为:\ public void attributeReplaced(HttpSessionBindingEvent arg0) { System.out.println(\替换的session名\值为:\ } } } } HttpSessionAttributeListener { Web.xml 别的文件中 //建立session HttpSession session = request.getSession(); //添加 session.setAttribute(\, username); //修改 session.setAttribute(\, \); //移除 session.removeAttribute(\); 结果: 添加的session名username 值为:admin 替换的session名username 值为:admin 移除的session名username 值为:replaced Servlet的几种跳转 在Servlet中跳转都发生在doGet()和doPost()方法中 1,redirect方式 response.sendRedirect(“文件路径”); 本方式可以跳转到任何页面。 DEMO:response.sendRedirect(“http://http://www.wodefanwen.com/”); 跳转后浏览器的地址栏变化,这种方式要传值得化只能放在url中或session中无法使用request.serAttribute来传递。 这种方式在客户端做重定向处理。该方法通过修改HTTP协议的header部分对浏览器下达重定向命令,让浏览器对在location中指定的urlt提出请求,使浏览器显示重定向网页的内容。 2.forward方式 RequestDispatcher dispatcher = request.getRequestDispatcher(“路径”); dispatcher.forward(request,response); 路径是相对路径,只能跳转到本web应用中的页面跳转后浏览器地址栏不会变化。 使用这种方式跳转,传值可以使用三种方法:url中带parameter,session,request.setAttribute 设计模式 DAO设计模式 1.DAO五个重要组成部分 数据库连接部分, VO类,DAO接口,DAO实现类,DAO工具类 2、数据连接类 主要功能:连接数据库并获取连接对象,以及关闭数据库。 在需要进行数据库连接时只需创建该类的实例调用其方法就可以获取其连接对象和关闭数据库。 Demo: package cn.dao;