Response对象:
功能:设置响应消息
1,设置响应行
1,格式:HTTP/1.0 200 OK
2,设置状态码:setStatus(int sc)
2,设置响应头
3,设置响应体
使用步骤:
1,获取输出流
字符输出流:printWriter getWriter()
字节输出流:ServletOutpStream getOutputStream()
2,使用输出流,将数据输出到客户端浏览器
案例:
1,完成重定向
重定向:资源跳转的方式
代码实现:
System.out.println("demo1");
//设置状态码
response.setStatus(302);
//设置响应头location
response.setHeader("location","/ServletTest_war_exploded/responesDemo2");
//简单的重定向方法:
response.sendRedirect("/ServletTest_war_exploded/responesDemo2");
重定向的特点:redirect
1,地址栏发生变化
2,重定向可以访问其他站点(服务器)资源
3,重定向是两次请求。不能使用request来共享资源
转发特点:forward
1,转发地址栏路径不变
2,转发只能访问当前服务器下的资源
3,转发是一次请求,可以使用request对象来共享数据
(面试笔试):forward和redirect区别(实际上就是转发和重定向的区别)
路径写法:
1,路径分类
1,相对路径:通过相对l路径不可以确定唯一资源
如:./index.html
不以/开头,以.开头
规则:找到当前资源和目标资源之间的相对位置关系
./:当前路径
../:后退一级目录
2,绝对路径:通过绝对路径可以确定唯一资源
如:http://localhost/one/response
以/开头
规则:判断定义的路径是给谁用的?判断请求将来从哪儿发出
给客户端浏览器使用:需要加虚拟目录(项目的访问路径)
建议虚拟目录动态获取:request.getContextPath()
<a>,<form>
给服务器使用:不需要加虚拟目录
转发路径
2,服务器输出字符数据到浏览器
步骤:
1,获取字符输出流
2,输出字段
注意:
乱码问题:
1,PrintWriter pw = response.getWriter();获取流的默认编码是ISO-8895-1
2,设置该流的默认编码
3,告诉浏览器响应体使用的编码
代码:
//简单形式设置编码,在获取流之前设置
response.setContentType("text/html;charset=utf-8");
PrintWriter pw = response.getWriter();
pw.write("你好,盛哥");
3,服务器输出字节数据到浏览器
response.setContentType("text/html;charset=utf-8");
ServletOutputStream sos = response.getOutputStream();
sos.write("hello".getBytes());
4,验证码
//验证码
int height=50;
int width=100;
//1,创建一对象,在内存中图片(验证码图片对象)
BufferedImage image=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
//美化图片
//1,填充背景色
Graphics g=image.getGraphics();//画笔对象
g.setColor(Color.pink);
g.fillRect(0,0,width-1,height-1);//填充
//2,生成随机字符
g.setColor(Color.black);
String str="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
Random random=new Random();
for(int i=1;i<=4;i++){
int k = random.nextInt(str.length());
char c = str.charAt(k);
g.drawString(c+"",100/5*i,height/2);
}
//3,画干扰线
g.setColor(Color.GREEN);
for(int i=0;i<10;i++){
int x1=random.nextInt(width);
int x2=random.nextInt(width);
int y1=random.nextInt(height);
int y2=random.nextInt(height);
g.drawLine(x1,x2,y1,y2);
}
//将图片输出到页面展示
ImageIO.write(image,"jpg",response.getOutputStream());
点击图片,图片刷新:
(html)
<title>Title</title>
<script>
/*
分析:
点击超链接或图片,需要h换一张
1,给超链接和图片绑定单击事件
2,重新设置图片的src属性值
*/
window.onload=function () {
var img = document.getElementById("checkCode");
img.onclick=function () {
//时间戳
var date=new Date().getTime();
img.src="/ServletTest_war_exploded/responseDemo2?"+date;
}
}
</script>
</head>
<body>
<img id="checkCode" src="/ServletTest_war_exploded/responseDemo2">
<a id="change" href="">看不清,换一张?</a>
</body>