java web登录界面中添加验证码

引言:Java web登录界面中添加验证码

1、前端HTML页面部分

登陆
验证码

2、后端controller代码

public void check(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
	        	Long time=System.currentTimeMillis();
		        //通知浏览器不要缓存
	            response.setHeader("Content-type", "text/html;charset=UTF-8");  
				response.setHeader("Expires", "-1");
				response.setHeader("Cache-Control", "no-cache");
				response.setHeader("Pragma", "-1");
				response.setDateHeader("Last-Modified", time);
				response.setDateHeader("Date", time);
				response.setDateHeader("Expires", 0);
			//	response.getWriter().write(  
			  //              "恭喜您登录成功,将在3秒后跳转到首页,如果没有跳转,请点击超链接");  
				int height=33;
				int width=90;
				//得到一个内存图像BufferedImage
				BufferedImage img=new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
				//得到一个画笔
				Graphics g=img.getGraphics();
				//画边框drawRect绘制指定矩形的边框。
				g.drawRect(0, 0, width, height);
				//填充颜色
				g.setColor(Color.gray);
				g.fillRect(1, 1, width-2, height-2);
				//画干扰线
				g.setColor(Color.BLACK);
				Random r=new Random();
				for(int i=0;i<20;i++)
				g.drawLine(r.nextInt(width), r.nextInt(height), r.nextInt(width), r.nextInt(height));
				//生成随机数字
				g.setColor(Color.RED);
				g.setFont(new Font("微软雅黑", Font.BOLD|Font.ITALIC, 20));//BOLD加粗,ITALIC斜体
				int d=15;
				StringBuffer sb=new StringBuffer();//可变字符串的利用
				for(int j=0;j<4;j++){
					String code=r.nextInt(10)+"";
					sb.append(code);
					g.drawString(code+"", d, 20);
					d+=20;
				}
				//将验证码输入到session中,用来验证
				request.getSession().setAttribute("checkcode", sb.toString());
				//输出打web页面
				ImageIO.write(img, "jpg", response.getOutputStream());
	}
展示结果



你可能感兴趣的:(java基础)