内容介绍
1 ServletContext对象
2 response响应对象
ServletContext对象
概述
ServletContext:servlet的上下文对象(全局管理者)
一个项目有且只有一个ServletContext对象
创建:tomcat一启动,就会为部署在它上面的项目创建一个对应的ServletContext对象
销毁:tomcat服务器只要已关闭,就会销毁当前的ServletContext对象
作用
1 可以作为一个容器,用来存储数据在多个servlet之间进行数据传递
2 获取当前项目被服务器发布的磁盘路径
API使用
1.获取对象:
getServletContext()
2.存储数据:
setAttribute()
getAttribute()
removeAttribute()
3.获取项目的磁盘路径:
getRealPath(String path)
1.获取对象:
// 可以作为域对象在多个servlet之间共享数据
public class ServletDemo1 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 获取ServletContext对象
ServletContext servletContext = getServletContext();
//存数据
servletContext.setAttribute("key1","aaaa");
servletContext.setAttribute("key2","bbbb");
response.getWriter().print("aaaa");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
}
2.存储数据:
// 可以作为域对象在多个servlet之间共享数据
public class ServletDemo2 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 获取ServletContext对象
ServletContext servletContext = getServletContext();
System.out.println(servletContext.getAttribute("key1")); // aaa
System.out.println(servletContext.getAttribute("key2")); // bbb
servletContext.removeAttribute("key1"); //删除aaa
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
}
3.获取项目的磁盘路径:
// 获取当前项目被服务器发布的磁盘根路径
public class ServletDemo4 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 获取当前项目被服务器发布的磁盘根路径
ServletContext servletContext = getServletContext();
String path = servletContext.getRealPath("download/4.jpg");
//E:\idea\code_demo\demo91\demo\out\artifacts\day03_war_exploded
System.out.println(path);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
}
response对象
概述
这个对象提供了可以对浏览器做响应数据
响应数据的组成:响应行 响应头 响应体
操作响应行(要求:知道状态码的含义)
格式:协议/版本 状态码 例如:HTTP/1.1 200
看懂状态码的意义:
200 请求已成功
302 重定向 (服务器让浏览器去访问别的资源)
304 去找缓存数据 (服务器让浏览器去找缓存)
403 服务器拒绝执行 (文件或文件夹加了权限)
404 请求的资源没找到 (代码中访问路径有问题)
405 请求的方法不存在 (代码中的方法找不到)
500 服务器错误 (代码写的有问题)
api方法:
setStatus(int sc) 设置响应的状态代码(一般用来设置 1xx 2xx 3xx)
sendError(int sc) 设置响应的状态代码(一般用来设置 4xx 5xx)
ps:我们一般是不操作状态码的 但需要知道一些状态码的含义
操作响应头
格式:key:value
api方法:
setHeader(String key,String value):设置键值对形式的响应头
掌握的响应头:
1 content-type: 通知浏览器响应的内容是什么类型的 并且用什么编码解析
(了解)response.setHeader("content-type","文件的类型;charset=utf-8");
(掌握)简写:response.setContentType("文件的类型;charset=utf-8");
2 location:重定向
(了解)response.setHeader("location", "/day31/sd4");
response.setStatus(302);
(掌握)简写:response.sendRedirect("url");
面试题:请求转发和重定向的区别?
1 请求转发是request对象方法 重定向是response对象方法
2 请求转发只有一次请求 地址不会发生改变 重定向多次请求 地址栏会发生改变
3 请求转发只能访问内部资源 重定向既可以访问内部资源也可以访问外部资源
3 refresh:定时刷新
(掌握)response.setHeader("refresh","秒数;url=跳转的路径");
4 content-disposition:通知浏览器写回去的东西要以附件形式打开 (只用于下载)
(掌握)response.setHeader("content-disposition","attachment;filename="+fileName);
1 content-type: 通知浏览器响应的内容是什么类型的 并且用什么编码解析
// 给浏览器做响应数据
// 服务器的任何数据信息如果想告诉浏览器,只能通过3个方面告知信息:通过响应行 通过响应头 通过响应体
public class ServletDemo5 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 响应行 (掌握每个状态码的含义 一般我们不会去主动操作状态码给浏览器的)
/* response.setStatus(200);
response.sendError(404);*/
// 响应头
// 作用:处理响应中文数据的乱码问题
//response.setHeader("content-type","text/html;charset=utf-8");
response.setContentType("text/html;charset=utf-8"); //掌握简写
response.getWriter().print("我得告诉浏览器展示在html页面上的数据,要使用utf-8编码去解析..");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
}
2 location:重定向 (既可以跳内部资源,也可以跳外部资源)
// 给浏览器做响应数据
// 服务器的任何数据信息如果想告诉浏览器,只能通过3个方面告知信息:通过响应行 通过响应头 通过响应体
public class ServletDemo6 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 响应头--location
System.out.println("浏览器访问到我了,但是我想让浏览器去访问百度,可是我要怎么告诉浏览器呢?");
// 重定向的第一种方式(了解)
// 响应行 302
// 响应头 百度地址
//response.setStatus(302);
//response.setHeader("location","http://www.baidu.com");
// 重定向的第二种方式(掌握)
response.sendRedirect("/day03/sd1");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
}
请求转发和重定向的区别:
3 refresh:定时刷新
public class ServletDemo7 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("浏览器访问到我了,但是我想告诉浏览器让浏览器5秒钟之后跳转到百度...");
// 设置头(定时刷新refresh)
response.setHeader("refresh","5;url=http://www.baidu.com");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
}
操作响应体
页面上要展示的内容
api方法:
PrintWriter getWriter().print();字符流
ServletOutputStream getOutputStream():字节流 (二进制)
特点:
1 不能同时出现
2 若是能写的出来的内容用字符流,其他全用字节流(下载专用)
3 服务器会自动帮我们关闭这2个流.
public class ServletDemo8 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//设置响应体 (都要在页面展示) 只能用字符流或者字节流中的一种
// 字符流
/*PrintWriter writer = response.getWriter();
writer.print("abcdefg");*/
response.getWriter().print("abcdefg");
// 字节流
/*ServletOutputStream outputStream = response.getOutputStream();
outputStream.print("abceefg12345");*/
response.getOutputStream().print("abcdefg12345");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
}
特点:
1 不能同时出现
2 若是能写的出来的内容用字符流,其他全用字节流(下载专用)
3 服务器会自动帮我们关闭这2个流.
案例实现-下载
下载:将服务器上的资源 下载到本地(io流)
上传:将本地的资源 上传到服务器上(io流)
下载步骤
1:获取用户点击要下载的资源是哪一个
2:需要拿着用户的下载资源去咱们的服务器匹配有没有这个资源
3:需要通过设置响应头,告诉浏览器写回去的东西要以附件形式打开
4:输入流和输出流 一个读 一个写
get提交方式就相当于在地址栏中拼接 ?
// getServletContext().getRealPath(); 获取当前项目部署的绝对位置
// 下载
/*
* 下载:从服务器上将资源下载到本地(io流)
* 上传:把本地的资源上传到服务器(io流)
* 步骤实现:
* 1 需要在服务器上准备用户要下载的资源
* 2 为用户提供一个下载的页面 download.html
* 3 只要用户点击要下载的资源 后台servlet要为用户实现下载功能
* 核心
* 1 明确用户要下载的资源是什么
* 2 获取用户要下载的资源和服务器上的资源做匹配
* 3 告诉浏览器写回去的数据要以附件形式打开(下载专用头)
* 4 如果匹配成功 一个流读 一个流写回去
*
* */
public class DownloadServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 1 明确用户要下载的资源是什么
String fileName = request.getParameter("fileName");
// 2 获取用户要下载的资源和服务器上的资源做匹配
// getServletContext().getRealPath(); 获取当前项目部署的绝对位置
ServletContext servletContext = getServletContext();
String realPath = servletContext.getRealPath("download/"+fileName);
// 3 告诉浏览器写回去的数据 要以附件形式打开
response.setHeader("content-disposition","attachment;filename="+fileName);
// 4 一个读数据 一个写数据
File file = new File(realPath);
// 输入流
FileInputStream is = new FileInputStream(file);
// 输出流
ServletOutputStream os = response.getOutputStream();
//一边读 一边写
IOUtils.copy(is,os); // IOUtils 工具类
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
}
若浏览器下载的文件含有中文名称,为确保不出现乱码。代码需改进。
public class DownloadServlet2 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 1 明确用户要下载的资源是什么
String fileName = request.getParameter("fileName"); // 文档.txt
// 2 获取用户要下载的资源和服务器上的资源做匹配
ServletContext servletContext = getServletContext();
String realPath = servletContext.getRealPath("download/"+fileName); //文档.txt
// 3 告诉浏览器写回去的数据 要以附件形式打开 //不能出现中文
//浏览器规定了附件回去的数据不能有中文 必须得是中文的字符格式编码
// 火狐浏览器是按照base64编码解 文档.txt--编成--base64的编码格式
// 其它浏览器是按照utf-8编码解 文档.txt--编成--utf-8的编码格式
String value = request.getHeader("user-agent");
String encode =null;
if(value.contains("Firefox")){
// 火狐浏览器
Base64.Encoder encoder = Base64.getEncoder();
encode = "=?utf-8?B?" + encoder.encodeToString(fileName.getBytes("utf-8")) + "?=";
}else {
// 其它浏览器
encode = URLEncoder.encode(fileName, "utf-8");
}
response.setHeader("content-disposition","attachment;filename="+encode); //文档.txt //%E6%96%87%E6%A1%A3.txt
// 4 一个读数据 一个写数据
File file = new File(realPath);
// 输入流
FileInputStream is = new FileInputStream(file);
// 输出流
ServletOutputStream os = response.getOutputStream();
//一边读 一边写
IOUtils.copy(is,os);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
}
案例切换验证码
验证码的好处:
可以防止恶意注册
验证码:servlet
点击一次(请求) 返回一张图片(响应)
1 简单验证码
// 模拟验证码
public class ServletDemo9 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 做一个随机数
int i = new Random().nextInt();
// respose响应回去
response.getWriter().print(i);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
}
2 复杂验证码
public class CodeServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 使用java图形界面技术绘制一张图片
int charNum = 4;
int width = 20 * 4;
int height = 28;
// 1. 创建一张内存图片
BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
// 2.获得绘图对象
Graphics graphics = bufferedImage.getGraphics();
// 3、绘制背景颜色
graphics.setColor(Color.YELLOW);
graphics.fillRect(0, 0, width, height);
// 4、绘制图片边框
graphics.setColor(Color.GRAY);
graphics.drawRect(0, 0, width - 1, height - 1);
// 5、设置字体颜色和属性
graphics.setColor(Color.RED);
graphics.setFont(new Font("宋体", Font.BOLD, 22));
// 随机输出4个字符
String s = "ABCDEFGHGKLMNPQRSTUVWXYZ23456789";
Random random = new Random();
// session中要用到
String msg = "";
int x = 5;
for (int i = 0; i < charNum; i++) {
int index = random.nextInt(32);
String content = String.valueOf(s.charAt(index));
msg += content;
graphics.setColor(new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255)));
graphics.drawString(content, x, 22);
x += 20;
}
// 6、绘制干扰线
graphics.setColor(Color.GRAY);
for (int i = 0; i < 5; i++) {
int x1 = random.nextInt(width);
int x2 = random.nextInt(width);
int y1 = random.nextInt(height);
int y2 = random.nextInt(height);
graphics.drawLine(x1, y1, x2, y2);
}
// 释放资源
graphics.dispose();
// 图片输出 ImageIO
ImageIO.write(bufferedImage, "jpg", response.getOutputStream());
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
案例统计网站访问次数
// 统计访问量
public class CountServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 获取ServletContext对象
ServletContext servletContext = getServletContext();
// 获取次数
Integer count =(Integer)servletContext.getAttribute("count");
// 判断
if(count==null){
count=1;
}else {
count=count+1;
}
// 存进去
servletContext.setAttribute("count",count);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
}
//展示访问次数
public class ShowServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
// 获取ServletContext对象
ServletContext servletContext = getServletContext();
// 获取访问次数
Object count = servletContext.getAttribute("count");
// 判断
if(count==null){
response.getWriter().print("该网站的访问量为:0");
}else{
response.getWriter().print("该网站的访问量为:"+count);
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
}