response对象
功能:设置相应消息
1:设置响应行
格式:http/1.1 200 ok
设置状态码:SetStatus(int sc)
2:设置响应头:setHrader(String name,String value)
3.设置响应体
使用步骤
- 获取输出流
*字符输出流:PrintWriter getWriter()
*字节输出流:ServletOutputStream getOutputStream() - 使用输出流将数据输出到客户端浏览器
实例
一 服务器输出字符数据到浏览器
步骤
1获取字符输出流
response.getWriter()
2.输出数据
注意
PrintWriter writer = resp.getWriter();获取的流的默认编码为ISO-8859-1
设置该流的默认编码
告诉浏览器响应体使用的编码
简单的设置编码形式是在获取流之前设置
resp.setContentType(“text/html;charset=utf-8”);
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html;charset=utf-8");
PrintWriter writer = resp.getWriter();
writer.write("你好世界 hollow word");
}
验证码
本质:图片
目的:防止恶意表单注册
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
BufferedImage image = new BufferedImage(200, 100, BufferedImage.TYPE_INT_RGB);//创建一个存储图片的对象
Graphics graphics = image.getGraphics();//获取画笔对象
String s="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
graphics.setColor(Color.magenta);//设置画笔颜色
graphics.fillRect(1,1,199,99);//填充矩形颜色
graphics.setColor(Color.blue);
graphics.drawRect(0,0,200,100);//画矩形
Random random = new Random();
for(int i=0;i<4;i++)
{
int n=random.nextInt(s.length());
char c = s.charAt(n);
graphics.drawString(c+" ",25+i*50,50);
}
graphics.setColor(Color.CYAN);
for (int i=0;i<5;i++)
{
int x1=random.nextInt(200);
int x2=random.nextInt(200);
int y1=random.nextInt(100);
int y2=random.nextInt(100);
graphics.drawLine(x1,y1,x2,y2);
}
ImageIO.write(image,"jpg",resp.getOutputStream());//将、图片输出到页面显示
}