Java Servlet 是运行在带有支持 Java Servlet 规范的解释器的 web 服务器上的 Java 类。
一、Servlet基础:
1.1 Servlet处理流程。
1.部署Web应用服务,Tomcat作为Servlet容器,利用Tomcat启动应用程序,会创建并初始化Servlet;
2.通过浏览器访问Web应用服务器,利用Http通讯协议传递数据;
3.当访问到达时,Servlet容器创建HttpServletRequest和HttpServletResponse对象,并且将请求数据放入HttpServletRequest中,同时请求信息通常是可以在一个共享容器(ServletContext)内存储和取出;
4.Servlet容器根据传递的url通过匹配web.xml中配置的Servlet路径,找到对应的Servlet,传递请求和响应对象;
<servlet>
<servlet-name>Init</servlet-name>
<servlet-class>org.xl.servlet.InitServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
5.Servlet中根据请求方式调用doGet或doPost方法,处理请求数据,将响应数据放入HttpServletResponse,返回给Servlet容器;
6.Servlet容器解析响应数据,根据HTTP通讯协议,返回给浏览器,浏览器解析并展示数据。
1.2 Servlet继承关系
public abstract class HttpServlet extends GenericServlet {
private static final String METHOD_DELETE = "DELETE";
private static final String METHOD_HEAD = "HEAD";
private static final String METHOD_GET = "GET";
private static final String METHOD_OPTIONS = "OPTIONS";
private static final String METHOD_POST = "POST";
private static final String METHOD_PUT = "PUT";
private static final String METHOD_TRACE = "TRACE";
private static final String HEADER_IFMODSINCE = "If-Modified-Since";
private static final String HEADER_LASTMOD = "Last-Modified";
private static final String LSTRING_FILE = "javax.servlet.http.LocalStrings";
private static ResourceBundle lStrings = ResourceBundle.getBundle("javax.servlet.http.LocalStrings");
public HttpServlet() {}
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {}
protected long getLastModified(HttpServletRequest req) {}
protected void doHead(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {}
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {}
protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {}
protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {}
private Method[] getAllDeclaredMethods(Class<? extends HttpServlet> c) {}
protected void doOptions(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {}
protected void doTrace(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {}
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {}
private void maybeSetLastModified(HttpServletResponse resp, long lastModified) {}
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {}
}
public abstract class GenericServlet implements Servlet, ServletConfig, Serializable {
private static final String LSTRING_FILE = "javax.servlet.LocalStrings";
private static ResourceBundle lStrings = ResourceBundle.getBundle("javax.servlet.LocalStrings");
private transient ServletConfig config;
public GenericServlet() {}
public void destroy() {}
public String getInitParameter(String name) {}
public Enumeration<String> getInitParameterNames() {}
public ServletConfig getServletConfig() {}
public ServletContext getServletContext() {}
public String getServletInfo() {}
public void init(ServletConfig config) throws ServletException {}
public void init() throws ServletException {} //让子类复写用
public void log(String msg) {}
public void log(String message, Throwable t) {}
public abstract void service(ServletRequest var1, ServletResponse var2) throws ServletException, IOException;
public String getServletName() {}
}
public interface ServletConfig {
String getServletName();
ServletContext getServletContext();
String getInitParameter(String var1);
Enumeration<String> getInitParameterNames();
}
public interface Servlet {
void init(ServletConfig var1) throws ServletException;
ServletConfig getServletConfig();
void service(ServletRequest var1, ServletResponse var2) throws ServletException, IOException;
String getServletInfo();
void destroy();
}
二、Servlet生命周期:
public class InitServlet extends HttpServlet{
//初始化servlet,调用init方法,只调用一次.
@Override
public void init() throws ServletException {
System.out.println("初始化时调用");
}
//每次服务器接收到一个 Servlet 请求时,服务器会产生一个新的线程并调用服务。
//service() 方法检查 HTTP 请求类型(GET、POST、PUT、DELETE 等),并在适当的时候调用 doGet、doPost、doPut,doDelete 等方法。
@Override
protected void service(HttpServletRequest arg0, HttpServletResponse arg1) throws ServletException, IOException {
System.out.println("开启服务时调用");
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
}
//方法只会被调用一次,在 Servlet 生命周期结束时被调用。
//destroy() 方法可以让您的 Servlet 关闭数据库连接、停止后台线程、把 Cookie 列表或点击计数器写入到磁盘,并执行其他类似的清理活动。
//在调用 destroy() 方法之后,servlet 对象被标记为垃圾回收。
@Override
public void destroy() {
System.out.println("销毁时调用");
}
}
2.1 init初始化操作
实例1: 读取web.xml的配置信息。
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0"
metadata-complete="true">
<!-- 声明初始化参数,这里初始化对应的xml文件(全局) -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath*:/config/spring/applicationContext.xml,classpath*:/config/spring/applicationContext-repository.xml
</param-value>
</context-param>
<servlet>
<servlet-name>initServlet</servlet-name>
<servlet-class>com.examples.servlet.InitServlet</servlet-class>
<!-- 对initServlet进行初始化参数(局部) -->
<init-param>
<param-name>initParam1</param-name>
<param-value>initServlet的初始参数:1</param-value>
</init-param>
<init-param>
<param-name>initParam2</param-name>
<param-value>initServlet的初始参数:2</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>initServlet</servlet-name>
<url-pattern>/ServletInit</url-pattern>
</servlet-mapping>
</web-app>
InitServlet.java
public class InitServlet extends HttpServlet {
public void init() throws ServletException {
String servletName=getServletConfig().getServletName();
System.out.println("ABO:---->servletName:【"+servletName+"】");
String contextParam =getServletConfig().getServletContext().getInitParameter("contextConfigLocation");
System.out.println("ABO:---->contextParam:【"+contextParam+"】");
Enumeration <String > enums=getServletConfig().getInitParameterNames();
while(enums.hasMoreElements()){
String param=enums.nextElement();
String paramValue=getInitParameter(param);
System.out.println("ABO:---->ParameterValues:【"+paramValue +"】");
}
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
控制台输出
ABO:---->servletName:【initServlet】
ABO:---->contextParam:【classpath*:/config/spring/applicationContext.xml,classpath*:/config/spring/applicationContext-repository.xml】
ABO:---->ParameterValues:【initServlet的初始参数:2】
ABO:---->ParameterValues:【initServlet的初始参数:1】
2.2. Servlet接收和响应浏览器请求
Servlet使用HttpServletRequest和HttpServletResponse处理浏览器请求以及对浏览器进行响应。
其中重定向和转发的区别:
- 重定向会改变地址栏的内容,转发不会。
- 重定向是两次请求的过程,而转发只有一次。重定向是由浏览器完成的,转发是服务器内部完成的转发由于是一次过程,所以request和response能在Servlet和jsp中共享,可以在里面添加Attribute,而重定向是两次过程,两次之间的request和response是独立的。
- 转发和重定向代码中的path路径的写法也不一样,转发中的/代表服务器的web站点目录,重定向/代表webapps这个目录。
HttpServletRequest API
Cookie[] getCookies():返回一个数组,包含客户端发送该请求的所有的 Cookie 对象。
Enumeration getAttributeNames():返回一个枚举,包含提供给该请求可用的属性名称。
Enumeration getHeaderNames():返回一个枚举,包含在该请求中包含的所有的头名。
Enumeration getParameterNames():返回一个String对象的枚举,包含在该请求中包含的参数的名称。
HttpSession getSession():返回与该请求关联的当前 session 会话,或者如果请求没有 session 会话,则创建一个。
HttpSession getSession(boolean create):返回与该请求关联的当前 HttpSession,或者如果没有当前会话,且创建是真的,则返回一个新的 session 会话。
Locale getLocale():基于 Accept-Language 头,返回客户端接受内容的首选的区域设置。
Object getAttribute(String name):以对象形式返回已命名属性的值,如果没有给定名称的属性存在,则返回 null。
ServletInputStream getInputStream():使用 ServletInputStream,以二进制数据形式检索请求的主体。
String getAuthType():返回用于保护 Servlet 的身份验证方案的名称,例如,"BASIC" 或 "SSL",如果JSP没有受到保护则返回 null。
String getCharacterEncoding():返回请求主体中使用的字符编码的名称。
String getContentType():返回请求主体的 MIME 类型,如果不知道类型则返回 null。
String getContextPath():返回指示请求上下文的请求 URI 部分。
String getHeader(String name):以字符串形式返回指定的请求头的值。
String getMethod():返回请求的 HTTP 方法的名称,例如,GET、POST 或 PUT。
String getParameter(String name):以字符串形式返回请求参数的值,或者如果参数不存在则返回 null。
String getPathInfo():当请求发出时,返回与客户端发送的 URL 相关的任何额外的路径信息。
String getProtocol():返回请求协议的名称和版本。
String getQueryString():返回包含在路径后的请求 URL 中的查询字符串。
String getRemoteAddr():返回发送请求的客户端的互联网协议(IP)地址。
String getRemoteHost():返回发送请求的客户端的完全限定名称。
String getRemoteUser():如果用户已通过身份验证,则返回发出请求的登录用户,或者如果用户未通过身份验证,则返回 null。
String getRequestURI():从协议名称直到 HTTP 请求的第一行的查询字符串中,返回该请求的 URL 的一部分。
String getRequestedSessionId():返回由客户端指定的 session 会话 ID。
String getServletPath():返回调用 JSP 的请求的 URL 的一部分。
String[] getParameterValues(String name):返回一个字符串对象的数组,包含所有给定的请求参数的值,如果参数不存在则返回 null。
boolean isSecure():返回一个布尔值,指示请求是否使用安全通道,如 HTTPS。
int getContentLength():以字节为单位返回请求主体的长度,并提供输入流,或者如果长度未知则返回 -1。
int getIntHeader(String name):返回指定的请求头的值为一个 int 值。
int getServerPort():返回接收到这个请求的端口号。
int getParameterMap():将参数封装成 Map 类型。
HttpServletResponse API
String encodeRedirectURL(String url):为 sendRedirect 方法中使用的指定的 URL 进行编码,或者如果编码不是必需的,则返回 URL 未改变。
String encodeURL(String url):对包含 session 会话 ID 的指定 URL 进行编码,或者如果编码不是必需的,则返回 URL 未改变。
boolean containsHeader(String name):返回一个布尔值,指示是否已经设置已命名的响应报头。
boolean isCommitted():返回一个布尔值,指示响应是否已经提交。
void addCookie(Cookie cookie):把指定的 cookie 添加到响应。
void addDateHeader(String name, long date):添加一个带有给定的名称和日期值的响应报头。
void addHeader(String name, String value):添加一个带有给定的名称和值的响应报头。
void addIntHeader(String name, int value):添加一个带有给定的名称和整数值的响应报头。
void flushBuffer():强制任何在缓冲区中的内容被写入到客户端。
void reset():清除缓冲区中存在的任何数据,包括状态码和头。
void resetBuffer():清除响应中基础缓冲区的内容,不清除状态码和头。
void sendError(int sc):使用指定的状态码发送错误响应到客户端,并清除缓冲区。
void sendError(int sc, String msg):使用指定的状态发送错误响应到客户端。
void sendRedirect(String location):使用指定的重定向位置 URL 发送临时重定向响应到客户端。
void setBufferSize(int size):为响应主体设置首选的缓冲区大小。
void setCharacterEncoding(String charset):设置被发送到客户端的响应的字符编码(MIME 字符集)例如,UTF-8。
void setContentLength(int len):设置在 HTTP Servlet 响应中的内容主体的长度,该方法设置 HTTP Content-Length 头。
void setContentType(String type):如果响应还未被提交,设置被发送到客户端的响应的内容类型。
void setDateHeader(String name, long date):设置一个带有给定的名称和日期值的响应报头。
void setHeader(String name, String value):设置一个带有给定的名称和值的响应报头。
void setIntHeader(String name, int value):设置一个带有给定的名称和整数值的响应报头。
void setLocale(Locale loc):如果响应还未被提交,设置响应的区域。
void setStatus(int sc):为该响应设置状态码。
浏览器会话对象:Session 、Cookie
Session API
public Object getAttribute(String name):该方法返回在该 session 会话中具有指定名称的对象,如果没有指定名称的对象,则返回 null。
public Enumeration getAttributeNames():该方法返回 String 对象的枚举,String 对象包含所有绑定到该 session 会话的对象的名称。
public long getCreationTime():该方法返回该 session 会话被创建的时间,自格林尼治标准时间 1970 年 1 月 1 日午夜算起,以毫秒为单位。
public String getId():该方法返回一个包含分配给该 session 会话的唯一标识符的字符串。
public long getLastAccessedTime():该方法返回客户端最后一次发送与该 session 会话相关的请求的时间自格林尼治标准时间 1970 年 1 月 1 日午夜算起,以毫秒为单位。
public int getMaxInactiveInterval():该方法返回 Servlet 容器在客户端访问时保持 session 会话打开的最大时间间隔,以秒为单位。
public void invalidate():该方法指示该 session 会话无效,并解除绑定到它上面的任何对象。
public boolean isNew():如果客户端还不知道该 session 会话,或者如果客户选择不参入该 session 会话,则该方法返回 true。
public void removeAttribute(String name):该方法将从该 session 会话移除指定名称的对象。
public void setAttribute(String name, Object value) :该方法使用指定的名称绑定一个对象到该 session 会话。
public void setMaxInactiveInterval(int interval):该方法在 Servlet 容器指示该 session 会话无效之前,指定客户端请求之间的时间,以秒为单位。
Cookie API
public void setDomain(String pattern):该方法设置 cookie 适用的域,例如 runoob.com。
public String getDomain():该方法获取 cookie 适用的域,例如 runoob.com。
public void setMaxAge(int expiry):该方法设置 cookie 过期的时间(以秒为单位)。如果不这样设置,cookie 只会在当前 session 会话中持续有效。
public int getMaxAge():该方法返回 cookie 的最大生存周期(以秒为单位),默认情况下,-1 表示 cookie 将持续下去,直到浏览器关闭。
public String getName():该方法返回 cookie 的名称。名称在创建后不能改变。
public void setValue(String newValue):该方法设置与 cookie 关联的值。
public String getValue():该方法获取与 cookie 关联的值。
public void setPath(String uri):该方法设置 cookie 适用的路径。如果您不指定路径,与当前页面相同目录下的(包括子目录下的)所有 URL 都会返回 cookie。
public String getPath():该方法获取 cookie 适用的路径。
public void setSecure(boolean flag):该方法设置布尔值,表示 cookie 是否应该只在加密的(即 SSL)连接上发送。
public void setComment(String purpose):设置cookie的注释。该注释在浏览器向用户呈现 cookie 时非常有用。
public String getComment():获取 cookie 的注释,如果 cookie 没有注释则返回 null。
示例:
package com.examples.servlet;
import com.examples.pojo.User;
import org.junit.Test;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Date;
import java.util.Enumeration;
import java.util.Properties;
public class InitServlet extends HttpServlet {
public void init() throws ServletException {}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//请求解码 响应设置编码
req.setCharacterEncoding("UTF-8");
// 获取字节输出流 处理响应乱码
//OutputStream os = response.getOutputStream();
//os.write("哈罗我的".getBytes("UTF-8"));
// 获取字符输出流 处理响应乱码
//PrintWriter out = resp.getWriter();
//resp.setContentType("text/html;charset=UTF-8");
//下面两个等同于resp.setContentType("text/html;charset=UTF-8");
// 设置response缓冲区的编码
//resp.setCharacterEncoding("UTF-8");
// 设置浏览器打开文件所采用的编码
//resp.setHeader("Content-Type", "text/html;charset=UTF-8");
//0- 使用PrintWriter对象相应浏览器请求
PrintWriter out = resp.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title>InitServlet</title>");
out.println("</head>");
out.println("<body>");
//1- 接收HttpServletRequest相关内容
User user=new User();
user.setUserName((String) req.getParameter("userName"));
user.setPassword((String) req.getParameter("password"));
out.println(user.getUserName()+"||"+user.getPassword());
out.println("<br/>");
//2- 接收cookies
Cookie[] cookies = req.getCookies();
for (int i = 0; i <cookies.length ; i++) {
Cookie cookie=cookies[i];
if (cookie.getName().equals("cookie")){
out.println("Cookie:"+URLDecoder.decode(cookie.getValue(),"UTF-8"));
out.println("<br/>");
}
}
// 3- 接收Session
HttpSession session=req.getSession();
if(session.getAttribute("mySession")!=null){
out.println(URLDecoder.decode((String) session.getAttribute("mySession"),"UTF-8"));
out.println("<br/>");
}
//设置Cookie
Cookie cookie=new Cookie("cookie", URLEncoder.encode("小饼干","UTF-8"));
cookie.setMaxAge(24*60*60);
resp.addCookie(cookie);
//设置Session
session.setAttribute("mySession","我的名字:XSession");
if (session.isNew()){
out.write("注销后的Session,ID:"+session.getId());
out.println("<br/>");
}else {
out.write("服务器初始Session,ID:"+session.getId());
out.println("<br/>");
}
//注销cookie和session
if("clear".equals(user.getPassword())){
cookie.setMaxAge(0);
session.invalidate();
}
out.println("</body>");
out.println("</html>");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
2.3 Servlet过滤器
Servlet 过滤器是可用于 Servlet 编程的 Java 类,过滤器是以一种组件的形式绑定到WEB应用程序当中的,与其他的WEB应用程序组件不同的是,过滤器是采用了“链”的方式进行处理的。可以实现以下目的:
- 在客户端的请求访问后端资源之前,拦截这些请求。
- 在服务器的响应发送回客户端之前,处理这些响应。
CharEncodeFilter.java
package com.examples.filter;
import javax.servlet.*;
import java.io.IOException;
public class CharEncodeFilter implements Filter {
private FilterConfig config = null;
public void init(FilterConfig arg0) throws ServletException {
this.config = arg0;
System.out.println("MyCharsetFilter初始化...");
}
public void doFilter(ServletRequest arg0, ServletResponse arg1,FilterChain chain) throws IOException, ServletException{
// 强制类型转换
HttpServletRequest request = (HttpServletRequest) arg0;
HttpServletResponse response = (HttpServletResponse) arg1;
// 获取web.xm设置的编码集,设置到Request、Response中
request.setCharacterEncoding(config.getInitParameter("charset"));
response.setContentType(config.getInitParameter("contentType"));
response.setCharacterEncoding(config.getInitParameter("charset"));
// 将请求转发到目的地
chain.doFilter(request, response);
}
public void destroy(){
System.out.println("MyCharsetFilter准备销毁...");
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0"
metadata-complete="true">
<!-- 声明初始化参数,这里初始化对应的xml文件 -->
<filter>
<filter-name>filter</filter-name>
<filter-class>com.examples.filter.CharEncodeFilter</filter-class>
<init-param>
<param-name>charset</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>contentType</param-name>
<param-value>text/html;charset=UTF-8</param-value>
</init-param>
<filter-mapping>
<filter-name>charEncodeFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>initServlet</servlet-name>
<servlet-class>com.examples.servlet.InitServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>initServlet</servlet-name>
<url-pattern>/ServletInit</url-pattern>
</servlet-mapping>
</web-app>
2.4 Servlet监听器
2.4.1 对Servlet上下文监听
可以监听ServletContext对象的创建和删除以及属性的添加、删除和修改等操作,该监听器需要用到如下两个接口类:
(1)ServletContextAttributeListener:监听对ServletContext属性的操作,比如增加、删除、修改。
(2)ServletContextListener:监听对ServletContext对象的创建和删除。
import javax.servlet.ServletContextAttributeEvent;
import javax.servlet.ServletContextAttributeListener;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class ServletContext implements ServletContextListener,ServletContextAttributeListener{
//上下文属性:添加、删除、修改监听
//1.上下文属性添加监听
public void attributeAdded(ServletContextAttributeEvent scae) {
print("增加ServletContext对象的一个属性:"+scae.getName()+","+scae.getValue());
}
//2.上下文属性删除监听
public void attributeRemoved(ServletContextAttributeEvent scae) {
print("删除ServletContext对象的一个属性:"+scae.getName()+","+scae.getValue());
}
//3.上下文属性修改监听
public void attributeReplaced(ServletContextAttributeEvent scae) {
print("修改ServletContext对象的一个属性:"+scae.getName()+","+scae.getValue());
}
//上下文对象:创建、销毁监听
//1.上下文对象创建监听
public void contextInitialized(ServletContextEvent sce) {
print("ServletContext初始化......"); }
//2.上下文对象销毁监听
public void contextDestroyed(ServletContextEvent sce) {
print("ServletContext销毁......"); }
@SuppressWarnings("deprecation")
private void print(String message){
//调用该方法在txt文件中打印出message字符串信息
PrintWriter out = null;
try {
out = new PrintWriter(new FileOutputStream("F:context_result.txt",true));
out.println(new java.util.Date().toLocaleString()+"contextListener:"+message);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();) }
}
}
2.4.2 对HTTP会话进行监听
可以监听http会话活动情况和http会话中的属性设置情况,也可以监听http会话的active和passivate情况等,该监听器需要用到如下多个接口类:
(1)HttpSessionListener:监听httpSession的操作。
(2)HttpSessionActivationListener:用于监听http会话的active和passivate情况。
(3)HttpSessionAttributeListener:监听HttpSession中的属性操作 。
import java.io.FileNotFoundException
import java.io.FileOutputStream;
import java.io.PrintWriter;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.http.HttpSessionActivationListener;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
public class SessionListener implements HttpSessionActivationListener,HttpSessionAttributeListener,
HttpSessionListener,ServletContextListener{
ServletContext context;
int users;
//session属性监听
//1.监听属性添加
public void attributeAdded(HttpSessionBindingEvent arg0) {
print("attributeAdded('"+arg0.getSession().getId()+"','"+arg0.getName()+"','"+arg0.getValue()+"')");
}
//2.监听属性删除
public void attributeRemoved(HttpSessionBindingEvent arg0) {
print("attributeRemoved('"+arg0.getSession().getId()+"','"+arg0.getName()+"','"+arg0.getValue()+"')");
}
//3.监听属性替换
public void attributeReplaced(HttpSessionBindingEvent arg0) {
print("attributeReplaced('"+arg0.getSession().getId()+"','"+arg0.getName()+"','"+arg0.getValue()+"')");
}
//session会话创建监听
//1.监听会话创建
public void sessionCreated(HttpSessionEvent arg0) {
users++;
print("sessionCreated('"+arg0.getSession().getId()+"'),目前拥有"+users+"个用户");
context.setAttribute("users",new Integer(users));
}
//2.监听会话释放
public void sessionDestroyed(HttpSessionEvent arg0) {
users--;
print("sessionDestroyed('"+arg0.getSession().getId()+"'),目前拥有"+users+"个用户");
context.setAttribute("users",new Integer(users));
}
public void contextInitialized(ServletContextEvent arg0) {
this.context = arg0.getServletContext();
this.print("ServletContext的初始化.....");
}
public void contextDestroyed(ServletContextEvent arg0) {
this.context = null;
print("ServletContext的释放");
}
//session活动监听
//1.监听会话的active情况
public void sessionDidActivate(HttpSessionEvent arg0) {
print("sessionDidActivate("+arg0.getSession().getId()+")");
}
//2.监听会话的passivate情况
public void sessionWillPassivate(HttpSessionEvent arg0) {
print("sessionWillPassivate("+arg0.getSession().getId()+")");
}
@SuppressWarnings("deprecation")
private void print(String message){
//调用该方法在txt文件中打印出message字符串信息
PrintWriter out = null;
try {
out = new PrintWriter(new FileOutputStream("F:session_result.txt",true));
out.println(new java.util.Date().toLocaleString()+"contextListener:"+message);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
2.4.3 对客户端请求进行监听
对客户端的请求进行监听是在Servlet2.4规范中新添加的一项新技术,使用的接口如下:
(1)ServletRequestListener接口类
(2)ServletRequestAttributeListener接口类
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import javax.servlet.ServletRequestAttributeEvent;
import javax.servlet.ServletRequestAttributeListener;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
public class RequestListener implements ServletRequestListener,ServletRequestAttributeListener{
//监听请求的初始化与否
//1.对实现客户端请求进行监听
public void requestInitialized(ServletRequestEvent arg0) {
print("request的初始化");
print(arg0.getServletRequest().getRemoteAddr()+";"+arg0.getServletRequest().getRemoteHost()+","+arg0.getServletRequest().getRemotePort());
}
//2.对销毁客户端请求进行监听
public void requestDestroyed(ServletRequestEvent arg0) {
print("request的销毁");
}
//监听请求属性
//1.对属性的添加进行监听
public void attributeAdded(ServletRequestAttributeEvent arg0) {
print("attributeAdded('"+arg0.getName()+"','"+arg0.getValue()+"')");
}
//2.对属性的删除进行监听
public void attributeRemoved(ServletRequestAttributeEvent arg0) {
print("attributeRemoved('"+arg0.getName()+"','"+arg0.getValue()+"')");
}
//3.对属性的更新进行监听
public void attributeReplaced(ServletRequestAttributeEvent arg0) {
print("attributeReplaced('"+arg0.getName()+"','"+arg0.getValue()+"')");
}
@SuppressWarnings("deprecation")
private void print(String message){
//调用该方法在txt文件中打印出message字符串信息
PrintWriter out = null;
try {
out = new PrintWriter(new FileOutputStream("F: equest_result.txt",true));
out.println(new java.util.Date().toLocaleString()+"RequestListener:"+message);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
网友评论