利用Servlet生成动态验证码
生活随笔
收集整理的這篇文章主要介紹了
利用Servlet生成动态验证码
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
在Servlet中,設置響應正文的類型為image/jpeg,表示響應的是一個圖片,然后通過java.awt包中的操作圖形圖像的類來生成一個圖像
-
java.awt.image.BufferedImage:創(chuàng)建該對象時,會在緩存中構造一個圖像
-
java.awt.Graphics:該類的對象表示一個畫筆,用來話矩形,寫字,添加顏色
-
java.util.Random:該類的對象用于生成隨機輸
新建ValidateCodeServlet類public class ValidateCodeServlet extends HttpServlet {
/*** Constructor of the object.*/public ValidateCodeServlet() {super();}/*** Destruction of the servlet. <br>*/public void destroy() {super.destroy(); // Just puts "destroy" string in log// Put your code here}/*** The doGet method of the servlet. <br>** This method is called when a form has its tag value method equals to get.* * @param request the request send by the client to the server* @param response the response send by the server to the client* @throws ServletException if an error occurred* @throws IOException if an error occurred*/public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {this.doPost(request, response);}/*** The doPost method of the servlet. <br>** This method is called when a form has its tag value method equals to post.* * @param request the request send by the client to the server* @param response the response send by the server to the client* @throws ServletException if an error occurred* @throws IOException if an error occurred*/public Color getRandomColor(int fc,int bc){Random random = new Random();Color randomColor = null;if(fc>255) fc=255;if(bc>255) bc=255;//設置個0-255之間的隨機顏色值int r=fc+random.nextInt(bc-fc);int g=fc+random.nextInt(bc-fc);int b=fc+random.nextInt(bc-fc);randomColor = new Color(r,g,b);return randomColor;//返回具有指定紅色、綠色和藍色值的不透明的 sRGB 顏色}public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {//禁止頁面緩存response.setHeader("Pragma", "No-cache");response.setHeader("Cache-Control", "No-cache");response.setDateHeader("Expires", 0);response.setContentType("image/jpeg"); //設置響應正文的MIME類型為圖片int width=60, height=20; /**創(chuàng)建一個位于緩存中的圖像,寬度60,高度20 */ BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics g = image.getGraphics(); //獲取用于處理圖形上下文的對象,相當于畫筆Random random = new Random(); //創(chuàng)建生成隨機數(shù)的對象g.setColor(getRandomColor(200,250)); //設置圖像的背景色g.fillRect(0, 0, width, height); //畫一個矩形 ,坐標(0,0),寬度60,高度20 g.setFont(new Font("Times New Roman",Font.PLAIN,18)); //設定字體格式g.setColor(getRandomColor(160,200));for(int i=0;i<130;i++){ //產(chǎn)生130條隨機干擾線int x = random.nextInt(width); int y = random.nextInt(height); int xl = random.nextInt(12); int yl = random.nextInt(12); g.drawLine(x,y,x+xl,y+yl); //在圖象的坐標(x,y)和坐標(x+x1,y+y1)之間畫干擾線 } String strCode=""; for (int i=0;i<4;i++){ String strNumber=String.valueOf(random.nextInt(10)); //把隨機數(shù)轉換成String字符串strCode=strCode+strNumber;//設置字體的顏色g.setColor(new Color(15+random.nextInt(120),15+random.nextInt(120),15+random.nextInt(120)));g.drawString(strNumber,13*i+6,16); //將驗證碼依次畫到圖像上,坐標(x=13*i+6,y=16)}request.getSession().setAttribute("Code",strCode); //把驗證碼保存到Session中 g.dispose(); //釋放此圖像的上下文以及它使用的所有系統(tǒng)資源ImageIO.write(image, "JPEG", response.getOutputStream()); //輸出JPEG格式的圖像 response.getOutputStream().flush(); //刷新輸出流 response.getOutputStream().close(); //關閉輸出流 }/*** Initialization of the servlet. <br>** @throws ServletException if an error occurs*/public void init() throws ServletException {// Put your code here}}
index.jsp頁面
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html><head><base href="<%=basePath%>"><title>用戶注冊</title><meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"><meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"><meta http-equiv="description" content="This is my page"><!--<link rel="stylesheet" type="text/css" href="styles.css">--><style type="text/css">table{font-size:12px;font-family: 隸書;color:gray;border: 1px green solid;}input{font-size:12px;font-family: 隸書;color:gray;}</style></head><body><form action="" method="post"><table align="center"><tr><td>用戶名:</td><td><input type="text" name="name" /></td></tr><tr><td>密碼:</td><td><input type="password" name="pwd" /></td></tr><tr><td>性別:</td><td><input type="radio" name="sex" value="男" />男<input type="radio" name="sex" value="女" />女</td></tr><tr><td>年齡:</td><td><input type="text" name="age" /></td></tr><tr><td>Email:</td><td><input type="text" name="email" /></td></tr><tr><td>驗證碼:</td><td><img alt="" src="validatecode" ></td></tr><tr><td>輸入驗證碼:</td><td><input type="text" name="code"/></td></tr><tr><td colspan="2" align="center"><input type="submit" value="注 冊" /><input type="reset" value="重 置" /></td></tr></table></form></body> </html>web.xml文件配置
<servlet><description>This is the description of my J2EE component</description><display-name>This is the display name of my J2EE component</display-name><servlet-name>ValidateCodeServlet</servlet-name><servlet-class>com.lh.servlet.ValidateCodeServlet</servlet-class></servlet><servlet-mapping><servlet-name>ValidateCodeServlet</servlet-name><url-pattern>/validatecode</url-pattern></servlet-mapping><welcome-file-list><welcome-file>index.jsp</welcome-file></welcome-file-list>總結
以上是生活随笔為你收集整理的利用Servlet生成动态验证码的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 将数据到处到Excel
- 下一篇: Servlet实现的个人所得税计算器