1.监听:
index.jsp:
<%@ 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>
</head>
<body>
<%
session.setAttribute("username", "zhangsan");// attributeAdded
session.setAttribute("pwd", "123456");// attributeAdded
session.setAttribute("username", "lisi");// attributeReplaced
session.removeAttribute("username");// attributeRemoved
%>
<h1>监听器</h1>
<pre>
在web项目中,监听器也是监听比较重要的事件或者对象
监听作用域
1.监听作用域的生命周期
2.监听作用域的值传递
**当监听器开始监听的时候,绝对是监听已经被创建后
监听的原则:
**作用一定要单一
三个作用域两个监听:每一个作用域都会有两个监听,一共有三个作用域,就会有六个监听
request:请求和所有请求转发的跳转的页面
ServletRequestListener:sre.getServletRequest();
ServletContextAttributeListener:
srae.getName();
srae.getValue();
srae.getServletRequest();
session:一次会话
HttpSessionListener:se.getSession();
HttpSessionAttributeListener:
event.getName();
event.getValue();
event.getSession();
application:作用于整个项目
ServletContextListener:sce.getServletContext()
ServletContextAttributeListener:
event.getName();
event.getValue();
event.getServletContext();
pageContext:虽然是作用域,但是作用范围很小,只作用于当前页面,所有两个servlet之间的值传递会失效,没有必要监听
四大作用域中,唯一一个没有监听的作用域
</pre>
</body>
</html>
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>20170807_listener</display-name>
<listener>
<listener-class>cn.zzsxt.lee.web.listener.HelloListener</listener-class>
</listener>
<listener>
<listener-class>cn.zzsxt.lee.web.listener.HiListener</listener-class>
</listener>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
HelloListener:
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class HelloListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent sce) {
// 系统默认加载的数据
System.out.println("我是初始化方法,我被调用了");
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
System.out.println("我是销毁方法,我被调用了");
}
}
HiListener:
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
public class HiListener implements HttpSessionAttributeListener {
@Override
public void attributeAdded(HttpSessionBindingEvent event) {
System.out.println("添加会被调用");
}
@Override
public void attributeRemoved(HttpSessionBindingEvent event) {
System.out.println("移除时会被调用");
}
@Override
public void attributeReplaced(HttpSessionBindingEvent event) {
System.out.println("替换时会被调用");
}
}
ManyListener:
import javax.servlet.ServletContextAttributeEvent;
import javax.servlet.ServletContextAttributeListener;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.ServletRequestAttributeEvent;
import javax.servlet.ServletRequestAttributeListener;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
public class ManyListener implements ServletContextListener, ServletContextAttributeListener, HttpSessionListener, HttpSessionAttributeListener, ServletRequestListener, ServletRequestAttributeListener {
@Override
public void attributeAdded(ServletRequestAttributeEvent srae) {
srae.getServletRequest().getAttribute("username");
// TODO Auto-generated method stub
}
@Override
public void attributeRemoved(ServletRequestAttributeEvent srae) {
// TODO Auto-generated method stub
}
@Override
public void attributeReplaced(ServletRequestAttributeEvent srae) {
}
@Override
public void requestDestroyed(ServletRequestEvent sre) {
// TODO Auto-generated method stub
}
@Override
public void requestInitialized(ServletRequestEvent sre) {
// TODO Auto-generated method stub
}
@Override
public void attributeAdded(HttpSessionBindingEvent event) {
// TODO Auto-generated method stub
}
@Override
public void attributeRemoved(HttpSessionBindingEvent event) {
// TODO Auto-generated method stub
}
@Override
public void attributeReplaced(HttpSessionBindingEvent event) {
// TODO Auto-generated method stub
}
@Override
public void sessionCreated(HttpSessionEvent se) {
// TODO Auto-generated method stub
}
@Override
public void sessionDestroyed(HttpSessionEvent se) {
// TODO Auto-generated method stub
}
@Override
public void attributeAdded(ServletContextAttributeEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void attributeRemoved(ServletContextAttributeEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void attributeReplaced(ServletContextAttributeEvent event) {
// TODO Auto-generated method stub
}
@Override
public void contextDestroyed(ServletContextEvent event) {
// TODO Auto-generated method stub
}
@Override
public void contextInitialized(ServletContextEvent event) {
// TODO Auto-generated method stub
}
}
2.上传:
jar:
index.jsp:
<%@ 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>
</head>
<body>
<form action="upload.sxt" enctype="multipart/form-data" method="post">
上传头像:
<input type="file" name="headPhoto" />
用户名:<input type="text" name="username" />
<input type="submit" value="提交" />
</form>
<!--
上传必须遵循以下规则:
文件的上传需要在form表单添加enctype属性,值必须为multipart/form-data
请求方式一定要是post,不能使用get
enctype="multipart/form-data" method="post"
会把需要上传的文件转换为字节流
所以在servlet中无法使用request.getParameter()获取
在上传成功后,文件头部会出现:
------WebKitFormBoundaryG5qMELzS6gD7bSK6
Content-Disposition: form-data; name="headPhoto"; filename="meinv.jpg"
Content-Type: image/jpeg
上传流程:
1.首先把需要上传的图片转换为字节流enctype="multipart/form-data" method="post"
2.在servlet接收:request.getInputStream();字节流
3.客户端向服务器端上传相对于服务器来说是输入流
4.服务器要把字节流转换为文件格式
5.关闭资源(为空判定)
-->
</body>
</html>
UploadServlet:
package cn.zzsxt.lee.web.servlet;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;
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 org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
@WebServlet("/upload.sxt")
public class UploadServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// File.separator:/
// 在windows中E:\\,但是在mac中/Desctop/,在linux中也是
// 获取项目全局作用域:application
ServletContext context = this.getServletContext();// ServletContext就是application
// context.getRealPath:zzsxt/
// tempDirectory:zzsxt/temp
// fileDirectory:zzsxt/upload
// 满64K写入的路径
String tempDirectory = context.getRealPath(File.separator + "temp");
// 最终上传到服务器上的路径
String fileDirectory = context.getRealPath(File.separator + "picture");
try {
// 写满该大小的缓存后,存入硬盘中。
int sizeThreshold = 1024 * 64;// 设置每几K写入一次
// 创建临时文件夹目录
File repositoryFile = new File(tempDirectory);// 创建临时文件夹
// 首先创建一个文件工厂:每64k就往临时文件夹写入一次数据
FileItemFactory factory = new DiskFileItemFactory(sizeThreshold, repositoryFile);
// jar给创建好了一个servlet来处理上传功能-->需要传入一个参数:factory
ServletFileUpload upload = new ServletFileUpload(factory);
// 设置上传文件的大小限制
upload.setSizeMax(500 * 1024 * 1024);// 文件最大上传大小,文件最大上传500M,多于500M就报错给你看
// 开始解析请求数据,将输入写到临时文件夹(一个表单域就是list的一个对象)
List items = upload.parseRequest(request);//request也就是相当于request.getInputStream();
// 开始遍历获取数据
Iterator iter = items.iterator();// 遍历list集合(客户端上传的字节流)
while (iter.hasNext()) {
// 获取一个表单域资源
FileItem item = (FileItem) iter.next(); // FileItem就是表示一个表单域:所谓表单域就是<form></form>标签面的东西
// 判断当前资源是否是一个文件(isFormField方法用于判断FileItem是否代表一个普通表单域(即非file表单域))
if (item.isFormField()) {// 判断客户端传过来的数据是否为一个普通表单域(所谓普通表单域就是非file的表单域text password select radio checkbox...)
// 返回表单域的名字
System.out.println("普通表单域的名字---------------" + item.getFieldName());
// 返回表单域的值
System.out.println("普通表单域的值----------------" + item.getString("utf-8"));
// 比如说要通过username进行查询
request.getParameter("username");
// 从数据库查询数据
// 调用service-->dao-->sql-->最终从数据库查询出值
} else {
// 就是file类型
// 获取表单域name属性的值
String fieldName = item.getFieldName();// headPhoto
System.out.println(fieldName);
// 返回该文件在客户机上的文件名。e.g: e:\dianying\\video\1.wmv
String fileName = item.getName();// 才是文件名(包含了服务器的路径)
// 获取文件的类型
String fileType = fileName.substring(fileName.lastIndexOf("."));// 从获取的文件名中截取出该文件的类型.txt;.jpg;.java.zip...
// System.out.println("文件域的名字--*****" + fieldName);
// System.out.println("上传文件的名字*****" + fileName);
// System.out.println("上传文件的类型*****" + fileType);
// 创建一个真实的文件目录
// 只有这才是真正上传,前面其他的东西都是为了这一步做铺垫
// zzsxt/upload/201707084132141321321fjdhfjdsh4718467363217.jpg
File uploadedFile = new File(fileDirectory + File.separator + new Date().getTime()
+ UUID.randomUUID().toString() + fileType);
// 将临时文件写入到真实文件夹里面去
item.write(uploadedFile);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void ioUpload(HttpServletRequest request, HttpServletResponse response) throws Exception {
// 上传和下载功能,一般情况下使用IO流
InputStream ip = request.getInputStream();
// System.out.println(ip.available());// 接收到数量
OutputStream os = new FileOutputStream("E:\\java_tools\\meinv" + UUID.randomUUID().toString() + ".jpg");
byte[] bytes = new byte[1024 * 8];// 每8k写入一次
int len = 0;
while ((len = ip.read(bytes)) != -1) {
os.write(bytes, 0, len);
}
os.flush();
if (os != null) {
os.close();
}
if (ip != null) {
ip.close();
}
// 要把上传记录保存在数据库中
// insert into语句
// 首先要保存路径
// 然后需要保存客户上传的文件名
// 最后还需要保存文件在服务器上的名字
}
}
3.下载:
.txt:
几年前,他无助时,她救了他,他那时候觉得他对她有一点好感,却不知道,自己已经已经陷入爱情的深渊,那个散发着纯净气息的无辜眼神,令他沦陷。几年后,她在闺蜜榕衫介绍的工作下,无意中当上了他的女仆,他发现了,她就是几年前的她……她娇弱的靠在他怀里,他的心,乱了。
index.jsp:
<%@ 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>
</head>
<body>
<a href="dowload.sxt?fileName=bdzcasw.txt">霸道总裁爱上我-简介</a>
</body>
</html>
DownloadServlet:
package cn.zzsxt.lee.web.servlet;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/dowload.sxt")
public class DownloadServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
// 获取需要下载的文件名
String fileName = request.getParameter("fileName");
// zzsxt/upload/需要下载的文件名
InputStream ip = new FileInputStream(
this.getServletContext().getRealPath(File.separator + "upload" + File.separator + fileName));
// 清空response
response.reset();
// 文件名中有可能存在中文-->中文乱码
// 把中文的文件名转换为字节数组
// UTF-8就是为了统一编码集
// ISO-8859-1:就是为了能发送字节流,默认情况下UTF-8是不能发送字节流
/*fileName.getBytes("UTF-8");
String str = new String(fileName.getBytes("UTF-8"), "IOS-8859-1");*/
response.addHeader("Content-Disposition",
"attachment;filename=" + new String(fileName.getBytes("utf-8"), "ISO-8859-1"));
response.addHeader("Content-Length", "" + ip.available());
// 服务器把客户端需要下载文件写出(转换成流的方式写出)
OutputStream op = response.getOutputStream();
byte[] bytes = new byte[1024 * 8];
int len = 0;
while ((len = ip.read(bytes)) != -1) {
op.write(bytes, 0, len);
}
op.flush();
if (op != null) {
op.close();
}
if (ip != null) {
ip.close();
}
}
}