码迷,mamicode.com
首页 > Web开发 > 详细

简单Maven的Web项目之验证码

时间:2015-07-26 06:14:16      阅读:150      评论:0      收藏:0      [点我收藏+]

标签:web   maven   验证码   serblet   

一:用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>

效果图如下
技术分享

版权声明:本文为博主原创文章,未经博主允许不得转载。

简单Maven的Web项目之验证码

标签:web   maven   验证码   serblet   

原文地址:http://blog.csdn.net/gao36951/article/details/47063011

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!