JavaEE(Java Enterprise Edition):Java企业版,早期叫J2EE(J2EE的版本从1.0到1.4结束);现在Java版本从JavaEE 5开始
JavaEE规范是很多Java开发技术的总称
HTTP(Hyper Text Transfer Protocol):超文本传输协议 HTTP协议是基于TCP/IP协议的 超文本:比普通文本更加强大 传输协议:客户端和服务端的通信规则(握手规则)
动态web项目创建 idea配置tomcat服务器
对象的生命周期,就是对象从出生到死亡的过程,官方的说法就是对象的创建到销毁的过程
出生:请求第一次到达Servlet时,对象就创建出来,并且初始化成功,只出生一次,将对象放到内存中
活着:服务提供服务的整个过程中,该对象一直存在,每次都是执行service方法
死亡:当服务停止时或者服务器宕机时,对象死亡
Servlet对象只会创建一次,销毁一次,所有Servlet对象只有一个实例,如果一个对象实例在应用中时唯一存在,我们可以称为单例模式
package cn.cdw.demo; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * @author DW-CHEN * Servlet生命周期 */ @WebServlet("/servletDemo4") public class Demo4 extends HttpServlet { //初始化 @Override public void init() throws ServletException { System.out.println("初始化了...."); } //服务 @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doPost(req,resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("服务过程....."); } //销毁 @Override public void destroy() { System.out.println("销毁了...."); } }由于Servlet采用的是单例模式,也就是整个应用中只有一个实例对象(Servlet是线程不安全的)
Servlet线程不安全问题展示
package cn.cdw.demo; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; /** * @author DW-CHEN * Servlet线程安全问题 * * 使用两个浏览器同时访问同一个请求,出现线程安全问题 * * 例如 * 浏览器一访问:http://localhost:8080/servletDemo5?testName=aaa * 浏览器二访问:http://localhost:8080/servletDemo5?testName=bbb * * 出现:浏览器1和浏览器2页面显示都是bbb * * */ @WebServlet("/servletDemo5") public class Demo5 extends HttpServlet { private String value;//定义接收请求值的属性 @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doPost(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { value = req.getParameter("testName");//获取请求testName属性的值 try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } PrintWriter writer = resp.getWriter(); writer.write("value:" + value);//把请求参数值响应到页面 writer.close(); } } 解决:定义类成员要谨慎,如果是共用的,并且只会在初始化时赋值,其他时间都是获取的话,那么是没问题的,如果不是共用的,或者每次使用都有可能对其赋值,那么要考虑线程安全问题了,可以将其定义到doGet或doPost方法内或者使用同步功能即可解决Servlet线程安全问题:把成员变量定义到局部变量
package cn.cdw.demo; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; /** * @author DW-CHEN * 解决Servlet线程安全问题:把成员变量定义到局部变量 */ @WebServlet("/servletDemo6") public class Demo6 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doPost(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String value = null; value = req.getParameter("testName");//获取请求testName属性的值 try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } PrintWriter writer = resp.getWriter(); writer.write("value:" + value);//把请求参数值响应到页面 writer.close(); } }使用同步代码块解决Servlet线程安全问题
package cn.cdw.demo; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; /** * @author DW-CHEN * 使用同步代码块解决Servlet线程安全问题 */ @WebServlet("/servletDemo7") public class Demo7 extends HttpServlet { private String value; private Object lock = new Object(); @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doPost(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { synchronized (lock) { value = req.getParameter("testName");//获取请求testName属性的值 } try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } PrintWriter writer = resp.getWriter(); writer.write("value:" + value);//把请求参数值响应到页面 writer.close(); } }注意:优先级问题,越是具体的优先级越高,也是模糊通用的优先级越低
通过多映射配置,在不同的访问路径在同一个方法里实现不同的功能逻辑
package cn.cdw.demo; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; /** * @author DW-CHEN * 通过多映射配置,在不同的访问路径在同一个方法里实现不同的功能逻辑 * * 例如:访问路径结尾为vip的购物优惠八折,为svip的购物优惠五折,普通不优惠 */ @WebServlet("/servletDemo8/*") public class Demo8 extends HttpServlet { private Integer money = 10000; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doPost(req,resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { StringBuffer requestURL = req.getRequestURL(); String url = requestURL.substring(requestURL.lastIndexOf("/"));//获取最后一个路径字符串 PrintWriter writer = resp.getWriter(); if ("/vip".equals(url)) { System.out.println("价钱:"+money + " 优惠后八折后为:"+(money) * 0.8); writer.write(String.valueOf((money) * 0.8)); }else if ("/svip".equals(url)) { System.out.println("价钱:"+money + " 优惠后八折后为:"+(money) * 0.5); writer.write(String.valueOf((money) * 0.5)); }else { System.out.println("价钱:" + money + " 没有优惠"); writer.write(String.valueOf((money))); } } }注解配置的方式
package cn.cdw.demo; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; /** * @author DW-CHEN * * 配置Servlet在服务器启动的时候就创建初始化 */ @WebServlet(value = "/servletDemo9",loadOnStartup = 1) public class Demo9 extends HttpServlet { @Override public void init() throws ServletException { System.out.println("Servlet初始化了..."); } }web.xml配置
ServletContext域对象设置共享数据
package cn.cdw.demo; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.annotation.WebFilter; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * @author DW-CHEN * ServletContext数据共享 */ @WebServlet("/servletDemo12") public class Demo12 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doPost(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { ServletContext servletContext = getServletContext(); servletContext.setAttribute("data", "this is data data.....");//共享数据 //servletContext.removeAttribute("data");//删除共享数据 } }获取ServletContext域对象数据
package cn.cdw.demo; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * @author DW-CHEN * ServletContext数据共享 */ @WebServlet("/servletDemo13") public class Demo13 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doPost(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { ServletContext servletContext = getServletContext(); String data = (String)servletContext.getAttribute("data");//获取共享数据 System.out.println(data); resp.getWriter().write(data); } }html测试页面
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>注册</title> <style> .div1{ width: 1200px; height: 800px; border: solid 1px red; } .div2{ width: 600px; height: 50%; margin-left: 500px; margin-top: 20px; } </style> </head> <body> <div class="div1"> <div class="div2"> <form action="/request/servletDemo19" method="get" autocomplete="off"> 姓名:<input type="text" name="name"><br/><br/> 密码:<input type="password" name="password"><br/><br/> 喜好:<input type="checkbox" name="hobby" value="play">玩游戏 <input type="checkbox" name="hobby" value="sleep">睡觉<br/><br/> <button type="submit">注册</button> </form> </div> </div> </body> </html>Java代码
package cn.cdw.demo; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; import java.util.Arrays; import java.util.Enumeration; import java.util.Map; import java.util.Set; /** * @author DW-CHEN * request获取请求参数常用方法 * 注意:这里并未处理中文乱码问题 */ @WebServlet("/servletDemo19") public class Demo19 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doPost(req,resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { PrintWriter writer = resp.getWriter(); System.out.println("======================获取请求参数属性获取请求参数数据======================="); String name = req.getParameter("name"); System.out.println(name); writer.write(name+"\r\n"); System.out.println(); System.out.println("===================根据请求属性名获取它对应的所有值====================="); String[] hobbies = req.getParameterValues("hobby"); System.out.println(Arrays.toString(hobbies)); writer.write(Arrays.toString(hobbies)+"\r\n"); System.out.println(); System.out.println("=======================获取所有请求参数数据======================================"); Enumeration<String> parameterNames = req.getParameterNames(); while (parameterNames.hasMoreElements()){ String getName = parameterNames.nextElement(); System.out.println(getName + " : " + Arrays.toString(req.getParameterValues(getName))); writer.write(getName + " : " + Arrays.toString(req.getParameterValues(getName))+"\r\n"); } System.out.println(); System.out.println("===================获取所有的请求参数数据以键值对方式======================="); Map<String, String[]> parameterMap = req.getParameterMap(); Set<String> keySet = parameterMap.keySet(); for (String key : keySet) { System.out.println(key + " :" + Arrays.toString(req.getParameterValues(key))); writer.write(key + " :" + Arrays.toString(req.getParameterValues(key))+"\r\n"); } writer.close(); } }html测试页面
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>注册</title> <style> .div1{ width: 1200px; height: 800px; border: solid 1px red; } .div2{ width: 600px; height: 50%; margin-left: 500px; margin-top: 20px; } </style> </head> <body> <div class="div1"> <div class="div2"> <form action="/request/servletDemo20" method="get" autocomplete="off"> 姓名:<input type="text" name="name"><br/><br/> 密码:<input type="password" name="password"><br/><br/> 喜好:<input type="checkbox" name="hobby" value="play">玩游戏 <input type="checkbox" name="hobby" value="sleep">睡觉<br/><br/> <button type="submit">注册</button> </form> </div> </div> </body> </html>Servlet
package cn.cdw.demo; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; import java.util.Arrays; /** * @author DW-CHEN * 手动将获取的请求数据封装到对象中 */ @WebServlet("/servletDemo20") public class Demo20 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doPost(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { PrintWriter writer = resp.getWriter(); String name = req.getParameter("name"); String password = req.getParameter("password"); String[] hobbies = req.getParameterValues("hobby"); Student student = new Student(name, password, hobbies);//封装到学生对象中 System.out.println(student); writer.write(String.valueOf(student)); writer.close(); } } //学生对象 class Student{ private String name; private String password; private String[] hobby; public Student() { } public Student(String name, String password, String[] hobby) { this.name = name; this.password = password; this.hobby = hobby; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String[] getHobby() { return hobby; } public void setHobby(String[] hobby) { this.hobby = hobby; } @Override public String toString() { return "Student{" + "name='" + name + '\'' + ", password='" + password + '\'' + ", hobby=" + Arrays.toString(hobby) + '}'; } }html测试页面
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>注册</title> <style> .div1{ width: 1200px; height: 800px; border: solid 1px red; } .div2{ width: 600px; height: 50%; margin-left: 500px; margin-top: 20px; } </style> </head> <body> <div class="div1"> <div class="div2"> <form action="/request/servletDemo21" method="get" autocomplete="off"> 姓名:<input type="text" name="name"><br/><br/> 密码:<input type="password" name="password"><br/><br/> 喜好:<input type="checkbox" name="hobby" value="play">玩游戏 <input type="checkbox" name="hobby" value="sleep">睡觉<br/><br/> <button type="submit">注册</button> </form> </div> </div> </body> </html>Servlet
package cn.cdw.demo; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.beans.IntrospectionException; import java.beans.PropertyDescriptor; import java.io.IOException; import java.io.PrintWriter; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Arrays; import java.util.Map; import java.util.Set; /** * @author DW-CHEN * 通过反射的方式将获取到的请求数据封装到对象中 */ @WebServlet("/servletDemo21") public class Demo21 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doPost(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { PrintWriter writer = resp.getWriter(); Student1 student = new Student1(); Map<String, String[]> parameterMap = req.getParameterMap();//获取到所有的请求参数值,以键值对的方式 Set<String> keySet = parameterMap.keySet(); for (String name : keySet) { String[] parameterValues = req.getParameterValues(name);//根据键获取对应的所有值 try { PropertyDescriptor propertyDescriptor = new PropertyDescriptor(name, student.getClass());//获取学生对象的属性描述器 Method writeMethod = propertyDescriptor.getWriteMethod();//通过属性描述器获取学生对象对应的setXXX方法 if (parameterValues.length > 1) {//判断根据键获取到的值是否时多个,如果是,则将它强转一下 writeMethod.invoke(student, (Object)parameterValues); }else { writeMethod.invoke(student, parameterValues); } } catch (IntrospectionException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } System.out.println(student); writer.write(student.toString()); writer.close(); } } //学生对象 class Student1{ private String name; private String password; private String[] hobby; public Student1() { } public Student1(String name, String password, String[] hobby) { this.name = name; this.password = password; this.hobby = hobby; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String[] getHobby() { return hobby; } public void setHobby(String[] hobby) { this.hobby = hobby; } @Override public String toString() { return "Student{" + "name='" + name + '\'' + ", password='" + password + '\'' + ", hobby=" + Arrays.toString(hobby) + '}'; } }使用工具类需要到入commons-beanutils-1.9.2.jar/commons-logging-1.1.1.jar包,下载地址:https://download.csdn.net/download/qq_42795277/12805872
html测试页面
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>注册</title> <style> .div1{ width: 1200px; height: 800px; border: solid 1px red; } .div2{ width: 600px; height: 50%; margin-left: 500px; margin-top: 20px; } </style> </head> <body> <div class="div1"> <div class="div2"> <form action="/request/servletDemo22" method="get" autocomplete="off"> 姓名:<input type="text" name="name"><br/><br/> 密码:<input type="password" name="password"><br/><br/> 喜好:<input type="checkbox" name="hobby" value="play">玩游戏 <input type="checkbox" name="hobby" value="sleep">睡觉<br/><br/> <button type="submit">注册</button> </form> </div> </div> </body> </html>学生类
package cn.cdw.demo; import java.util.Arrays; public class Student2{ private String name; private String password; private String[] hobby; public Student2() { } public Student2(String name, String password, String[] hobby) { this.name = name; this.password = password; this.hobby = hobby; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String[] getHobby() { return hobby; } public void setHobby(String[] hobby) { this.hobby = hobby; } @Override public String toString() { return "Student{" + "name='" + name + '\'' + ", password='" + password + '\'' + ", hobby=" + Arrays.toString(hobby) + '}'; } }Servlet
package cn.cdw.demo; import org.apache.commons.beanutils.BeanUtils; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.util.Arrays; import java.util.Map; /** * @author DW-CHEN * 通过工具类将请求数据封装到对象中 * 注意:需要在web目录下导入commons-beanutils-1.9.2.jar/commons-logging-1.1.1.jar包 */ @WebServlet("/servletDemo22") public class Demo22 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doPost(req,resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Student2 student = new Student2(); Map<String, String[]> parameterMap = req.getParameterMap(); try { BeanUtils.populate(student,parameterMap); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } System.out.println(student); resp.getWriter().write(student.toString()); } }html测试页面
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>注册</title> <style> .div1{ width: 1200px; height: 800px; border: solid 1px red; } .div2{ width: 600px; height: 50%; margin-left: 500px; margin-top: 20px; } </style> </head> <body> <div class="div1"> <div class="div2"> <form action="/request/servletDemo23" method="get" autocomplete="off"> 姓名:<input type="text" name="name"><br/><br/> 密码:<input type="password" name="password"><br/><br/> 喜好:<input type="checkbox" name="hobby" value="play">玩游戏 <input type="checkbox" name="hobby" value="sleep">睡觉<br/><br/> <button type="submit">注册</button> </form> </div> </div> </body> </html>通过字符对象获取请求数据,注意:请求方式必须为post方式
package cn.cdw.demo; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.BufferedReader; import java.io.IOException; /** * @author DW-CHEN * 通过流对象获取请求数据 * * 通过字符对象获取请求数据,注意:请求方式必须为post方式 */ @WebServlet("/servletDemo23") public class Demo23 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doPost(req,resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { BufferedReader bufferedReader = req.getReader(); String data; while ((data = bufferedReader.readLine()) != null) { System.out.println(data); resp.getWriter().write(data); } } }通过字节流对象获取请求数据,注意:请求方式必须为post方式
package cn.cdw.demo; import javax.servlet.ServletException; import javax.servlet.ServletInputStream; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * @author DW-CHEN * 通过流对象获取请求数据 * * 通过字节流对象获取请求数据,注意:请求方式必须为post方式 */ @WebServlet("/servletDemo24") public class Demo24 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doPost(req,resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { ServletInputStream inputStream = req.getInputStream(); byte[] bytes = new byte[1024]; int len; while ((len = inputStream.read(bytes)) != -1){ System.out.println(new String(bytes,0,len)); resp.getWriter().write(new String(bytes,0,len)); } } }就是客户端的一次请求到达后,发现需要借助其他的Servlet来实现功能
特点:
浏览器地址栏不变域对象中的数据不会丢失负责转发的Servlet转发前后的响应正文会丢失由转发的目的地来响应客户端 方法名说明RequestDispatcher getRequestDispatcher(String name)获取请求调度对象void forward(ServletRequest req,ServletResponse resq)实现转发 package cn.cdw.demo; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * @author DW-CHEN * * 请求域/请求转发 */ @WebServlet("/servletDemo26") public class Demo26 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doPost(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setAttribute("data","我是request域的共享数据"); RequestDispatcher requestDispatcher = req.getRequestDispatcher("/servletDemo27");//设置转发到 /request/servletDemo27 requestDispatcher.forward(req, resp); } } package cn.cdw.demo; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * @author DW-CHEN * * 请求转发到这个类进行处理 */ @WebServlet("/servletDemo27") public class Demo27 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doPost(req,resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Object data = req.getAttribute("data");//根据名称获取request域的共享数据 System.out.println("Demo27类方法执行了,收到的request域的共享数据为:"+data); resp.getWriter().write("TEST SUCCESS....."); } }response 字节流方式响应消息
package cn.cdw.demo; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * @author DW-CHEN * * 乱码问题 * * response 字节流方式响应消息 */ @WebServlet("/servletDemo30") public class Demo30 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doPost(req,resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/html;charset=UTF-8");//统一设置编码 String str = "我是响应消息"; ServletOutputStream outputStream = resp.getOutputStream(); outputStream.write(str.getBytes("UTF-8")); } }response 字符流方式响应消息
package cn.cdw.demo; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; /** * @author DW-CHEN * * 乱码问题 * * response 字符流方式响应消息 */ @WebServlet("/servletDemo31") public class Demo31 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doPost(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/html;charset=UTF-8"); String str = "我是字符流方式的响应消息"; PrintWriter writer = resp.getWriter(); writer.write(str); } }response字节流方式响应图片
package cn.cdw.demo; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.BufferedInputStream; import java.io.FileInputStream; import java.io.IOException; /** * @author DW-CHEN * * response字节流方式响应图片 */ @WebServlet("/servletDemo32") public class Demo32 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doPost(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { ServletContext servletContext = req.getServletContext(); String realPath = servletContext.getRealPath("/img/1.jpg");//需要根据ServletContext对象获取到资源的绝对路径,不然读取不到资源 BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(realPath));//读取资源文件 ServletOutputStream outputStream = resp.getOutputStream();//获取响应字节流 byte[] bytes = new byte[1024]; int len; while ((len = bufferedInputStream.read(bytes)) != -1) { outputStream.write(bytes, 0, len); } bufferedInputStream.close(); } }就是客户端的一次请求到达后,发现需要借助其它的Servlet来实现功能
特点:
浏览器地址栏会发生改变两次请求请求域对象中不能共享数据可以重定向到其它服务器response 响应对象下载文件
package cn.cdw.demo; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.BufferedInputStream; import java.io.FileInputStream; import java.io.IOException; /** * @author DW-CHEN * response 响应对象下载文件 */ @WebServlet("/servletDemo37") public class Demo37 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doPost(req,resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/html;charset=UTF-8"); ServletContext servletContext = req.getServletContext(); String realPath = servletContext.getRealPath("/img/1.jpg"); BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(realPath)); resp.setHeader("Content-Type","application/octet-stream");//设置支持类型响应头参数,Content-Type:表示支持类型;application/octet-stream:表示应用的类型为字节流 resp.setHeader("Content-Disposition","attachment;filename=1.jpg");//设置下载处理响应头参数,Content-Disposition:表示处理的形式;attachment:表示以附件的形式下载;filename:表示指定下载文件的名称(可以自定义命名) ServletOutputStream outputStream = resp.getOutputStream(); byte[] bytes = new byte[1024]; int len; while ((len = bufferedInputStream.read(bytes)) != -1) { outputStream.write(bytes, 0, len); } bufferedInputStream.close(); } }通过cookie记录最后访问时间
package cn.cdw.demo; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; import java.text.SimpleDateFormat; import java.util.Date; /** * @author DW-CHEN * 通过cookie记录最后访问时间 */ @WebServlet("/servletDemo40") public class Demo40 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doPost(req,resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/html;charset=UTF-8"); PrintWriter writer = resp.getWriter(); Cookie cookie = new Cookie("time", System.currentTimeMillis()+"");//创建一个Cookie记录最后访问时间 cookie.setMaxAge(3600);//设置cookie最大存活时间(单位为秒) resp.addCookie(cookie);//添加cookie到客户端 Cookie[] cookies = req.getCookies();//获取所有客户端cookie for (Cookie cookie1 : cookies) { if ("time".equals(cookie1.getName())) {//根据名称找到记录最后访问时间的cookie String value = cookie1.getValue();//获取到记录最后访问时间的值 SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");//进行一下时间格式化 String lastTime = simpleDateFormat.format(new Date(Long.parseLong(value)));//时间格式化最后访问时间格式 writer.write("最后访问时间为:"+lastTime); } } } }HttpSession:服务端会话管理技术(本质也是采用客户端会话管理技术) 作用:可以实现数据共享
浏览器禁用Cookie
方式一:通过提示信息告知用户 package cn.cdw.demo; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; import java.io.PrintWriter; /** * @author DW-CHEN * 处理浏览器cookie功能关闭后影响session对象问题 * * 方式一:提示用户打开cookie功能 */ @WebServlet("/servletDemo43") public class Demo43 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doPost(req,resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/html;charset=UTF-8"); PrintWriter writer = resp.getWriter(); HttpSession session = req.getSession(false);//当没有session域时不自动创建session对象 if (session == null) { writer.write("为了不影响您的使用,请把浏览器的cookie功能打开"); } writer.write("正常使用...."); } } 方式二:访问时拼接jsessionid标识,通过encodeURL()方法重写地址 package cn.cdw.demo; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; import java.io.PrintWriter; /** * @author DW-CHEN * 处理浏览器cookie功能关闭后影响session对象问题 * * 方式二:实现url重写,在请求路径后拼接上(;jssionid=session的唯一标识id) 不建议使用 */ @WebServlet("/servletDemo44") public class Demo44 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doPost(req,resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/html;charset=UTF-8"); PrintWriter writer = resp.getWriter(); HttpSession session = req.getSession(); writer.write(session.toString()+"<br/>"); writer.write(session.getId()+"<br/>"); writer.write("<a href='"+resp.encodeURL("http://localhost:8080/session/servletDemo43")+"'>点击我<a/>"); } }钝化和活化:
钝化:序列化,把长时间不用,但还不到过期时间的HttpSession进行序列化写到磁盘上活化:相反的状态什么时候钝化
第一种情况:当访问量很大时,服务器会根据getLastAccessTie来进行排序,对长时间不用但还没有过期时间的HttpSession进行序列化第二种情况:当服务器进行重启的时候,为了保持客户HttpSession中的数据,也要对其进行序列化注意:HttpSession的序列化是由服务器自动完成的
JSP(Java Server Pages):是一种动态网页技术标准
JSP是基于Java语言的,它的本质就是Servlet生成的Java文件目录:C:\Users\Administrator.IntelliJIdea2019.2\system\tomcat\Tomcat_8_5_31_webDemo\work\Catalina\localhost\request\org\apache自定义类
package cn.cdw.demo; public class Student3{ private String name; private Integer age; private String address; public Student3() { } public Student3(String name, Integer age, String address) { this.name = name; this.age = age; this.address = address; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } } <%@ page import="cn.cdw.demo.Student3" %> <%@ page import="java.util.ArrayList" %> <%@ page import="java.util.Map" %> <%@ page import="java.util.HashMap" %> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>EL 获取不同的数据</title> </head> <body> ===================获取基本数据类型============================<br/> <% String s = "你好 el...."; pageContext.setAttribute("str", s); %> ${str}<br/><br/> ===================获取自定义对象类型============================<br/> <% Student3 student = new Student3("小明", 12, "深圳"); pageContext.setAttribute("student", student); %> 学生对象:${student}<br/> 学生姓名:${student.name}<br/> 学生年龄:${student.age}<br/> 学生地址:${student.address}<br/><br/> ===================获取数组类型============================<br/> <% int[] arr = {12, 22}; pageContext.setAttribute("arr", arr); %> 数组对象:${arr}<br/> 数组的第一个元素:${arr[0]}<br/> 数组的第二个元素:${arr[1]}<br/><br/> ===================获取list集合数据类型============================<br/> <% ArrayList<Student3> arrayList = new ArrayList<>(); arrayList.add(new Student3("小李", 21, "深圳")); arrayList.add(new Student3("小红", 22, "北京")); arrayList.add(new Student3("小明", 43, "上海")); pageContext.setAttribute("arrayList", arrayList); %> 集合对象:${arrayList}<br/> 集合中的第一个学生对象:${arrayList[0]}<br/> 集合中的第一个学生对象的姓名:${arrayList[0].name}<br/> 集合中的第二个学生对象的地址:${arrayList[1].address}<br/><br/> ===================获取map集合数据类型============================<br/> <% Map<String, Student3> map = new HashMap<>(); map.put("stu1", new Student3("小明", 12, "深圳")); map.put("stu2", new Student3("小李", 22, "北京")); pageContext.setAttribute("map", map); %> map集合:${map}<br/> map集合中Kye为stu2的学生对象:${map.stu2}<br/> map集合中Kye为stu2的学生对象的姓名:${map.stu2.name}<br/> map集合中Kye为stu2的学生对象的年龄:${map.stu2.age}<br/> map集合中Kye为stu2的学生对象的地址:${map.stu2.address}<br/> </body> </html>使用JSTL需要下载的jstl-1.2.jar包,下载地址:https://download.csdn.net/download/qq_42795277/12804268
标签库名称说明<标签名:if>流程控制,用于条件判断<标签名:choose> ,<标签名:when>,<标签名:otherwise>流程控制,用于多条件判断<标签名:forEach>迭代遍历,用于循环遍历 <%@ page import="java.util.ArrayList" %> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <html> <head> <title>jstl使用</title> </head> <body> =======================jstl的使用,需要在web下的WEB-INF添加jstl-1.2.jar包===============================================================<br/> <% String str = "A"; pageContext.setAttribute("data", str); %> =======================if判断语句===============================================================<br/> <c:if test="${'A'.equals(data)}"> 你的成绩优秀.... </c:if><br/><br/> =======================多条件判断语句===============================================================<br/> <c:choose> <c:when test="${'A' eq data}">你的成绩优秀....</c:when> <c:when test="${'B' eq data}">你的成绩很好....<</c:when> <c:when test="${'C' eq data}">你的成绩一般....</c:when> <c:when test="${'D' eq data}">继续努力....</c:when> <c:otherwise>数据错误..</c:otherwise> </c:choose><br/><br/> =======================遍历集合===============================================================<br/> <% ArrayList<Integer> arrayList = new ArrayList<>(); arrayList.add(12); arrayList.add(22); arrayList.add(33); pageContext.setAttribute("arrayList", arrayList); %> <c:forEach items="${arrayList}" var="num"> ${num}<br/> </c:forEach> </body> </html>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"> <welcome-file-list> <welcome-file>/demo/index.jsp</welcome-file> </welcome-file-list> <!--配置过滤器Demo48--> <filter> <filter-name>filterNameDemo48</filter-name> <filter-class>cn.cdw.demo.Demo48</filter-class> </filter> <filter-mapping> <filter-name>filterNameDemo48</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>注解的方式,使用过滤器统一处理编码问题
package cn.cdw.demo; import javax.servlet.*; import javax.servlet.annotation.WebFilter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * @author DW-CHEN * 通过Filter过滤器解决多个资源写出中文乱码问题 */ @WebFilter("/*") //设置过滤拦截所有请求 public class Demo48 implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { try { HttpServletRequest req = (HttpServletRequest)servletRequest; HttpServletResponse resp = (HttpServletResponse)servletResponse; req.setCharacterEncoding("UTF-8"); resp.setContentType("text/html;charset=UTF-8"); filterChain.doFilter(req, resp);//处理完成后放行 } catch (Exception e) { e.printStackTrace(); } } @Override public void destroy() { } }FilterConfig是一个接口,代表过滤器的配置对象,可以加载一些初始化参数
方法名说明String getFilterName()获取过滤器对象名称String getInitParameter(String key)根据key获取valueEnueration<String> getInitParameterNames()获取所有的参数的keyServletContextgetServletContext()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"> <welcome-file-list> <welcome-file>/demo/index.jsp</welcome-file> </welcome-file-list> <!--配置过滤器Demo51--> <filter> <filter-name>filterNameDemo51</filter-name> <filter-class>cn.cdw.demo.Demo51</filter-class> <!--配置初始化值--> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> <init-param> <param-name>name</param-name> <param-value>aaa</param-value> </init-param> </filter> <filter-mapping> <filter-name>filterNameDemo51</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app> package cn.cdw.demo; import javax.servlet.*; import java.io.IOException; import java.util.Enumeration; /** * @author DW-CHEN * FilterConfig */ public class Demo51 implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { System.out.println("======================获取过滤器名称========================"); String filterName = filterConfig.getFilterName(); System.out.println(filterName); System.out.println("\r\n"); System.out.println("\r\n"); System.out.println("=========================根据名称获取过滤器中的初始化值(web.xml中配置的过滤初始化值)==================================="); String encoding = filterConfig.getInitParameter("encoding"); System.out.println(encoding); System.out.println("\r\n"); System.out.println("\r\n"); System.out.println("=========================获取过滤器中的所有初始化值(web.xml中配置的过滤初始化值)==================================="); Enumeration<String> initParameterNames = filterConfig.getInitParameterNames(); while (initParameterNames.hasMoreElements()) { String name = initParameterNames.nextElement(); System.out.println(name + " : " + filterConfig.getInitParameter(name)); } System.out.println("\r\n"); System.out.println("\r\n"); System.out.println("=========================获取上下文对象,然后可以调用上下文对象相关方法使用==================================="); ServletContext servletContext = filterConfig.getServletContext(); String contextPath = servletContext.getContextPath(); System.out.println(contextPath); } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { } @Override public void destroy() { } }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"> <welcome-file-list> <welcome-file>/demo/index.jsp</welcome-file> </welcome-file-list> <!-- 配置过滤器Demo53--> <filter> <filter-name>filterNameDemo53</filter-name> <filter-class>cn.cdw.demo.Demo53</filter-class> <async-supported>true</async-supported><!--配置开启异步支持,当dispatcher为ASYNC时需要进行配置开启异步支持--> </filter> <filter-mapping> <filter-name>filterNameDemo53</filter-name> <url-pattern>/index.jsp</url-pattern> <dispatcher>REQUEST</dispatcher><!--过滤请求,默认值--> <dispatcher>ERROR</dispatcher><!--过滤全局错误页面:当由服务器调用全局错误页面时进行过滤工作--> <dispatcher>FORWARD</dispatcher><!--过滤请求转发,当请求转发时,过滤器工作--> <dispatcher>INCLUDE</dispatcher><!--过滤请求包含,当请求包含时,过滤器工作;它只能过滤动态包含,jsp的include指令是静态包含--> <dispatcher>ASYNC</dispatcher><!--过滤异步类型,它需要我们在filter标签中配置开启异步支持--> </filter-mapping> <!--配置错误全局页面--> <error-page> <exception-type>java.lang.Exception</exception-type> <location>/err/err.jsp</location> </error-page> <error-page> <error-code>404</error-code> <location>/err/err.jsp</location> </error-page> </web-app>Servlet,看如果修改拦截配置,测试访问servlet看过滤器是否执行
package cn.cdw.demo; import javax.servlet.*; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * @author DW-CHEN * servlet * 过滤器的五种拦截行为 */ @WebServlet("/servletDemo52") public class Demo52 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doPost(req,resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // int i = 1 / 0; //测试出现异常,是否执行过滤器,注意测试时修改一下拦截对应的路径 System.out.println("Demo52servlet执行了...."); //req.getRequestDispatcher("/index.jsp").forward(req, resp);//测试进行转发时,是否执行过滤器,注意测试时修改一下拦截对应的路径 req.getRequestDispatcher("/index.jsp").include(req, resp);//测试进行包含时,是否执行过滤器,注意测试时修改一下拦截对应的路径 } }过滤器
package cn.cdw.demo; import javax.servlet.*; import java.io.IOException; /** * @author DW-CHEN * 过滤器的五种拦截行为 */ public class Demo53 implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { System.out.println("过滤器Demo53执行了......."); filterChain.doFilter(servletRequest, servletResponse); } @Override public void destroy() { } }监听对象的
ServletContextListenerHttpSessionListenerServletRequestListener监听属性变化的
ServletContextAttributeListenerHttpSessionAttributeListenerServletRequestAttributeListener监听会话相关感知型
HttpSessionBindingListenerHttpSessionActivationListener参数:ServletContextEvent 代表事件对象,事件对象中封装了事件源,也就是ServletContext,真正的事件指的是创建或销毁ServletContext对象的操作
参数:HttpSessionEvent 代表事件对象,事件对象中封装了事件源,也就是HttpSession,真正的事件指的时创建或销毁HttpSession对象的操作
ServletRequestListener:用于监听ServletRequest对象的创建和销毁
方法名说明void requestInitialized(ServletRequestEvent sre)对象创建的时候执行该方法void requestDestroyed(ServletRequestEvent sre)对象销毁时执行该方法参数:ServletRequestEvent 代表事件对象,事件对象中封装了事件源,也就是ServletRequest,真正的事件指的时创建或销毁ServletRequest对象的操作
测试Servlet
package cn.cdw.demo; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * @author DW-CHEN * 测试应用域对象属性发生改变,监听器是否执行 */ @WebServlet("/servletDemo56") public class Demo56 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doPost(req,resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { ServletContext servletContext = req.getServletContext(); servletContext.setAttribute("name", "添加了数据"); servletContext.setAttribute("name", "修改了数据"); servletContext.removeAttribute("name");//删除了数据 } }参数:ServletContextAttributeEvent 代表事件对象,事件对象中封装了事件源,也就是ServletContex,真正的事件指的是添加,移除,替换应用域中的属性操作
参数:HttpSessionBindingEvent 代表事件对象,事件对象中封装了事件源,也就是HttpSession,真正的事件指的是添加,移除,替换会话域中的属性操作
参数:ServletRequestAttributeEvent 代表事件对象,事件对象中封装了事件源,也就是ServletRequest,真正的事件指的是添加,移除,替换请求域中的属性操作
参数:HttpSessionBindingEvent 代表事件对象,事件对象中封装了事件源,也是是HttpSession,真正的事件指的是添加,移除会话域中的数据操作
HttpSessionActivationListener:用于感知会话域中对象钝化和活化的监听器 方法名说明void sessionWillPassivate(HttpSessionEven se)会话数据钝化时执行该方法void sessionDidActivate(HttpSessionEvent se)会话域中数据活化时执行该方法参数:HttpSessionEvent代表事件对象,事件对象中封装了事件源,也就是HttpSession,正在的事件指的是会话域中数据钝化,活化操作