欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Servlet中的response

程序员文章站 2022-04-16 07:49:01
向response中写数据的两种方法:getOutputStream(),getWriter()文件下载:图片认证:BufferedImage image = new BufferedImage(WIDTH,HEIGHT,TYPE_INT_RGB)Graphics g =image.getGraphics()setBackGround(g) //设置背景色setBorder(g) //设置边框drawRandomLine(g) //画干扰线drawRandomNum((...

向response中写数据的两种方法getOutputStream(),getWriter()
Servlet中的responseServlet中的response
Servlet中的response
文件下载:

Servlet中的response
图片认证:

public class VerificationServlet extends HttpServlet {
	private static final int WIDTH = 120;
	private static final int HEIGHT = 25;
       
   
	protected void doGet(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		
		BufferedImage image = new BufferedImage(WIDTH,HEIGHT,BufferedImage.TYPE_INT_RGB);

		Graphics g =image.getGraphics();

		setBackGround(g);  //设置背景色

         setBorder(g);  //设置边框

		drawRandomLine(g);  //画干扰线

		drawRandomNum((Graphics2D)g);  //写随机数

		//图形写给浏览器
		response.setContentType("image/jpeg");

		//发头控制浏览器不要缓存
		response.setDateHeader("expries",-1);
		response.setHeader("Cache-Control","no-cache");
		response.setHeader("Pragma","no-cache");
		ImageIO.write(image,"jpg",response.getOutputStream() );
	}
		private void setBackGround(Graphics g)
		{
		   g.setColor(Color.WHITE);
		   g.fillRect(0,0,WIDTH,HEIGHT);  //填充指定的矩形
		}

		private void setBorder(Graphics g)
		{
		   g.setColor(Color.BLUE);
		   g.drawRect(1,1,WIDTH-2,HEIGHT-2); //绘制指定矩形的边框
		}

		private void drawRandomLine(Graphics g)
		{
		    g.setColor(Color.GREEN);
		    for(int i=0;i<5;i++)
		  {
		    int x1=new Random().nextInt(WIDTH);  //起始
		    int y1=new Random().nextInt(HEIGHT);

		   int x2=new Random().nextInt(WIDTH);  //终点
		   int y2=new Random().nextInt(HEIGHT);
		   g.drawLine(x1,y1,x2,y2);  //画一条线
		  }
		}

		private void drawRandomNum(Graphics2D g)
		{
		  g.setColor(Color.RED);
		  g.setFont(new Font("宋体",Font.BOLD,20));
		  String base="    ";
		 int x=10;
		  for(int i=0;i<4;i++)
		  {
		   int degree =new Random().nextInt()%30;  //随机生成-30到30之间的数
		    String ch=base.charAt(new Random().nextInt(base.length() ) )+"";
		    g.rotate(degree*Math.PI/180,x,20);  //设置旋转弧度
		    g.drawString(ch,x,20);
		    x=+30;
		  }
		}

控制浏览器缓存时间:

response.setDateHeader("expires",System.currentTimeMillis()+1000*3600)  
//控制浏览器缓存,并设置缓存过期时间。System.currentTimeMillis()返回以毫秒为单位的当前时间,1000*3600指一小时

本文地址:https://blog.csdn.net/weixin_45647970/article/details/107367147