完成重定向
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("demo1....");
//访问ResponseDemo1资源会跳转到ResponseDemo2资源
//设置状态码为302
response.setStatus(302);
//设置状态码
response.setHeader("location", "/Resp/ResponseDemo2");
//简单的重定向方法
response.sendRedirect("/Resp/ResponseDemo2");
}
重定向的特点:(redirect)
1,地址栏发生变化
2,重定向可以访问其他站点的资源
3,重定向是两次请求
转发的特点:(forward)
1,转发地址栏路径不变
2,转发只能访问当前服务器下的资源
3,转发是一次请求,可以使用request对象共享数据
路径写法:
相对路径:
通过相对路径不可以确定唯一资源。
./:当前目录
…/:后退一级目录
规则:找到当前资源和目标资源之间的相对位置关系
绝对路径:
通过绝对路径可以确定唯一资源。
以/开头的路径
规则:判断定义的路径给谁用的?
给客户端浏览器用:需要加虚拟目录
a,from,重定向
给服务器使用:不需要虚拟目录
String path = request.getContextPath(); //getContextPath()获取虚拟目录
response.sendRedirect(path+"/ResponseDemo2");
服务器输出字符数据到浏览器
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// //1,获取流对象之前,设置流的默认编码
response.setContentType("text/html;charset=utf-8");
// response.setHeader("content-type", "text/html;charset=utf-8");
//2,获取字符输出流
PrintWriter pw = response.getWriter();
//,输出数据
pw.write("<h1>Hello response 你好<h1>");
}
注意:设置该流的默认编码,以及告诉浏览器使用的编码。
服务器输出字节数据到浏览器
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
//获取字节输出流
ServletOutputStream sos = response.getOutputStream();
//输出数据
sos.write("你好".getBytes());
}
验证码
1,本质: 图片
2,目的:防止恶意表单注册
int width=100;
int height=50;
//创建一个对象,在内存中代表一个图片(验证码图片对象)
BufferedImage image=new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
//美化图片
Graphics g = image.getGraphics();
//填充颜色
g.setColor(Color.PINK);
g.fillRect(0, 0, width, height);
//化边框
g.setColor(Color.BLUE);
g.drawRect(0, 0, width-1, height-1);
//写验证码
String str = "ABCDEFGHIJKLMNOPQRSTUVMXYZabcdefghihgklmnopqrstuvmxyz0123456789";
//生产随机角标
Random ran=new Random();
for(int i =1 ; i <=4 ; i++) {
int index = ran.nextInt(str.length());
//获取字符
char ch = str.charAt(index);
g.drawString(ch+"", width/5*i, height/2);
}
//画干扰线
g.setColor(Color.GREEN);
for(int i= 0;i<10 ;i ++) {
int x1 = ran.nextInt(width);
int x2 = ran.nextInt(width);
int y1 = ran.nextInt(height);
int y2 = ran.nextInt(height);
g.drawLine(x1,y1,x2,y2);
}
//将图片输出到页面展示
ImageIO.write(image, "jpg", response.getOutputStream());
//html页面测试
<body>
<img id="checkCode" alt="" src="/Resp/checkCodeServlet">
<a id="change" href="http://localhost/Resp/resgister.html">看不清换一张?</a>
</body>
<script type="text/javascript">
window.onload=function(){
var img=document.getElementById("checkCode");
img.onclick=function(){
var date = new Date().getTime();
img.src="/Resp/checkCodeServlet?"+date;
}
}
</script>