JavaWeb开发常用工具类

JavaWeb开发常用工具类

图片验证码

package cn.liuweiwei.utils;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Random;
import javax.imageio.ImageIO;
/**
 * 动态生成图片
 */
public class VerificationCode {
    // {"宋体", "华文楷体", "黑体", "华文新魏", "华文隶书", "微软雅黑", "楷体_GB2312"}
    private static String[] fontNames = { "宋体", "华文楷体", "黑体", "微软雅黑",  "楷体_GB2312" };
    // 可选字符
    //"23456789abcdefghjkmnopqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ";
    private static String codes = "23456789abcdefghjkmnopqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ";
    // 背景色
    private Color bgColor = new Color(255, 255, 255);
    // 基数(一个文字所占的空间大小)
    private int base = 30;
    // 图像宽度
    private int width = base * 4;
    // 图像高度
    private int height = base;
    // 文字个数
    private int len = 4;
    // 设置字体大小
    private int fontSize = 22;
    // 验证码上的文本
    private String text;
    //图片的缓冲流
    private BufferedImage img = null;
    //画笔
    private Graphics2D g2 = null;

    /**
     * 生成验证码图片
     * @param outputStream 传入一个输出流,就是将该图片输出到哪里
     */
    public void drawImage(OutputStream outputStream) {
        // 1.创建图片缓冲区对象, 并设置宽高和图像类型
        img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        // 2.得到绘制环境
        g2 = (Graphics2D) img.getGraphics();
        // 3.开始画图
        // 设置背景色
        g2.setColor(bgColor);
        //设置画笔的开始位置,0,0代表左上角
        g2.fillRect(0, 0, width, height);

        StringBuffer sb = new StringBuffer();// 用来装载验证码上的文本

        for (int i = 0; i < len; i++) {
            // 设置画笔颜色 -- 随机
            // g2.setColor(new Color(255, 0, 0));
            g2.setColor(new Color(getRandom(0, 150), getRandom(0, 150),getRandom(0, 150)));

            // 设置字体
            g2.setFont(new Font(fontNames[getRandom(0, fontNames.length)], Font.BOLD, fontSize));

            // 旋转文字(-45~+45)
            int theta = getRandom(-45, 45);
            g2.rotate(theta * Math.PI / 180, 7 + i * base, height - 8);

            // 写字
            String code = codes.charAt(getRandom(0, codes.length())) + "";
            g2.drawString(code, 7 + i * base, height - 8);
            sb.append(code);
            g2.rotate(-theta * Math.PI / 180, 7 + i * base, height - 8);
        }

        this.text = sb.toString();

        // 画干扰线
        for (int i = 0; i < len + 2; i++) {
            // 设置画笔颜色 -- 随机
            // g2.setColor(new Color(255, 0, 0));
            g2.setColor(new Color(getRandom(0, 150), getRandom(0, 150),
                                  getRandom(0, 150)));
            g2.drawLine(getRandom(0, 120), getRandom(0, 30), getRandom(0, 120),
                        getRandom(0, 30));
        }
        //绘制边框
        g2.setColor(Color.GRAY);
        //0,0是坐标值,左上角是0,0坐标,宽高都-1为了比矩形小一点,看着好看一些
        g2.drawRect(0, 0, width-1, height-1);

        // 4.保存图片到指定的输出流
        try {
            ImageIO.write(this.img, "JPEG", outputStream);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }finally{
            // 5.释放资源
            g2.dispose();
        }
    }

    /**
     * 获取验证码字符串
     * @return
     */
    public String getCode() {
        return this.text;
    }

    /*
     * 生成随机数的方法
     */
    private static int getRandom(int start, int end) {
        Random random = new Random();
        return random.nextInt(end - start) + start;
    }
    //测试
    public static void main(String[] args) throws Exception {
        VerificationCode code = new VerificationCode();
        code.drawImage(new FileOutputStream("f:/vc.jpg"));
        System.out.println("执行成功~!");
        System.out.println(code.getCode());
    }
}

QQ邮箱验证码工具类

// package cn.liuweiwei.util;

import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message.RecipientType;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class MailUtils {

	// 发送方邮箱地址
	private static String senderEmailAddress = "vivi.love.java@qq.com";
	// 发送邮件的标题
	private static String senderEmailHeader = "验证码";
	// 开启服务的授权码
	private static String authecticationPassword = "保密";

	/**
	 * 设置邮件的标题、默认为验证码
	 * 
	 * @param header
	 */
	public static void setEmailHeader(String header) {
		senderEmailHeader = header;
	}

	/**
	 * 发送邮件的方法
	 * 
	 * @param receiverEmailAdderss 接收方的邮箱地址
	 * @param emailMessage         要发送的邮件信息
	 * @throws Exception
	 */
	public static void sendMail(String receiverEmailAdderss, Object emailMessage) throws Exception {
		Properties properties = new Properties();
		properties.setProperty("mail.transport.protocol", "SMTP");
		properties.setProperty("mail.host", "smtp.qq.com");
		properties.setProperty("mail.smtp.auth", "true");

		Authenticator authenticator = new Authenticator() {
			@Override
			protected PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication(senderEmailAddress, authecticationPassword);
			}
		};
		Session session = Session.getInstance(properties, authenticator);
		MimeMessage message = new MimeMessage(session);
		message.setFrom(new InternetAddress(senderEmailAddress));
		message.setRecipient(RecipientType.TO, new InternetAddress(receiverEmailAdderss));
		message.setSubject(senderEmailHeader);
		message.setContent(emailMessage, "text/html;charset=utf-8");
		Transport.send(message);
	}

	// 测试
	public static void main(String[] args) throws Exception {
			sendMail("233@qq.com", "澳门赌场上线啦!!!");
	}

}

生成少量个数字符串的工具类

ps可以配合邮箱验证码使用

// package cn.liuweiwei.util;

import java.util.Random;

public class RandomCharsUtils {

	private static char[] chars = null;
	private static Random random = new Random();

	private RandomCharsUtils() {
	}

	static {
		initChars();
	}

	private static void initChars() {
		chars = "abcdefghijklmnopqrstuvwxyz0123456789".toCharArray();
	}

	public static String RandomChars(int number) {
		String result = "";
		for (int i = 0; i < number; i++) {
			result += chars[RandomIndex()];
		}
		return result;
	}

	private static int RandomIndex() {
		return random.nextInt(chars.length);
	}

}


发送邮箱验证码时需要开通qq邮箱相关的服务、自行百度解决

持续更新…

上一篇:java绘制五子棋棋盘


下一篇:XCTF logmein