生活随笔
收集整理的這篇文章主要介紹了
Response_案例4_验证码_点击切换
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
驗(yàn)證碼
?? ?1. 本質(zhì):圖片
?? ?2. 目的:防止惡意表單注冊(cè)
?
package com.learn.web.servlet;import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;@WebServlet("/checkCodeServlet")
public class CheckCodeServlet extends HttpServlet {protected void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {int width = 100;int height = 50;//1.創(chuàng)建一對(duì)象,在內(nèi)存中圖片(驗(yàn)證碼圖片對(duì)象)BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);//2.美化圖片//2.1 填充背景色Graphics g = image.getGraphics();//畫筆對(duì)象g.setColor(Color.PINK);//設(shè)置畫筆顏色g.fillRect(0,0,width,height);//2.2畫邊框g.setColor(Color.BLUE);g.drawRect(0,0,width - 1,height - 1);String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghigklmnopqrstuvwxyz0123456789";//生成隨機(jī)角標(biāo)Random ran = new Random();for (int i = 1; i <= 4; i++) {int index = ran.nextInt(str.length());//獲取字符char ch = str.charAt(index);//隨機(jī)字符//2.3寫驗(yàn)證碼g.drawString(ch+"",width/5*i,height/2);}//2.4畫干擾線g.setColor(Color.GREEN);//隨機(jī)生成坐標(biāo)點(diǎn)for (int i = 0; i < 10; i++) {int x1 = ran.nextInt(width);int x2 = ran.nextInt(width);int y1 = ran.nextInt(height);int y2 = ran.nextInt(height);g.drawLine(x1,y1,x2,y2);}//3.將圖片輸出到頁(yè)面展示ImageIO.write(image,"jpg",response.getOutputStream());}protected void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {this.doPost(request,response);}
}
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Title</title><script>/*分析:點(diǎn)擊超鏈接或者圖片,需要換一張1.給超鏈接和圖片綁定單擊事件2.重新設(shè)置圖片的src屬性值*/window.onload = function(){//1.獲取圖片對(duì)象var img = document.getElementById("checkCode");//2.綁定單擊事件img.onclick = function(){//加時(shí)間戳var date = new Date().getTime();img.src = "/day15/checkCodeServlet?"+date;}}</script></head>
<body><img id="checkCode" src="/day15/checkCodeServlet" /><a id="change" href="">看不清換一張?</a></body>
</html>
?
總結(jié)
以上是生活随笔為你收集整理的Response_案例4_验证码_点击切换的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。