![8d0fbe8e4b87ccbf6b64e64f0eb92cbc.png](https://img-blog.csdnimg.cn/img_convert/8d0fbe8e4b87ccbf6b64e64f0eb92cbc.png)
常用对象
Cookie对象
浏览器的一种技术通过服务器的程序能将一些只须保存在客户端,或者 在客户端进行处理的数据,放在本地的计算机上,不需要通过网络传输;cookie的大小在4kb左右,每个浏览器在同一域名下能存放cookie数量是有限的,谷歌浏览器大概是50个。Cookie不跨浏览器,换电脑也无效。
优缺点
提高网页的效率,减轻服务器的负载。
安全性较差
创建cookie
Cookie cookie = new Cookie("cookie的名称","cookie的值");
键和值都是字符串,不支持中文
发送cookie
response.addCookie(cookie对象);
public class Servlet01 extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("Cookie01...");
// 创建Cookie对象
Cookie cookie = new Cookie("uname","zhangsan");
// 通过response对象响应cookie对象给客户端
resp.addCookie(cookie);
}
}
获取cookie
request.getCookies(); 返回的是所有的cookie的数组
public class Servlet02 extends HttpServlet {
@SuppressWarnings("deprecation")
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("Cookie02...");
// 获取cookie数组
Cookie[] cookies = req.getCookies();
// 判断cookies数值是否为空
if (cookies != null && cookies.length > 0) {
// 遍历cookie数组
for (Cookie cookie : cookies) {
// 得到cookie的键和值
String name = cookie.getName();
String value = cookie.getValue();
// 如果有中文需要解码 URLdecoder.decode()
name = URLDecoder.decode(name);
value = URLDecoder.decode(value);
System.out.println(name+"="+value);
// 得到指定的键的值
if ("uname".equals(name)) {
System.out.println("指定Coookie的值为:" + value);
}
}
}
}
}
cookie到期时间设置
注:Cookie是浏览器技术,关闭服务器不会影响cookie的变化
到期时间,到期时间用来指定该 cookie 何时失效
默认为当前浏览器关闭即失效
手动设定 cookie 的有效时间(通过到期时间计算)
通过 setMaxAge(int time);方法设定 cookie 的最大有效时间,以秒为单位
设置时间
大于 0 的整数,表示存储的秒数
若为负数,则表示不存储该 cookie;若为 0,则删 除该 cookie
负整数:cookie 的 maxAge 属性的默认值就是-1,表示只在浏览器内存中存活,一旦关闭浏览器窗口,那么 cookie 就会消失
正整数:表示 cookie 对象可存活指定的秒数。当生命大于 0 时,浏览器会把 Cookie 保存到硬盘上,就算关闭浏览器,就算重启客户端电脑,cookie 也会存活相应的时间
零:cookie 生命等于 0 是一个特殊的值,它表示 cookie 被作废!也就是说,如果原来浏览器已经保存了这个 Cookie,那么可以通过 Cookie 的setMaxAge(0)来删除这个 Cookie。 无论是在浏览器内存中,还是在客户端硬盘上都会删除这个 Cookie
public class Servlet03 extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("Cookie03...");
// 创建cookie对象
Cookie cookie = new Cookie("uname2","lisi");
// 设置cookie对象的失效时间
// cookie.setMaxAge(15); // 正整数。15秒后失效
// cookie.setMaxAge(-1); // 负整数,默认关闭浏览器即失效
cookie.setMaxAge(0); // 零:表示即刻删除cookie对象
// 发送cookie
resp.addCookie(cookie);
// 删除指定cookie对象
Cookie cookie2 = new Cookie("uname",null);
cookie2.setMaxAge(0); // 删除cookie
resp.addCookie(cookie2); // 响应cookie
}
}
cookie不能存中文
有中文则通过 URLEncoder.encode()来进行编码
获取时通过 URLDecoder.decode()来进行解码
public class Servlet04 extends HttpServlet {
@SuppressWarnings("deprecation")
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("Cookie04...");
// 创建cookie对象
Cookie cookie = new Cookie(URLEncoder.encode("姓名"),URLEncoder.encode("张三"));
// 发送cookie
resp.addCookie(cookie);
}
}
cookie的覆盖
如果出现相同的cookie名称,则会覆盖原来的cookie(在相同的domain和path下)
Cookie的path
只有访问的地址中包含cookie的path值时,才能得到cookie对象
public class Servlet06 extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("Cookie06...");
// 创建cookie
Cookie cookie = new Cookie("uname","admin");
// 设置path (当前服务器下任意资源都可访问)
cookie.setPath("/");
// 发送cookie
resp.addCookie(cookie);
// 创建cookie
Cookie cookie2 = new Cookie("userName","Lisa");
// 设置path
cookie2.setPath("/sc04/test/aa");
// 发送cookie
resp.addCookie(cookie2);
}
}
HttpSession对象
Session的作用
Session 的作用就是为了标识一次会话,或者说确认一个用户
并且在一次会话(一个用户的多次请求)期间共享数据
可以通过 req.getSession()方法,来获取当前会话的 session 对象
JSESSIONID
SessionId 是为了标识一次会话的唯一标志
每当一次请求到达服务器,如果开启了会话(访问了 session),服务器第一步会查看是否从客户端回传一个名为 JSESSIONID 的 cookie
如果JSESSIONID不存在,则服务器会新建session对象,并重新标识
如果JSESSIONID存在,服务器会将客户端回传过来的ID去服务器中查找与之对应的session对象
如果没找到,则服务器会新建session对象,并重新标识
如果找到,则获取 session对象,响应给客户端
public class Session01 extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("Session01...");
// 获取session对象
HttpSession session = req.getSession();
// 会话标识符
String id = session.getId();
System.out.println("会话标识符: " + id);
// 创建时间
System.out.println("创建时间:" + session.getCreationTime());
// 最后一次访问时间
System.out.println("最后一次访问时间:" + session.getLastAccessedTime());
// 是否是新的session
System.out.println("是否是新的session对象:" + session.isNew());
}
}
Session域对象
通过 setAttribute(name,value);方法向域对象中添加数据
通过 getAttribute(name) 从域对象中获取数据
通过 removeAttribute(name)从域对象中移除数据
public class Session02 extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("Session02...");
// 创建或获取session对象
HttpSession session = req.getSession();
System.out.println(session.getId());
// 设置session域对象
session.setAttribute("aa", "AA");
// 设置request域对象
req.setAttribute("bb", "BB");
// 请求转发跳转到指定servlet
//req.getRequestDispatcher("ser03").forward(req, resp);
// 重定向
resp.sendRedirect("ser03");
}
}
public class Session03 extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("Session03...");
// 创建或获取session对象
HttpSession session = req.getSession();
System.out.println(session.getId());
// 获取session域对象
String aa = (String) session.getAttribute("aa");
System.out.println("Session中的域对象:" + aa);
// 获取request域对象
String bb = (String) req.getAttribute("bb");
System.out.println("Request中的域对象:" + bb);
}
}
Session的失效
1、达到最大不活动时间
Tomcat中默认最大不活动时间为30分钟
可以自行修改默认不活动时间,但不建议
<session-config>
<session-timeout>30</session-timeout>
</session-config>
2、自己设定过期时间
通过 session.setMaxInactiveInterval(int);来设定 session 的最大不活动时间,单位为秒
通过 getMaxInactiveInterval();方法来查看当前 Session 对象的最大不活动时间
3、立即失效
手动销毁session对象 session.invalidate()
4、关闭浏览器
session的底层依赖于cookie,默认关闭浏览器失效
5、关闭服务器
非正常关闭服务器时才会失效
如果是正常关闭服务器,session会被钝化到本地磁盘,下次访问时会从本地磁盘中活化出来
public class Session04 extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("Session04...");
// 创建或获取session对象
HttpSession session = req.getSession();
System.out.println(session.getId());
// 当前 Session 对象的最大不活动时间
System.out.println(session.getMaxInactiveInterval());
// 设置Session 对象的最大不活动时间
session.setMaxInactiveInterval(150);
// 手动销毁session
// session.invalidate();
}
}
ServletContext对象
每个web应用(web项目)有且仅有一个ServletContext对象,又称为application对象;Web容器在启动时会为每个web应用创建一个ServletContext对象
作用
1、作为域对象,共享数据,在整个应用中都有效
2、获取web应用相关信息
获取服务器版本 getServerInfo()
获取当前项目在服务器中真实路径 getRealPath()
获取ServletContext对象
1> 通过request对象获取
request.getServletContext();
2> 通过session获取
request.getSession().getServletContext()
3> 通过getServletConfig()方法获取
getServletConfig().getServletContext()
4> 直接获取
getServletContext()
application域对象
通过 setAttribute(name,value);方法向域对象中添加数据
通过 getAttribute(name) 从域对象中获取数据
通过 removeAttribute(name)从域对象中移除数据
常用方法
获取服务器版本 getServerInfo()
获取当前项目在服务器中真实路径 getRealPath()
public class Servlet01 extends HttpServlet {
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("Servlet01...");
// 1> 通过request对象获取
ServletContext servletContext = request.getServletContext();
// 2> 通过session获取
ServletContext servletContext2 = request.getSession().getServletContext();
// 3> 通过getServletConfig()方法获取
ServletContext servletContext3 = getServletConfig().getServletContext();
// 4> 直接获取
ServletContext servletContext4 = getServletContext();
// 获取服务器版本 getServerInfo()
String serverInfo = request.getServletContext().getServerInfo();
// 获取当前项目在服务器中真实路径 getRealPath()
String path = servletContext.getRealPath("/");
System.out.println("获取服务器版本: " + serverInfo);
System.out.println("获取当前项目在服务器中真实路径: " + path);
}
}
UploadServlet(文件上传)
前台页面
表单实现文件上传
1、表单的提交类型为method="POST”
2、表单类型设置为enctype="multipart/fptm-data"
3、表单元素设置为name属性值
后台代码
首先需要导入第三方 jar 包,Apache Commons - Apache Commons
下 载commons-io 和 commons-fileupload 两个 jar 的资源。解压并导入到项目中
commons-fileupload.jar 是文件上传的核心包
commons-io.jar 是 filefupload 的依赖包,同时又是一个工具包
实现步骤
DiskFileItemFactory – 设置磁盘空间,保存临时文件。只是一个工具类
ServletFileUpload – 文件上传的核心类,此类接收 request,并解析
ServletFileUpload.parseRequest(request); – List 解析 request
1、创建一个 DiskFileItemFactory工厂类,并制定临时文件的大小
2、创建SevletFileUpload核心类,接受临时文件,做请求的转换
3、通过ServletFileUpload类转换原始请求,得到FileItem集合
4、遍历集合中的各个元素并处理
5、判断每个元素是否是普通表单项,如果是则按照普通表单项处理
6、如果不是普通表单项,则是文件,通过处理的方式进行处理(上传)
public class UploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("文件上传...");
// 设定编码,可以获取中文文件名
request.setCharacterEncoding("UTF-8");
// 获取tomcat下的upload目录的路径
String path = getServletContext().getRealPath("/upload");
// 临时文件目录
String tempPath = getServletContext().getRealPath("/temp");
// 检查我们是否有文件上传请求
// boolean isMultipart = ServletFileUpload.isMultipartContent(request);
// 1、声明DiskFileItemFactory工厂类,用于在指定磁盘上设置一个临时目录
DiskFileItemFactory disk = new DiskFileItemFactory(1024 * 10, new File(tempPath));
// 2、声明ServletFileUpload,接收上面的临时文件。也可以默认值
ServletFileUpload uplaod = new ServletFileUpload(disk);
try {
// 3、解析request,返回FileItem的集合
List<FileItem> list = uplaod.parseRequest(request);
// 判断集合是否为空
if (list.size() > 0) {
// 遍历FileItem的集合,判断是普通表单项还是文件上传
for (FileItem file : list)
// 判断是否是普通的表单项
if (file.isFormField()) {
String fieldName = file.getFieldName();
// 中文乱码,此时还需要指定获取数据的编码方式
// String value = file.getString();
String value = file.getString("UTF-8");
System.out.println(fieldName + "=" + value);
} else { // 说明是一个文件
// 获取文件本身的名称
String fileName = file.getName();
System.out.println(file.getFieldName());
// 处理文件名称
fileName = fileName.substring(fileName.lastIndexOf("") + 1);
System.out.println("old Name : " + fileName);
// 修改名称 (得到文件的后缀名)
String extName = fileName.substring(fileName.lastIndexOf("."));
// 生成随机的文件名 + 文件后缀
String newName = UUID.randomUUID().toString().replace("-", "") + extName;
// 保存新的名称,并写出到新文件中
file.write(new File(path + "/" + newName));
System.out.println("文件名是:" + fileName);
System.out.println("文件大小是:" + file.getSize());
// 删除临时文件
file.delete();
}
}
} catch (FileUploadException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
DownloadServlet(文件下载)
1:需要通过 HttpServletResponse.setContentType 方法设置 Content-type 头字段的值,为浏览器无法使用某种方式或激活某个程序来处理的 MIME 类型,
例 如 ”application/octet-stream” 或 ”application/x-msdownload” 等
2:需要通过 HttpServletResponse.setHeader 方法设置Content-Disposition 头的值 为”attachment;filename=文件名”
3: 读取下载文件,调用 HttpServletResponse.getOutputStream 方法返回的 OutputStream 对象来向客户端写入附件内容
ublic class DownloadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 设置请求的编码
request.setCharacterEncoding("UTF-8");
// 得到要下载的文件名
String fileName = request.getParameter("fileName");
// 得到文件存放咋服务器中的真实路径
String filePath = request.getServletContext().getRealPath("/upload/" + fileName);
// 通过路径得到file对象
File file = new File(filePath);
// 判断文件是否存在,并且是一个标准文件
if (file.exists() && file.isFile()) {
// 设置相应类型 application/octet-stream
response.setContentType("application/x-msdownload");
// 设置头信息
response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
// 得到文件的输入流
InputStream in = new FileInputStream(file);
// 得到字节输出流
ServletOutputStream out = response.getOutputStream();
// 定义字节数组 和 长度
byte[] bytes = new byte[1024];
int len = 0;
// 遍历
while((len = in.read(bytes)) != -1) {
out.write(bytes, 0, len);
}
// 关闭资源
out.close();
in.close();
} else {
System.out.println("文件不存在!");
}
}
}