回顾:
过滤器:
1.过滤器概念
过滤器是servlet技术,也叫Filter
可以对
请求进行拦截
处理共用操作,例如:编码,登录验证
处理完后,放行;
控制权到servelt/jsp(如果有一个过滤器,就逐个执行)
servlet/jsp相应完成,控制器又回到过滤器;
最后过滤器执行完,服务器响应用户!
le->filter1->filter2->servlet/jsp->filter2->filter1
2.过滤器API
|--interface Filter 过滤器接口
init(FilterConfig config);
doFilter(ServletRequest request,ServletResponse response,FilterChain chain);
destroy();
|--FilterConfig 通过这个对象,可以获取过滤器在web.xml中配置信息!
|--FilterChain 过滤器链对象,代表这个项目中过滤器的执行状态!
doFilter(request,response);对请求资源放行,进入下一个过滤器或执行请求
Servlet/ServletConfig/ServletContext/ServeltRequest/ServletResponse
HttpServletRequest/HttpServletResponse
Filter/FilterConfig/FilterChain
3.过滤器技术细节
配置:
拦截所有的请求
指定路径的请求
拦截指定类型的请求:REQUEST(默认)/FORWARD(转发后拦截)
4.案例
a)编码处理
b)登录用户验证
1.文件上传与下载
1.1为什么要用文件上传?
项目中经常用到文件上传
例如:
QQ上传图像
资料共享:csdn
网站提供xls模板,让用户按照模板填写,填写后需要上传!
.......
1.2文件上传
文件上传:
1.指定表单类型为文件上传表单
enctype="multipart/form-data"
2.提交方式必须为:POST
3.表单中存在文件域元素
例如:
<form action="${pageContext.request.contextPath }/test" method="post" enctype="multipart/form-data">
用户名:<input type="text" name="username"/> <br/>
文件:<input type="file" name="file1"/> <br/>
<input type="submit">
</form>
index.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE body PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<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">
</head>
<body>
<form action="${pageContext.request.contextPath }/test" method="post" enctype="multipart/form-data">
用户名:<input type="text" name="username"/> <br/>
文件:<input type="file" name="file1"/> <br/>
<input type="submit">
</form>
</body>
</html>
TestServlet.java:
package cn.itcast.a_test_upload;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class TestServlet
* 手动处理文件上传
*/
@WebServlet("/TestServlet")
public class TestServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
/*request.getQueryString();//获取GET:username=Tom&pwd=888
request.getInputStream();//获取POST:inputStream
request.getParameter("");*/
//获取表单(POST)数据
InputStream in=request.getInputStream();
//转换流
InputStreamReader inReader=new InputStreamReader(in);
//缓冲流
BufferedReader reader = new BufferedReader(inReader);
String str=null;
while((str=reader.readLine())!=null){
System.out.println(str);
}
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
web.xml:
<?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">
<servlet>
<servlet-name>Test</servlet-name>
<servlet-class>cn.itcast.a_test_upload.TestServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Test</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
a.txt:
aaaaaaaaaaa
bbbbbbbbbbbbbbbbb
ccccccccccccccccc
------WebKitFormBoundary6vG3jk0aMY0VBWLu
Content-Disposition: form-data; name="username" 【FileItem】
Tom
------WebKitFormBoundary6vG3jk0aMY0VBWLu
Content-Disposition: form-data; name="file1"; filename="a.txt"
Content-Type: text/plain 【FileItem】
aaaaaaaaaaa
bbbbbbbbbbbbbbbbb
ccccccccccccccccc
------WebKitFormBoundary6vG3jk0aMY0VBWLu--
如果要获取上传文件数据,需要对上面结果进行解析!
如果自己解析,比较麻烦!
通常,对于文件上传,我们使用别人写好的解析程序即可!即使用别人写好的组件,这个组件叫FileUpload组件!文件上传组件!
FileUpload组件
FileUpload组件,也叫文件上传组件!,是apache提供的开源项目!
组件使用:
1.下载组件,引入jar文件
commons-fileupload-1.2.1.jar 【文件上传组件核心jar包】
commons-io-1.4.jar 【封装了对文件处理的相关工具类】
2.配置(prop/xml)
3.Api学习
先使用文件上传组件,实现一个文件上传功能!
2.文件上传组件API
|--FileItemFactory 文件上传工厂类(把每一个请求表单项封装为一个个FileItem对象)
fac.setRepository(Repository);//设置删除临时目录
|--SevletFileUpload 文件上传核心类:可以获取所有的FileItem对象
List parseRequest(request); 获取所有文件上传项
Boolean isMultipartContent(request) 判断表单类型,文件上传表单,返回true
upload.setFileSizeMax(fileSizeMax); 设置单个文件的最大值
upload.setSizeMax(sizeMax); 设置总文件的大小
upload.setHeaderEncoding("UTF-8"); 设置上传文件名的编码 相当于request.setCharacterEncoding(..)
|--FileItem 封装了普通表单项的值及文件上传表单元素值
item.getFieldName(); 获取上传表单元素名称
item.getString(); 获取上传数据
item.getString(); 获取上传数据,处理中文
item.getContentType(); 获取上传文件类型【文件项】
item.getInputStream(); 获取文件流【文件项】
item.getName(); 获取文件名【文件项】
item.write(file); 写文件
item.delete(); 删除临时文件
实现一个完整的文件上传:
1.设置单个文件不能超过30M
2.设置总大小不能超过50M
3.上传目录:上传到项目资源目录下的upload目录下
4.上传文件不能覆盖,解决上传文件文件名的同名问题
index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE body PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<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">
</head>
<body>
<form action="${pageContext.request.contextPath }/FileUpload" method="post" enctype="multipart/form-data">
用户名:<input type="text" name="username"/> <br/>
文件:<input type="file" name="file1"/> <br/>
<input type="submit">
</form>
</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_2_5.xsd" version="2.5">
<servlet>
<servlet-name>upload</servlet-name>
<servlet-class>cn.itcast.b_upload.FileUpload</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>upload</servlet-name>
<url-pattern>/FileUpload</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>TestServlet</servlet-name>
<servlet-class>cn.itcast.a_test_upload.TestServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>TestServlet</servlet-name>
<url-pattern>/test</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
FileUpload.java(Servlet)
package cn.itcast.b_upload;
import java.io.File;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.FileItem;
/**
* Servlet implementation class FileUpload
* 文件上传组件使用
*/
public class FileUpload extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.创建文件上传工厂类
DiskFileItemFactory fac=new DiskFileItemFactory();
//2.创建文件上传核心类对象
ServletFileUpload upload=new ServletFileUpload();
upload.setFileItemFactory(fac);
//【一,设置单个文件最大:30】
upload.setFileSizeMax(30 * 1024 * 1024);//30M
//【二,设置总文件大小:50】
upload.setSizeMax(50 * 1024 * 1024);
//判断:表单是否为文件上传表单
if(upload.isMultipartContent(request)){
//3.把请求数据转换为FileItem的集合
try {
List<FileItem> items=upload.parseRequest(request);
//遍历FileItem
for(FileItem item:items){
//判断普通表单元素还是文件元素
//普通表单
if(item.isFormField()){
//获取元素名称
String fieldName=item.getFieldName();
//获取值
String value=item.getString();
System.out.println(fieldName+value);
}else{
//处理文件上传
//获取文件名
String name=item.getName();
//获取上传的目录路径
/*D:\Tomcat8.0 webapps day23 upload*/
String basePath=getServletContext().getRealPath("/upload");
//创建文件对象
File file=new File(basePath,name);
try {
item.write(file);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}//写文件
item.delete();//删除临时文件
}
}
} catch (FileUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else{
System.out.println("不处理!");
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
文件上传与下载完整案例:
index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>index</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
</head>
<body>
<a href="${pageContext.request.contextPath }/upload.jsp">文件上传</a>
<a href="${pageContext.request.contextPath }/fileServlet?method=downList">文件下载</a>
</body>
</html>
downlist.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>下载列表</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
</head>
<body>
<table border="1" align="center">
<tr>
<th>序号</th>
<th>文件名</th>
<th>操作</th>
</tr>
<c:forEach var="en" items="${requestScope.fileNames}" varStatus="vs">
<tr>
<td>${vs.count }</td>
<td>${en.value }</td>
<td>
<%--<a href="${pageContext.request.contextPath }/fileServlet?method=down&..">下载</a>--%>
<!-- 构建一个地址 -->
<c:url var="url" value="fileServlet">
<c:param name="method" value="down"></c:param>
<c:param name="fileName" value="${en.key}"></c:param>
</c:url>
<!-- 使用上面地址 -->
<a href="${url }">下载</a>
</td>
</tr>
</c:forEach>
</table>
</body>
</html>
upload.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>upload</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
</head>
<body>
<form name="frm_test" action="${pageContext.request.contextPath }/fileServlet?method=upload" method="post" enctype="multipart/form-data">
<%--<input type="hidden" name="method" value="upload">--%>
用户名:<input type="text" name="userName"> <br/>
文件: <input type="file" name="file_img"> <br/>
<input type="submit" value="提交">
</form>
</body>
</html>
web.xml
<?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">
<servlet>
<servlet-name>FileServlet</servlet-name>
<servlet-class>cn.itcast.servlet.FileServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>FileServlet</servlet-name>
<url-pattern>/fileServlet</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
FileServlet.java
package cn.itcast.servlet;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.servlet.ServletException;
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;
/**
* 处理文件上传与下载
* @author Jie.Yuan
*
*/
public class FileServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 获取请求参数: 区分不同的操作类型
String method = request.getParameter("method");
if ("upload".equals(method)) {
// 上传
upload(request,response);
}
else if ("downList".equals(method)) {
// 进入下载列表
downList(request,response);
}
else if ("down".equals(method)) {
// 下载
down(request,response);
}
}
/**
* 1. 上传
*/
private void upload(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
// 1. 创建工厂对象
FileItemFactory factory = new DiskFileItemFactory();
// 2. 文件上传核心工具类
ServletFileUpload upload = new ServletFileUpload(factory);
// 设置大小限制参数
upload.setFileSizeMax(10*1024*1024); // 单个文件大小限制
upload.setSizeMax(50*1024*1024); // 总文件大小限制
upload.setHeaderEncoding("UTF-8"); // 对中文文件编码处理
// 判断
if (upload.isMultipartContent(request)) {
// 3. 把请求数据转换为list集合
List<FileItem> list = upload.parseRequest(request);
// 遍历
for (FileItem item : list){
// 判断:普通文本数据
if (item.isFormField()){
// 获取名称
String name = item.getFieldName();
// 获取值
String value = item.getString();
System.out.println(value);
}
// 文件表单项
else {
/******** 文件上传 ***********/
// a. 获取文件名称
String name = item.getName();
// ----处理上传文件名重名问题----
// a1. 先得到唯一标记
String id = UUID.randomUUID().toString();
// a2. 拼接文件名
name = id + "#" + name;
// b. 得到上传目录
String basePath = getServletContext().getRealPath("/upload");
// c. 创建要上传的文件对象
File file = new File(basePath,name);
// d. 上传
item.write(file);
item.delete(); // 删除组件运行时产生的临时文件
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 2. 进入下载列表
*/
private void downList(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 实现思路:先获取upload目录下所有文件的文件名,再保存;跳转到down.jsp列表展示
//1. 初始化map集合Map<包含唯一标记的文件名, 简短文件名> ;
Map<String,String> fileNames = new HashMap<String,String>();
//2. 获取上传目录,及其下所有的文件的文件名
String bathPath = getServletContext().getRealPath("/upload");
// 目录
File file = new File(bathPath);
// 目录下,所有文件名
String list[] = file.list();
// 遍历,封装
if (list != null && list.length > 0){
for (int i=0; i<list.length; i++){
// 全名
String fileName = list[i];
// 短名
String shortName = fileName.substring(fileName.lastIndexOf("#")+1);
// 封装
fileNames.put(fileName, shortName);
}
}
// 3. 保存到request域
request.setAttribute("fileNames", fileNames);
// 4. 转发
request.getRequestDispatcher("/downlist.jsp").forward(request, response);
}
/**
* 3. 处理下载
*/
private void down(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 获取用户下载的文件名称(url地址后追加数据,get)
String fileName = request.getParameter("fileName");
fileName = new String(fileName.getBytes("ISO8859-1"),"UTF-8");
// 先获取上传目录路径
String basePath = getServletContext().getRealPath("/upload");
// 获取一个文件流
InputStream in = new FileInputStream(new File(basePath,fileName));
// 如果文件名是中文,需要进行url编码
fileName = URLEncoder.encode(fileName, "UTF-8");
// 设置下载的响应头
response.setHeader("content-disposition", "attachment;fileName=" + fileName);
// 获取response字节流
OutputStream out = response.getOutputStream();
byte[] b = new byte[1024];
int len = -1;
while ((len = in.read(b)) != -1){
out.write(b, 0, len);
}
// 关闭
out.close();
in.close();
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request, response);
}
}