当前位置:   article > 正文

Java实现登陆校验码_java数字登录校验码

java数字登录校验码

Java实现登陆校验码

在做Javaweb的时候,一般会在登陆页面中添加一个校验码,就是为了方式机器恶意的进行登陆。

首先,看看前端页面怎么编写。

<div class="default" >
  <input id="user_input_verifyCode"name="user_input_verifyCode"
         value="${user_input_verifyCode}"  type="text" placeholder="验证码 " />
    <div class="vcode" id="vcodeDiv">
    		<img id="verifyCodeImage" title="验证码看不清?点击获取新验证码" src="" 				     οnclick="getValidateCode()" />
	 			<a id="changeVerifImageRegister" href="javascript:void(0);"  οnclick="javascript:changeImage();" title="验证码看不清?点击获取新验证码">看不清图片?</a>
		 		<input name="code" type="hidden" id="code" value="dologin" />
 	</div>
 </div> 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

图片上添加一个点击函数,每点击一次,就更换一次

 <script type="text/javascript">
 //当项目第一次运行时,验证码类没有被请求,因此是这没有被生成验证码的,所以人为对发送一次请求,保证页面刷新后能出现验证码
 var num=1;
$(function(){
       $('#verifyCodeImage').attr('src','${pageContext.request.contextPath }/checkCode?num='+num);
});	
</script> 
<script type="text/javascript">
  // 这是一个获取时间的函数
function genTimestamp() {    
    var time = new Date();    
    return time.getTime();    
} 
function changeImage() {
     $('#verifyCodeImage').attr('src',
             '${pageContext.request.contextPath }/checkCode?timestamp=' + genTimestamp());
 }
// 在请求的后面加上时间,是为了让每次请求都不一样,不然浏览器就不会向服务器发送请求,直接从缓存中获取请求的值。
</script> 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

后台数据controller

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


import org.apache.commons.io.output.ByteArrayOutputStream;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class VerificationCodeController {
	
  @Autowired
	@Qualifier("AhualyService")
	private AhualyService ahualyservice;
	@RequestMapping(value="/checkCode")

	/**
	 * 获取验证码
	 */
	@ResponseBody
	public void toCreateCode(HttpServletRequest request,HttpServletResponse response,HttpSession session,Integer num) throws IOException {
		
			ByteArrayOutputStream output = new ByteArrayOutputStream();
			ServletOutputStream out = null;
			drawImg(output,session);
			try {
				 
				 out = response.getOutputStream();
				  output.writeTo(out);
	             
			} catch (IllegalStateException e) {
				e.printStackTrace();
			}
		}
	 
		/**
		 * 绘画验证码
		 */
		private String drawImg(ByteArrayOutputStream output,HttpSession session) {
			Random random = new Random();
			String code = "";
			// 随机产生5个字符
			for (int i = 0; i < 5; i++) {
				code += randomChar();
			}
			// 定义图片的宽度和高度
	        int width = (int) Math.ceil(5 * 20);
	        int height = 30;
	        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
	        // 获取图片的上下文
	        Graphics gr = image.getGraphics();
	        // 设定图片背景颜色
	        gr.setColor(Color.WHITE);
	        gr.fillRect(0, 0, width, height);
	        // 设定图片边框
	        gr.setColor(Color.GRAY);
	        gr.drawRect(0, 0, width - 1, height - 1);
	        // 画十条干扰线
	        for (int i = 0; i < 5; i++) {
	            int x1 = random.nextInt(width);
	            int y1 = random.nextInt(height);
	            int x2 = random.nextInt(width);
	            int y2 = random.nextInt(height);
	            gr.setColor(randomColor());
	            gr.drawLine(x1, y1, x2, y2);
	        }
	        // 设置字体,画验证码
	        gr.setColor(randomColor());
	        gr.setFont(randomFont());
	        gr.drawString(code, 10, 22);
	        // 图像生效
	        gr.dispose();
	       // 输出到页面
			try {
        //将验证码保存到session中,为登陆的时候做校验使用
				session.setAttribute("code",code.toLowerCase());
				System.out.println("session=="+session.getAttribute("code"));
				ImageIO.write(image, "jpg", output);
			} catch (IOException e) {
				e.printStackTrace();
			}
			return code;
		}
	 
		/**
		 * 随机参数一个字符
		 */
		private char randomChar() {
			Random r = new Random();
			String s = "abcdefghjkmnprstuvwxyzABCDEFGHJKMNPRSTUVWXYZ23456789";
			return s.charAt(r.nextInt(s.length()));
		}
	    // 生成随机的颜色
	    private Color randomColor() {
	        int red = r.nextInt(150);
	        int green = r.nextInt(150);
	        int blue = r.nextInt(150);
	        return new Color(red, green, blue);
	    }
	    
	    private String[] fontNames = { "宋体", "华文楷体", "黑体", "微软雅黑", "楷体_GB2312" };
	    private Random r = new Random();

	    // 生成随机的字体
	    private Font randomFont() {
	        int index = r.nextInt(fontNames.length);
	        String fontName = fontNames[index];// 生成随机的字体名称
	        int style = r.nextInt(4);
	        int size = r.nextInt(3) + 24; // 生成随机字号, 24 ~ 28
	        return new Font(fontName, style, size);
	    }
}
	
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126

通过以上步骤就可以实现前端登陆验证码的绘制了。

登陆的时候,前端传入的值中带有验证码,后端需要判断

if(!user_input_verifyCode.toLowerCase().equals(session.getAttribute("code"))){
				mv.addObject("message", "验证码错误!请重新输入!!!");
				// 服务器内部跳转到登录页面
				mv.setViewName("forward:/loginForm");
	}
  • 1
  • 2
  • 3
  • 4
  • 5

以上就是完整的步骤了。下面是一张效果图。
在这里插入图片描述

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小小林熬夜学编程/article/detail/543088
推荐阅读
相关标签
  

闽ICP备14008679号