文件的上传和下载
文件上传的介绍
<?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">
<servlet>
<servlet-name>UploadServlet</servlet-name>
<servlet-class>com.atguigu.servlet.UploadServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>UploadServlet</servlet-name>
<url-pattern>/uploadServlet</url-pattern>
</servlet-mapping>
</web-app>
package com.atguigu.servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class UploadServlet extends HttpServlet {
/**
* 用来处理文件生成
* @param req
* @param resp
* @throws ServletException
* @throws IOException
*/
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("文件上传过来了");
}
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<%-- form:post --%>
<form action="http://localhost:8080/jstl/uploadServlet" method="post" enctype="multipart/form-data">
用户名 :<input type="text" name="username"> <br>
头像 :<input type="file" name="photo"> <br>
<input type="submit" value="上传">
</form>
</body>
</html>
上传的http协议介绍
- 以流的形式上传和接收
- 所以如果用getPraramter没有用
package com.atguigu.servlet;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class UploadServlet extends HttpServlet {
/**
* 用来处理文件生成
* @param req
* @param resp
* @throws ServletException
* @throws IOException
*/
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletInputStream inputStream = req.getInputStream();
byte[] buffer = new byte[1024000];
int read = inputStream.read(buffer);
System.out.println(new String(buffer, 0, read));
}
}
上传合用到的类和方法介绍
使用fileupload解析上传的数据
选中整行以后 command + option + t 快捷键
然后选择 try catch,然后手动改成Exception
package com.atguigu.servlet;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;
public class UploadServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 1、先判断上传的数据是否为多段数据(只有是多段数据,才是文件上传的)
if (ServletFileUpload.isMultipartContent((req))) {
// 创建FileItemFactory工厂实现类
FileItemFactory fileItemFactory = new DiskFileItemFactory();
// 创建用于解析上传数据的工具类 ServletFileUpload类
ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory);
// 解析上传的数据,得到每一个表单项FileItem
try {
List<FileItem> list = servletFileUpload.parseRequest(req);
// 循环判断,每一个表单项,是普通类型,还是上传的文件
for (FileItem fileItem : list) {
if (fileItem.isFormField()) {
// 普通表单项
System.out.println("表单项的name属性值:" + fileItem.getFieldName());
// 参数UTF-8,解决乱码问题
System.out.println("表单的value属性值:" + fileItem.getString("UTF-8"));
} else {
// 上传的文件
System.out.println("表单项的name属性值:" + fileItem.getFieldName());
System.out.println("上传的文件名:" + fileItem.getName());
// fileItem.write((new File(("e:\\" + fileItem.getName()))));
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
文件下载的实现
package com.atguigu.servlet;
import org.apache.commons.io.IOUtils;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
public class Download extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 1、获取要下载的文件名
String downloadFileName = "1.png";
// 2、读取要下载的文件内容(通过ServletContext对象可以读取)
ServletContext servletContext = getServletContext();
// 获取要下载的文件类型
String mimeType = servletContext.getMimeType("/file/" + downloadFileName);
System.out.println("下载的文件类型:" + mimeType);
// 4、在回传前,通过响应头告诉客户端返回的数据类型
resp.setContentType(mimeType);
// 5、还要告诉客户端收到的数据是用于下载使用(还是使用响应头)
// Content-Disposition响应头,表示收到的数据怎么处理
// attacjment表示附件,表示下载使用
// filename= 表示指定下载的文件名
resp.setHeader("Content-Disposition", "attachment;filename=" + downloadFileName);
/**
* /斜杠被服务器解析表示地址为http://ip:port/工程名/ 映射 到代码的web目录
*/
InputStream resourceAsStream = servletContext.getResourceAsStream("/file/" + downloadFileName);
// 获取响应的输出流
ServletOutputStream outputStream = resp.getOutputStream();
// 3、把下载的文件内容回传给客户端
// 读取输入流中全部的数据,复制给输出流,输出给客户端
IOUtils.copy(resourceAsStream, outputStream);
}
}
输入后敲回车,直接就下载文件了
使用URLEncoder解决谷歌和IE浏览器中文下载名乱码问题
可以和原文件名不同,下载下来显示的名称就是filename
如果filename=中国.jpg
,文件名会无法识别
因此,要对中文进行URL编码
Base64编解码操作
如果是火狐浏览器不支持上面这种方式
发现这个类和URLEncode类不同,不是静态方法,因此要先new
Base64编解码操作 解决 火狐浏览器的附近中文名问题
将原先那个setHeader换成resp.setHeader("Content-Disposition", "attachment; filename==?UTF-8?B?" + new BASE64Encoder().encode("中国.jpg".getBytes("UTF-8")) + "?=");
使用User-Agent请求头判断,动态切换不同的方案解决所有浏览器附件中文乱码问题
书城项目
command + shift + R
可以查找替换(可以先选中目录)
动态的base标签值
表单提交失败的错误回显
合并LoginServlet和RegistServlet程序为UserServlet程序
使用反射优化大量else if代码
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String action = req.getParameter("action");
try {
// 获取 action 业务鉴别字符串,获取相应的业务 方法反射对象
Method method = this.getClass().getDeclaredMethod(action, HttpServletRequest.class, HttpServletResponse.class);
// System.out.println(method);
// 调用目标业务 方法
method.invoke(this, req, resp);
} catch (Exception e) {
e.printStackTrace();
}
}
抽取 BaseServlet 程序
public abstract class BaseServlet extends HttpServlet {
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String action = req.getParameter("action");
try {
// 获取 action 业务鉴别字符串,获取相应的业务 方法反射对象
Method method = this.getClass().getDeclaredMethod(action, HttpServletRequest.class, HttpServletResponse.class);
// System.out.println(method);
// 调用目标业务 方法
method.invoke(this, req, resp);
} catch (Exception e) {
e.printStackTrace();
}
}
}
数据的封装和抽取 BeanUtils 的使用
command + option + t
选择代码的环绕方式
MVC概念
Cookie
什么是Cookie
Cookie的创建
<!-- Cookie.html -->
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="pragma" content="no-cache" />
<meta http-equiv="cache-control" content="no-cache" />
<meta http-equiv="Expires" content="0" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Cookie</title>
<!-- 因为是html页面 -->
<base href="http://localhost:8080/cookie/">
<style type="text/css">
ul li {
list-style: none;
}
</style>
</head>
<body>
<iframe name="target" width="500" height="500" style="float: left;"></iframe>
<div style="float: left;">
<ul>
<li><a href="cookieServlet?action=createCookie" target="target">Cookie的创建</a></li>
<li><a href="cookieServlet?action=getCookie" target="target">Cookie的获取</a></li>
<li><a href="cookieServlet?action=updateCookie" target="target">Cookie值的修改</a></li>
<li>Cookie的存活周期</li>
<li>
<ul>
<li><a href="cookieServlet?action=defaultLife" target="target">Cookie的默认存活时间(会话)</a></li>
<li><a href="cookieServlet?action=deleteNow" target="target">Cookie立即删除</a></li>
<li><a href="cookieServlet?action=life3600" target="target">Cookie存活3600秒(1小时)</a></li>
</ul>
</li>
<li><a href="cookieServlet?action=testPath" target="target">Cookie的路径设置</a></li>
<li><a href="" target="target">Cookie的用户免登录练习</a></li>
</ul>
</div>
</body>
</html>
package com.atguigu.servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;
public abstract class BaseServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 解决post请求中文乱码问题
// 一定要在获取请求参数之前调用才有效
req.setCharacterEncoding("UTF-8");
// 解决响应中文乱码问题
resp.setContentType("text/html; charset=UTF-8");
String action = req.getParameter("action");
try {
// 获取action业务鉴别字符串,获取相应的业务 方法反射对象
Method method = this.getClass().getDeclaredMethod(action, HttpServletRequest.class, HttpServletResponse.class);
// System.out.println(method);
// 调用目标业务 方法
method.invoke(this, req, resp);
} catch (Exception e) {
e.printStackTrace();
}
}
}
package com.atguigu.servlet;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class CookieServlet extends BaseServlet{
protected void createCookie(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 1、创建Cookie对象
Cookie cookie = new Cookie("key1", "value1");
// 2、通知客户端保存Cookie
resp.addCookie(cookie);
resp.getWriter().write("Cookie创建成功");
}
}
Cookie的获取
package com.atguigu.servlet;
import com.example.Cookie.CookieUtils;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class CookieServlet extends BaseServlet{
protected void createCookie(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 1、创建Cookie对象
Cookie cookie = new Cookie("key1", "value1");
// 2、通知客户端保存Cookie
resp.addCookie(cookie);
resp.getWriter().write("Cookie创建成功");
}
protected void getCookie(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Cookie[] cookies = req.getCookies();
// getName方法
// getValue方法
for (Cookie cookie : cookies) {
resp.getWriter().write("Cookie[" + cookie.getName() + " = " + cookie.getValue() + "] <br>");
}
Cookie iWantCookie = CookieUtils.findCookie("key1", cookies);
if (iWantCookie != null) {
resp.getWriter().write("找到了需要的Cookie");
}
}
}
package com.atguigu.util;
import javax.servlet.http.Cookie;
public class CookieUtils {
/**
* 查找指定名称的cookie对象
* @param name
* @param cookies
* @return
*/
public static Cookie findCookie(String name, Cookie[] cookies) {
if (name == null || cookies == null || cookies.length == 0) {
return null;
}
for (Cookie cookie : cookies) {
if (name.equals(cookie.getName())) {
return cookie;
}
}
return null;
}
}
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="pragma" content="no-cache" />
<meta http-equiv="cache-control" content="no-cache" />
<meta http-equiv="Expires" content="0" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Cookie</title>
<!-- 因为是html页面 -->
<base href="http://localhost:8080/cookie/">
<style type="text/css">
ul li {
list-style: none;
}
</style>
</head>
<body>
<iframe name="target" width="500" height="500" style="float: left;"></iframe>
<div style="float: left;">
<ul>
<li><a href="cookieServlet?action=createCookie" target="target">Cookie的创建</a></li>
<li><a href="cookieServlet?action=getCookie" target="target">Cookie的获取</a></li>
<li><a href="cookieServlet?action=updateCookie" target="target">Cookie值的修改</a></li>
<li>Cookie的存活周期</li>
<li>
<ul>
<li><a href="cookieServlet?action=defaultLife" target="target">Cookie的默认存活时间(会话)</a></li>
<li><a href="cookieServlet?action=deleteNow" target="target">Cookie立即删除</a></li>
<li><a href="cookieServlet?action=life3600" target="target">Cookie存活3600秒(1小时)</a></li>
</ul>
</li>
<li><a href="cookieServlet?action=testPath" target="target">Cookie的路径设置</a></li>
<li><a href="" target="target">Cookie的用户免登录练习</a></li>
</ul>
</div>
</body>
</html><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="pragma" content="no-cache" />
<meta http-equiv="cache-control" content="no-cache" />
<meta http-equiv="Expires" content="0" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Cookie</title>
<!-- 因为是html页面 -->
<base href="http://localhost:8080/cookie/">
<style type="text/css">
ul li {
list-style: none;
}
</style>
</head>
<body>
<iframe name="target" width="500" height="500" style="float: left;"></iframe>
<div style="float: left;">
<ul>
<li><a href="cookieServlet?action=createCookie" target="target">Cookie的创建</a></li>
<li><a href="cookieServlet?action=getCookie" target="target">Cookie的获取</a></li>
<li><a href="cookieServlet?action=updateCookie" target="target">Cookie值的修改</a></li>
<li>Cookie的存活周期</li>
<li>
<ul>
<li><a href="cookieServlet?action=defaultLife" target="target">Cookie的默认存活时间(会话)</a></li>
<li><a href="cookieServlet?action=deleteNow" target="target">Cookie立即删除</a></li>
<li><a href="cookieServlet?action=life3600" target="target">Cookie存活3600秒(1小时)</a></li>
</ul>
</li>
<li><a href="cookieServlet?action=testPath" target="target">Cookie的路径设置</a></li>
<li><a href="" target="target">Cookie的用户免登录练习</a></li>
</ul>
</div>
</body>
</html>
Cookie值的修改
protected void updateCookie(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 方案一 :
// 1、先创建一个要修改的同名的Cookie对象
// 2、在构造器,同时赋于新的cookie值
Cookie cookie = new Cookie("key1", "newValue1");
// 3、调用resp.addCookie(cookie); ;通知 客户端 保存修改
resp.addCookie(cookie);
resp.getWriter().write("key1的cookie已经修改好了");
}
protected void updateCookie(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Cookie cookie = CookieUtils.findCookie("key1", req.getCookies());
if (cookie != null) {
cookie.setValue("newValue1");
resp.addCookie(cookie);
}
}
- 中文也是
谷歌和火狐浏览器如何查看Cookie
Cookie的生命设置
protected void defaultLife(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Cookie cookie = new Cookie("defaultLife", "defaultLife");
cookie.setMaxAge(-1); // 设置存活时间
resp.addCookie(cookie);
}
protected void deleteNow(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 先找到要删除的cookie对象
Cookie cookie = CookieUtils.findCookie(("key1"), req.getCookies());
if (cookie != null) {
// 调用setMaxAge(0);
cookie.setMaxAge(0); // 表示马上删除,都不需要等待浏览器关闭
// 调用addCookie
resp.addCookie(cookie);
resp.getWriter().write("key1的cookie已经被删除");
}
}
Cookie 有效路径 Path 的设置
protected void testPath(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Cookie cookie = new Cookie("path1", "path1");
// getContextPath 得到工程路径
cookie.setPath( req.getContextPath() + "/abc" ); // 工程路径/abc
resp.addCookie(cookie);
resp.getWriter().write("创建了一个带有Path路径的Cookie");
}
Cookie 练习—免输入用户名登录
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>login.jsp</title>
</head>
<body>
<form action="http://localhost:8080/cookie/loginServlet" method="get">
用户名:<input type="text" name="username" value="${ cookie.username.value }"> <br>
密码:<input type="password" name="password"> <br>
<input type="submit" value="登陆">
</form>
</body>
</html>
package com.atguigu.servlet;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class LoginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String username = req.getParameter("username");
String password = req.getParameter("password");
if ("wzg168".equals(username) && "123456".equals(password)) {
Cookie cookie = new Cookie("username", username);
cookie.setMaxAge(60 * 60 * 24 * 7); // 当前Cookie一周内有效
resp.addCookie(cookie);
System.out.println("登陆成功");
} else {
System.out.println("登陆失败");
}
}
}
- 在登陆成功一次,且在cookie消亡时间之前,再次访问login.jsp用户名会自动显示