JAVA實現註冊頁面驗證碼重新整理
阿新 • • 發佈:2018-11-15
撰寫人——軟體二班——陳喜平
需要的工具:tomcat/eclipse/jdk/(注意jdk版本要和tomca相匹配,以及注意區分32位和64位)
步驟:依次建立servlet (伺服器需要)/ jsp(頁面需要)
引入web.xml
如圖所示:
doget方法裡面的程式碼:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub //response.getWriter().append("Served at: ").append(request.getContextPath()); int width=158; int height=30; // 1、首先將畫布畫出來 BufferedImage buffIMG=new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR); //建立畫筆 Graphics2D g2d=(Graphics2D) buffIMG.getGraphics(); // 畫筆顏色 g2d.setColor(Color.white); // 設定字型 g2d.setFont(new Font("宋體",Font.BOLD,15)); Random rd=new Random(); // 拿到字串 String word="asdfghjklzxcvbnmqwertyuiop1234567890"; // 3.將字串畫到畫布上 int x=25; int y=25; for(int i=0;i<4;i++) { int index =rd.nextInt(word.length()); char ch = word.charAt(index); int jiaodu=rd.nextInt(30)-15; double hudu=jiaodu*Math.PI/180; g2d.rotate(hudu,x,y); g2d.drawString(ch+" ", x, y); x+=9.5; g2d.rotate(-hudu, x, y); } int x1,x2,y1,y2; for(int j=0;j<3;j++) { g2d.setColor(Color.green); x1=rd.nextInt(width); x2=rd.nextInt(width); y1=rd.nextInt(height); y2=rd.nextInt(height); g2d.drawLine(x1, y1, x2, y2); } // 4.將驗證碼的圖片顯示在頁面上 ImageIO.write(buffIMG, "jpg", response.getOutputStream()); }
web.xml需要新增的程式碼
<servlet> <!-- 服務名 --> <servlet-name>myservlet</servlet-name> <!-- 服務名所在的路徑 --> <servlet-class>com.teach.servlet.myservlet</servlet-class> </servlet> <servlet-mapping> <!-- 服務名 --> <servlet-name>myservlet</servlet-name> <!-- url請求名--> <url-pattern>/hello</url-pattern> </servlet-mapping>
全部程式碼壓縮包
連結:https://pan.baidu.com/s/1ItnylRntamGMsZp0lp6MSA
提取碼:eoal
成果圖: