response 响应对象 功能:
设置响应消息 1.设置响应行 格式:HTTP/1.1 状态码 设置:setStatus(int i)
设置响应头: setHeader(String name,String value) location : uri地址 重定向:资源的跳转的方式 1.完成重定向 *设置状态码为302 response.setStatus(302) *设置响应的location属性 response.setHeader("location","/day01/responseDemo2") 重定向的特点:
1.地址栏会发生改变
2.重定向可以访问其他服务器的资源
3.重定向是2次请求,不能使用request对象域进行数据共享
请求转发:
1.地址栏不会改变
2.只能访问当前服务器的资源
3.一次请求,可以使用request对象域进行数据共享
protected void doPost(HttpServletRequest request, HttpServletRespon
se response) throws ServletException, IOException {
System.out.println("demo1....");
//1.设置响应状态码
// 访问responseDemo1,会自动跳转到responseDemo2资源
//设置状态码为302
response.setStatus(302);
//2.设置响应头 location
response.setHeader("location","/day01/responseDemo2");
}
response对象提供简单的方法重定向
response.sendRedirect(String uri)
服务器输出字节流到浏览器中
response.getOutputStream();
protected void doPost(HttpServletRequest request, HttpServletRespon
se response) throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
//1.获取字节输出流
ServletOutputStream sos = response.getOutputStream();
//2.输出数据
sos.write("您好".getBytes("utf-8"));
}
验证码:当前服务器中生成一张随机图片
目的:防止恶意的表单访问
@WebServlet("/responseDemo7")
public class ResponseDemo7 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletRespon
se response) throws ServletException, IOException {
//验证码就是一张图片
int width = 100;
int height = 50;
//1.创建一个图片对象(内存中的图片)
BufferedImage image = new BufferedImage(width,height,BufferedIm
age.TYPE_INT_RGB);
//2.图片内容的添加
//2.1获取画笔工具
Graphics g = image.getGraphics();//获取绘制当前图片的画笔工具
//2.2设置图片的背景颜色
//2.2.1设置当前画笔的属性,当前画笔的颜色
g.setColor(Color.white);
g.fillRect(0,0,width,height);
//2.3绘制一个边框
g.setColor(Color.PINK);
g.drawRect(0,0,width-1,height-1);
//3.绘制要生成的文字
String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOQPRSTUVW
XYZ0123456789";
g.setFont(new Font("微软雅黑",Font.BOLD,30));
Random random = new Random();
for(int i = 1; i<=4 ; i++){
g.setColor(new Color(random.nextInt(255),random.nextInt(25
5),random.nextInt(255)));
int index = random.nextInt(str.length());
char ch = str.charAt(index);
//3.1将获取的每个元素写入到图片上
g.drawString(""+ch,width/5*i,height/4*3);
}
//3.2绘制一些干扰线
// g.drawLine(x,y,x1,y1);
for(int i = 0;i<5;i++){
g.setColor(new Color(random.nextInt(255),random.nextInt(25
5),random.nextInt(255)));
int x1 = random.nextInt(width);
int x2 = random.nextInt(width);
int y1 = random.nextInt(height);
int y2 = random.nextInt(height);
g.drawLine(x1,y1,x2,y2);
}
//4.将图片输出到网页中
ImageIO.write(image,"jpg",response.getOutputStream());
}
protected void doGet(HttpServletRequest request, HttpServletRespons
e response) throws ServletException, IOException {
this.doPost(request,response);
}
}