簡單Maven的Web項目之驗證碼,mavenweb驗證碼

來源:互聯網
上載者:User

簡單Maven的Web項目之驗證碼,mavenweb驗證碼
一:用Maven命令建立一個Web項目

建立命令如下:

mvn archetype:create -DgroupId=com.gao.web -DartifactId= VerifyCode -DarchetypeArtifactId=maven-archetype-webapp
  • 首先配置好maven環境,之前的部落格有說環境配置問題,然後在命令列運行上述命令,成功後如下

  • 然後運行下面命令將產生的maven項目轉化為elipse能識別的項目
mvn -Dwtpversion=1.0 eclipse:eclipse
二:開始編寫產生驗證碼的代碼
  • 首先將項目匯入elipse中
    產生驗證碼的Servlet代碼如下:
package com.niu.gao;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.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;/**   * @Description: (產生驗證碼Servlet)      * @author:relieved  * @date:2015-7-25 */public class GenerateCodeServlet extends HttpServlet {    /**     * serialVersionUID     */    private static final long serialVersionUID = 1L;    @Override    protected void doGet(HttpServletRequest req, HttpServletResponse resp)            throws ServletException, IOException {        //映像資料緩衝區  建構函式 第一個參數為寬 第二個參數為高  第三個為圖片類型        BufferedImage bi = new BufferedImage(100, 25, BufferedImage.TYPE_INT_RGB);        //繪製圖片        Graphics grap = bi.getGraphics();        //設定字型        Font f = new Font("宋體",Font.ITALIC ,20);         grap.setFont(f);        //背景顏色        Color color = new Color(200,160,255);        //設定背景顏色        grap.setColor(color);        grap.fillRect(0, 0, 100, 25);//座標  繪製圖片寬、高        //驗證碼內容        char[] content = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray();        Random ran = new Random();//根據隨機數來取組合驗證碼內容        int len = content.length,index;        StringBuffer generateCode = new StringBuffer();//儲存隨機產生的驗證碼        //產生6位的驗證碼        for(int i = 0;i<6;i++){            index = ran.nextInt(len);            //設定驗證碼顏色            grap.setColor(new Color(ran.nextInt(100), ran.nextInt(180),ran.nextInt(255)));            //將字元畫在畫板上            grap.drawString(content[index]+"", i*16+3, 19);            generateCode.append(content[index]);        }        //將產生的驗證碼放在session中以便之後驗證用到        req.getSession().setAttribute("verifyCode", generateCode.toString());        //將產生的驗證碼圖片輸出        ImageIO.write(bi, "PNG", resp.getOutputStream());    }    @Override    protected void doPost(HttpServletRequest req, HttpServletResponse resp)            throws ServletException, IOException {        this.doGet(req, resp);    }}

web.xml檔案配置如下

<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd" ><web-app>    <display-name>VerifyCode</display-name>    <servlet>        <servlet-name>generateCode</servlet-name>        <servlet-class>com.niu.gao.GenerateCodeServlet</servlet-class>    </servlet>    <servlet-mapping>        <servlet-name>generateCode</servlet-name>        <url-pattern>/generate/verifyCode.do</url-pattern>    </servlet-mapping>    <welcome-file-list>    <welcome-file>index.jsp</welcome-file>  </welcome-file-list></web-app>

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>VerifyCode</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">    <script type="text/javascript" src="jquery-1.9.1.js"></script>    <script type="text/javascript">        var path="<%=path%>";        $( document ).ready(function() {            $("#codeImg").on("click",function(){                $('#codeImg').prop('src',path+'/generate/verifyCode.do?nocache='+new Date().getTime());            });        });    </script>  </head><body style="text-align: center;"><h2>Hello World!</h2><span style="margin: 10px 0 0 10px;vertical-align: baseline;">請輸入驗證碼:<input name="verifyCode" type="text" /></span><img id="codeImg" style="vertical-align: bottom;;margin: 10px 0 0 10px;cursor: pointer;"  alt="驗證碼" src="<%=path%>/generate/verifyCode.do"></body></html>

如下

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.