图片验证码,数字大小写字母组合,session验证

登陆时常用的验证码,用于防止恶意注册等操作。

先是HTML代码,一个简单的登陆页面,在注册码处显示生成的注册码图片。

<html>
  <head>
    <title>RandomNum.html</title>
    <!-- 点击图片时进行验证码的切换 -->
    <script type="text/javascript">
    <span style="white-space:pre">	</span>function changeImage(img){
    <span style="white-space:pre">		</span>img.src = img.src + "?" + new Date().getTime();//防止浏览器缓存
    <span style="white-space:pre">	</span>}
    </script>
  </head>
 <span style="white-space:pre">	</span><body>
    <form action="/JavaWebLearn/servlet/LoginServlet" method="post">
    <span style="white-space:pre">	</span>用户名:<input type="text" name="username"><br/> 
    <span style="white-space:pre">	</span>密码:<input type="password" name="password"><br/> 
    <span style="white-space:pre">	</span>认证码:<input type="text" name="checkcode">
    <span style="white-space:pre">	</span><img alt="换一张" style="cursor: hand" src="/JavaWebLearn/servlet/RandomImg" οnclick="changeImage(this)">
    <span style="white-space:pre">	</span><br>
    <span style="white-space:pre">	</span><input type="submit" value="登陆"/>
    </form>
<span style="white-space:pre">	</span></body>
</html>
插入的图片除 src="/JavaWebLearn/servlet/RandomImg"返回RandomImg产生的随机验证码

下面是RandomImg(Servlet)代码

public class RandomImg extends HttpServlet {
<span style="white-space:pre">	</span>public static final int WIDTH = 120;//设置图片的宽度
<span style="white-space:pre">	</span>public static final int HEIGHT = 25;//设置图片的高度
<span style="white-space:pre">	</span>public void doGet(HttpServletRequest request, HttpServletResponse response)
<span style="white-space:pre">			</span>throws ServletException, IOException {
<span style="white-space:pre">		</span>BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
<span style="white-space:pre">		</span>Graphics g = image.getGraphics();
<span style="white-space:pre">		</span>
<span style="white-space:pre">		</span>//1.设置背景色
<span style="white-space:pre">		</span>setBackGround(g);
<span style="white-space:pre">		</span>//2.设置边框
<span style="white-space:pre">		</span>setBorder(g);
<span style="white-space:pre">		</span>//3.画干扰线
<span style="white-space:pre">		</span>drawRandomLine(g);
<span style="white-space:pre">		</span>//4.写随机数
<span style="white-space:pre">		</span>String imgcheckcode = drawRandomNum(g);
<span style="white-space:pre">		</span>//将产生的随机验证码存入到session中
<span style="white-space:pre">		</span>request.getSession().setAttribute("imgcheckcode", imgcheckcode);
<span style="white-space:pre">		</span>//5.图形写给浏览器
<span style="white-space:pre">		</span>response.setContentType("image/jpeg");
<span style="white-space:pre">		</span>//发头,控制浏览器不要缓存
<span style="white-space:pre">		</span>response.setDateHeader("expries", -1);
<span style="white-space:pre">		</span>response.setHeader("Cache-Control", "no-cache");
<span style="white-space:pre">		</span>response.setHeader("Pragma", "no-cache");
<span style="white-space:pre">		</span>ImageIO.write(image, "jpg", response.getOutputStream());


<span style="white-space:pre">	</span>}

<span style="white-space:pre">	</span>private String drawRandomNum(Graphics g) throws UnsupportedEncodingException {
<span style="white-space:pre">		</span>g.setColor(Color.RED);
<span style="white-space:pre">		</span>g.setFont(new Font("宋体", Font.BOLD, 20));
<span style="white-space:pre">		</span>
<span style="white-space:pre">		</span>int x = 5;
<span style="white-space:pre">		</span>StringBuffer sb = new StringBuffer();
        for (int i = 0; i < 4; i++) {
        <span style="white-space:pre">	</span>String ch = getCharAndNumr(1);
        <span style="white-space:pre">	</span>sb.append(ch);
            g.drawString(ch, x, 20);
            x+=30;
        }
<span style="white-space:pre">		</span>return sb.toString();
<span style="white-space:pre">	</span>}
<span style="white-space:pre">	</span>
<span style="white-space:pre">	</span>private void drawRandomLine(Graphics g) {
<span style="white-space:pre">		</span>g.setColor(Color.GREEN);
<span style="white-space:pre">		</span>
<span style="white-space:pre">		</span>for(int i=0;i<4;i++){
<span style="white-space:pre">			</span>int x1 = new Random().nextInt(WIDTH-2);
<span style="white-space:pre">			</span>int y1 = new Random().nextInt(HEIGHT-2);
<span style="white-space:pre">			</span>
<span style="white-space:pre">			</span>int x2 = new Random().nextInt(WIDTH-2);
<span style="white-space:pre">			</span>int y2 = new Random().nextInt(HEIGHT-2);
<span style="white-space:pre">			</span>
<span style="white-space:pre">			</span>g.drawLine(x1, y1, x2, y2);
<span style="white-space:pre">		</span>}
<span style="white-space:pre">	</span>}

<span style="white-space:pre">	</span>private void setBorder(Graphics g) {
<span style="white-space:pre">		</span>g.setColor(Color.BLUE);
<span style="white-space:pre">		</span>g.drawRect(1, 1, WIDTH-2, HEIGHT-2);
<span style="white-space:pre">	</span>}

<span style="white-space:pre">	</span>private void setBackGround(Graphics g) {
<span style="white-space:pre">		</span>g.setColor(Color.WHITE);
<span style="white-space:pre">		</span>g.fillRect(0, 0, WIDTH, HEIGHT);
<span style="white-space:pre">	</span>}

<span style="white-space:pre">	</span>public void doPost(HttpServletRequest request, HttpServletResponse response)
<span style="white-space:pre">			</span>throws ServletException, IOException {
<span style="white-space:pre">		</span>doGet(request, response);
<span style="white-space:pre">	</span>}
<span style="white-space:pre">	</span>
<span style="white-space:pre">	</span>//生成任意长度的大小写字母数字组成的随机码
<span style="white-space:pre">	</span>public static String getCharAndNumr(int length) {
        String val = "";
        Random random = new Random();
        for (int i = 0; i < length; i++) {
            // 输出字母还是数字
            String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num"; 
            // 字符串
            if ("char".equalsIgnoreCase(charOrNum)) {
                // 取得大写字母还是小写字母
                int choice = random.nextInt(2) % 2 == 0 ? 65 : 97; 
                val += (char) (choice + random.nextInt(26));
            } else if ("num".equalsIgnoreCase(charOrNum)) { // 数字
                val += String.valueOf(random.nextInt(10));
            }
        }
        return val;
    }

}
至此,程序结束。运行效果为

然后点击提交,将验证码传入Servlet处理
public class LoginServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//处理请求之前,判断验证码是否正确
		String checkcode = request.getParameter("checkcode");
		String imgcheckcode = (String) request.getSession().getAttribute("imgcheckcode");
		if(!"".equals(checkcode)){
			if(checkcode.equals(imgcheckcode)){
				System.out.println("正确");
				System.out.println(checkcode+"---"+imgcheckcode);
			}else{
				System.out.println("错误");
				return;
			}
		}else{
			return;
		}
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}






 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值