JavaWeb——response、ServletContext

ServletContext 是项目运行时的一个唯一对象。

ServletContext();
上下文对象,创建服务器时自动创建的对象。
全局域对象,整个Web应用都可以使用。

获取方式:
this.getServletContext();
request.getServletContext();

package beer.longpress.www;

import java.io.IOException;

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;

@WebServlet("/getServletContext")
public class One extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		ServletContext context1 = this.getServletContext();
		ServletContext context2 = request.getServletContext();
		System.out.println(context1==context2);//返回结果true
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}
}
package beer.longpress.www;

import java.io.IOException;

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;

@SuppressWarnings("all")
@WebServlet("/getDatas")
public class Datas extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		ServletContext servletContext = this.getServletContext();
		//存全局变量
		servletContext.setAttribute("id", 677889);
		//读取全局变量
		Object attribute = servletContext.getAttribute("id");
		System.out.println(attribute);
		//删除全局变量
		servletContext.removeAttribute("id");
		System.out.println(servletContext.getAttribute("id"));
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
}

生命周期:
创建:随服务器创建而创建
销毁:服务器关闭即销毁

  1. 获取项目的配置信息
  2. 在项目内共享信息
package beer.longpress.www;

import java.io.IOException;

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;

@SuppressWarnings("all")
@WebServlet("/getData")
public class getInitData extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//获取ServletContext对象
		ServletContext servletContext = request.getServletContext();
		//读取web.xml中的初始值化值
		String initParameter = servletContext.getInitParameter("name");
		System.out.println(initParameter);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
}
方法名 描述
setAttribute(String name,Object object) 向ServletContext中存数据 map.put(key,value)  
getAttribute(String name) 从ServletContext中取数据 Map.get(key)
removeAttribute(name) 从ServletContext中移除数据 Map.remove(key)  
package beer.longpress.www;

import java.io.IOException;

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;

@SuppressWarnings("all")
@WebServlet("/getDatas")
public class Datas extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		ServletContext servletContext = this.getServletContext();
		//存全局变量
		servletContext.setAttribute("id", 677889);
		//读取全局变量
		Object attribute = servletContext.getAttribute("id");
		System.out.println(attribute);
		//删除全局变量
		servletContext.removeAttribute("id");
		System.out.println(servletContext.getAttribute("id"));
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
}

response对象

response对象
服务器向浏览器发送信息通过response发送。
在Servlet API中,定义了一个HttpServletResponse接口,它继承自ServletResponse接口,专门用来封装HTTP响应消息。

ServletResponse接口,普通响应接口。不能处理http协议
HttpServletResponse接口,专门处理http协议的响应接口。
Response对象封装了响应行、头、体三部分信息,我们可以通过调用response对象的方法,来轻松控制服务器向浏览器写响应信息

response对象操作响应行

状态码:
200 响应成功
404 路径找不到
500 服务器内部异常
302 重定向

  • setStatus(int status);

该方法用于设置HTTP响应消息的状态码,并生成响应状态行。由于响应状态行中的状态描述信息直接与状态码相关,而HTTP版本由服务器确定,因此,只要通过setStatus(int status)方法设置了状态码,即可实现状态行的发送。
若未设置状态码,且服务器运行正常,Web服务器会默认产生一个状态码为200的状态行

  • sendError(int sc,String errorMsg);

该方法用于发送表示错误信息的状态码。

package beer.longpress.www;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@SuppressWarnings("all")
@WebServlet("/StaCode")
public class StaCode extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//设置状态码,以及状态描述
		response.sendError(500, "by zero");
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
}

response对象操作响应头

当Servlet向客户端发送响应消息时,由于HTTP协议的响应头字段有很多种,为此,在HttpServletResponse接口中,定义了一系列设置HTTP响应头字段的方法,

       方法声明 功能描述
void addHeader(String name, String value)
void setHeader(String name, String value)
这两个方法都是用来设置HTTP协议的响应头字段,其中,参数name用于指定响应头字段的名称,参数value用于指定响应头字段的值。不同的是,addHeader()方法可以增加同名的响应头字段,而setHeader()方法则会覆盖同名的头字段
void setCharacterEncoding(String charset) 该方法用于设置输出内容使用的字符编码,对HTTP 协议来说,就是设置Content-Type头字段中的字符集编码部分。
void setContentType(String type) 该方法用于设置Servlet输出内容的MIME类型,对于HTTP协议来说,就是设置Content-Type响应头字段的值。例如,如果发送到客户端的内容是jpeg格式的图像数据,就需要将响应头字段的类型设置为“image/jpeg”。需要注意的是,如果响应的内容为文本,setContentType()方法的还可以设置字符编码,如:text/html;charset=UTF-8
void addIntHeader(String name, int value)
void setIntHeader(String name, int value)
这两个方法专门用于设置包含整数值的响应头。避免了使用addHeader()setHeader()方法时,需要将int类型的设置值转换为String类型的麻烦
void setContentLength(int len) 该方法用于设置响应消息的实体内容的大小,单位为字节。对于HTTP协议来说,这个方法就是设置Content-Length响应头字段的值 无需手动设置,由服务器自行设置
package beer.longpress.www;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@SuppressWarnings("all")
@WebServlet("/SetHead")
public class SetHead extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//设置编码格式,防止中文乱码
		response.setContentType("text/html;charset=utf-8");
		response.setCharacterEncoding("UTF-8");
		//操作响应头
		response.addHeader("uname", "lucy");
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
}

response对象操作响应体

         响应体信息无限,所以一般用来传递大量数据。

  • getOutputStream()

向响应体输出二进制字节流信息。

  • getWriter()

向响应体输出字符流信息。

  • 中文乱码问题

response.setCharacterEncoding("utf-8");
设置响应体数据的编码方式为utf-8

response.setContentType("text/html;charset=utf-8")Html:通知浏览器响应数据是html形式

Charset:编码方式
设置响应体数据的编码方式为utf-8,并且通知浏览器使用utf-8的方式解码

资源跳转-重定向

资源跳转有两种方式:

  1. 重定向   response
  2. 请求转发  request

重定向分为两种:

1、立即重定向

response.sendRedirect("https://longpress.ink");

2、延迟重定向

response.setHeader("refresh", "5;url=https://longpress.ink");
package beer.longpress.www;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@SuppressWarnings("all")
@WebServlet("/ReLo")
public class ReLo extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.sendRedirect("/a.html");//立即重定向
		response.setHeader("refresh", "5,url=/D/d.html");//延迟指定时间后重定向
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
}

案例

获取绝对路径、读取文件配置信息

package beer.onexone.serv;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
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("/read")
public class read extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public read() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//获取项目的真实地址
		String realPath = request.getServletContext().getRealPath("/");
		//获取项目内文件的第一行
		readFirstLine(realPath + "WEB-INF/webifo.txt");
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
	
	//IO流读取文件第一行
	public static void readFirstLine(String fileURL) throws IOException {
		BufferedReader bufferedReader = new BufferedReader(new FileReader(fileURL));
		String readLine = bufferedReader.readLine();
		System.out.println(readLine);
		bufferedReader.close();
		}
}

下载文件

package beer.longpress.www;

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;

@SuppressWarnings("all")
@WebServlet("/Download")
public class Download extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//		接收请求参数
		String filename = request.getParameter("filename");
//		获取图片路径
		String path = request.getServletContext().getRealPath("/download")+"\\"+filename;
		System.out.println(path);
//		创建字节输入流
		InputStream inputStream = new FileInputStream(path);
//		创建字节输出流
		OutputStream outputStream = response.getOutputStream();
//		设置响应头
		response.setHeader("Content-Disposition", "attachment;filename="+filename);
		byte[] buf = new byte[1024];
		int len = 0;//每次读取的有效字节长度
		while((len=inputStream.read(buf))!=-1){
			outputStream.write(buf, 0, len);
		}
		inputStream.close();
		outputStream.close();
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
}

验证码案例:

html:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<div>
	<img alt="" src="/2019-8-5_Two/pic" onclick="vc(this)">
</div>
	<script type="text/javascript">
		function vc(img) {
			//因浏览器会缓存请求,所以在请求后面加上时间来保证每次请求都更换验证码
			img.src="/2019-8-5_Two/pic?time="+new Date().getTime();
		}
	</script>
</body>
</html>

Servlet:

package beer.longpress.www;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@SuppressWarnings("all")
@WebServlet("/pic")
public class VerifyCodeServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	//生成图片
	protected void doGet(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		
		//1 高和宽
		int height = 30;
		int width = 60;
		String data = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
		Random random = new Random();
		
		
		//2 创建一个图片
		BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		
		//3 获得画板
		Graphics g = image.getGraphics();
		//4 填充一个矩形
		// * 设置颜色
		g.setColor(Color.BLACK);
		g.fillRect(0, 0, width, height);
		
		g.setColor(Color.WHITE);
		g.fillRect(1, 1, width-2, height-2);
		// * 设置字体
		g.setFont(new Font("宋体", Font.BOLD|Font.ITALIC, 25));
		
		
		//5 写随机字
		for(int i = 0 ; i < 4 ; i ++){
			// 设置颜色--随机数
			g.setColor(new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255)));
			
			// 获得随机字
			int index = random.nextInt(data.length());
			String str = data.substring(index, index + 1);
			
			// 写入
			g.drawString(str, width/6 * (i + 1), 20);
			
		}
		
		//6 干扰线
		for(int i = 0 ; i < 3 ; i ++){
			// 设置颜色--随机数
			g.setColor(new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255)));
			// 随机绘制先
			g.drawLine(random.nextInt(width), random.nextInt(height), random.nextInt(width),random.nextInt(height));
			// 随机点
			g.drawOval(random.nextInt(width), random.nextInt(height), 2, 2);
		}
		
		
		//end 将图片响应给浏览器
		ImageIO.write(image, "jpg", response.getOutputStream());
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		doGet(request, response);
	}

}

jingsongchan

发表评论

电子邮件地址不会被公开。 必填项已用*标注