JavaWeb开发常用工具类

这个博客分享了两个实用工具类,一个是用于生成JavaWeb动态图片验证码的类,包括设置字体、颜色、干扰线等功能;另一个是QQ邮箱发送验证码的工具类,涉及SMTP协议和授权码验证。此外,还提供了一个生成随机字符串的辅助类。
摘要由CSDN通过智能技术生成

图片验证码

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", "澳门赌场上线啦!!!");
	}

}

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


// 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邮箱相关的服务、自行百度解决

持续更新…

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值