一,Servlet生成图片验证码
第一步:创建一个生成图片的ImageServlet类
package com.lmc.servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class ImageServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
}
第二步:创建一个数据缓存图像对象
//其中width表示图像的宽度,height表示图像的高度,最后一个参数表示图像字节灰度图像
BufferedImage b = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY);
第三步:获取BufferedImage的绘制对象,再设置一些属性
//获取BufferedImage的绘制对象
Graphics g = b.getGraphics();
//绘制干扰线
for (int i = 0;i < 5; i++){
int x1 = random.nextInt(59);
int y1 = random.nextInt(29);
int x2 = random.nextInt(59);
int y2 = random.nextInt(29);
g.drawLine(x1,y1,x2,y2);
}
// 设置画笔的一些属性(比如颜色、字体风格、背景、前景色等等)
第四步:创建一个图片验证的jsp页面
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 19/7/26
Time: 14:00
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>图片验证</h1>
<img width="60px" height="30px" οnclick="changeImage(this)">
</body>
<script>
window.onload = function () {
document.getElementsByTagName("img")[0].src = "/lmc/image.do?time="+ new Date().getTime();;
}
function changeImage(e) {
e.src = "/lmc/image.do?time="+ new Date().getTime();
}
</script>
</html>
代码:
package com.lmc.servlet;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
public class ImageServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
//创建一个数据缓存图像对象
BufferedImage b = new BufferedImage (60, 30, BufferedImage.TYPE_BYTE_GRAY);
//创建字符源
String charSourses = "abcdefghijklmnopqrstuvwxyz0123456789";
String numStr = "";
Random random = new Random();
for (int i = 0;i < 4; i++){
int num = random.nextInt(charSourses.length() - 1);
numStr += charSourses.substring(num,num+1);
}
//获取BufferedImage的绘制对象
Graphics g = b.getGraphics();
//绘制干扰线
for (int i = 0;i < 5; i++){
int x1 = random.nextInt(59);
int y1 = random.nextInt(29);
int x2 = random.nextInt(59);
int y2 = random.nextInt(29);
g.drawLine(x1,y1,x2,y2);
}
// 设置画笔的一些属性(比如颜色、字体风格、背景、前景色等等)
g.drawString(numStr, 12, 19);
request.getSession().setAttribute("checkCode",numStr);
ImageIO.write(b, "jpg",response.getOutputStream());
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
}
二,使用Kaptcha插件生成验证码
1. 导入相应的jar包
kaptcha-2.3.jar
2. 写一个生成验证码图片的servlet
package com.eight.servlet;
import com.google.code.kaptcha.Producer;
import com.google.code.kaptcha.util.Config;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Properties;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class KaptchaServlet extends HttpServlet implements Servlet {
private Properties props;
private Producer kaptchaProducer;
private String sessionKeyValue;
public KaptchaServlet() {
this.props = new Properties();
this.kaptchaProducer = null;
this.sessionKeyValue = null;
}
public void init(ServletConfig conf) throws ServletException {
super.init(conf);
ImageIO.setUseCache(false);
Enumeration initParams = conf.getInitParameterNames();
while (initParams.hasMoreElements()) {
String key = (String) initParams.nextElement();
String value = conf.getInitParameter(key);
this.props.put(key, value);
}
Config config = new Config(this.props);
this.kaptchaProducer = config.getProducerImpl();
this.sessionKeyValue = config.getSessionKey();
}
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setDateHeader("Expires", 0L);
resp.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
resp.addHeader("Cache-Control", "post-check=0, pre-check=0");
resp.setHeader("Pragma", "no-cache");
resp.setContentType("image/jpeg");
String capText = this.kaptchaProducer.createText();
String s1 = capText.substring(0, 1);
String s2 = capText.substring(1, 2);
String culs = "+-*";
Random random = new Random();
char cul = culs.charAt(random.nextInt(3));
int r = 0;
switch(cul){
case '+':
r = Integer.valueOf(s1).intValue() + Integer.valueOf(s2).intValue();
break;
case '-':
r = Integer.valueOf(s1).intValue() - Integer.valueOf(s2).intValue();
break;
case '*':
r = Integer.valueOf(s1).intValue() * Integer.valueOf(s2).intValue();
break;
}
req.getSession().setAttribute(this.sessionKeyValue, String.valueOf(r));
BufferedImage bi = this.kaptchaProducer.createImage(s1 + cul + s2 + "=?");
ServletOutputStream out = resp.getOutputStream();
ImageIO.write(bi, "jpg", out);
try {
out.flush();
} finally {
out.close();
}
}
}
第三步:在web.xml上配置一些信息
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<!-- 登陆验证码Kaptcha 2 -->
<servlet>
<servlet-name>Kaptcha</servlet-name>
<servlet-class>com.eight.servlet.KaptchaServlet</servlet-class>
<init-param>
<description>图片边框,合法值:yes , no</description>
<param-name>kaptcha.border</param-name>
<param-value>yes</param-value>
</init-param>
<init-param>
<description>
边框颜色,合法值: r,g,b (and optional alpha) 或者 white,black,blue.
</description>
<param-name>kaptcha.border.color</param-name>
<param-value>black</param-value>
</init-param>
<init-param>
<description>边框厚度,合法值:>0</description>
<param-name>kaptcha.border.thickness</param-name>
<param-value>1</param-value>
</init-param>
<init-param>
<description>图片宽 200</description>
<param-name>kaptcha.image.width</param-name>
<param-value>200</param-value>
</init-param>
<init-param>
<description>图片高 50</description>
<param-name>kaptcha.image.height</param-name>
<param-value>50</param-value>
</init-param>
<init-param>
<description>图片实现类</description>
<param-name>kaptcha.producer.impl</param-name>
<param-value> com.google.code.kaptcha.impl.DefaultKaptcha </param-value>
</init-param>
<init-param>
<description>文本实现类</description>
<param-name>kaptcha.textproducer.impl</param-name>
<param-value>
com.google.code.kaptcha.text.impl.DefaultTextCreator
</param-value>
</init-param>
<init-param>
<description>文本集合,验证码值从此集合中获取</description>
<param-name>kaptcha.textproducer.char.string</param-name>
<param-value>1234567890</param-value>
</init-param>
<init-param>
<description>验证码长度 5</description>
<param-name>kaptcha.textproducer.char.length</param-name>
<param-value>2</param-value>
</init-param>
<init-param>
<description>字体 Arial, Courier</description>
<param-name>kaptcha.textproducer.font.names</param-name>
<param-value>Arial, Courier</param-value>
</init-param>
<init-param>
<description>字体大小 40px.</description>
<param-name>kaptcha.textproducer.font.size</param-name>
<param-value>40</param-value>
</init-param>
<init-param>
<description> 字体颜色,合法值: r,g,b 或者 white,black,blue. </description>
<param-name>kaptcha.textproducer.font.color</param-name>
<param-value>black</param-value>
</init-param>
<init-param>
<description>文字间隔 2</description>
<param-name>kaptcha.textproducer.char.space</param-name>
<param-value>2</param-value>
</init-param>
<init-param>
<description>干扰实现类</description>
<param-name>kaptcha.noise.impl</param-name>
<param-value>
<!-- com.google.code.kaptcha.impl.NoNoise -->
com.google.code.kaptcha.impl.DefaultNoise
</param-value>
</init-param>
<init-param>
<description> 干扰颜色,合法值: r,g,b 或者 white,black,blue. </description>
<param-name>kaptcha.noise.color</param-name>
<param-value>black</param-value>
</init-param>
<init-param>
<description>
图片样式: 水纹com.google.code.kaptcha.impl.WaterRipple 鱼眼com.google.code.kaptcha.impl.FishEyeGimpy 阴影com.google.code.kaptcha.impl.ShadowGimpy
</description>
<param-name>kaptcha.obscurificator.impl</param-name>
<param-value> com.google.code.kaptcha.impl.WaterRipple </param-value>
</init-param>
<init-param>
<description>背景实现类</description>
<param-name>kaptcha.background.impl</param-name>
<param-value> com.google.code.kaptcha.impl.DefaultBackground </param-value>
</init-param>
<init-param>
<description>背景颜色渐变,开始颜色</description>
<param-name>kaptcha.background.clear.from</param-name>
<param-value>green</param-value>
</init-param>
<init-param>
<description>背景颜色渐变,结束颜色</description>
<param-name>kaptcha.background.clear.to</param-name>
<param-value>white</param-value>
</init-param>
<init-param>
<description>文字渲染器</description>
<param-name>kaptcha.word.impl</param-name>
<param-value>
com.google.code.kaptcha.text.impl.DefaultWordRenderer
</param-value>
</init-param>
<init-param>
<description> session中存放验证码的key键 </description>
<param-name>kaptcha.session.key</param-name>
<param-value>KAPTCHA_SESSION_KEY</param-value>
</init-param>
<init-param>
<description>
The date the kaptcha is generated is put into the HttpSession. This is the key value for that item in the session.
</description>
<param-name>kaptcha.session.date</param-name>
<param-value>KAPTCHA_SESSION_DATE</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>Kaptcha</servlet-name>
<url-pattern>/randomcode.jpg</url-pattern>
</servlet-mapping>
</web-app>
3. 在jsp页面写入验证码图片标签和相关js
<script type="text/javascript">
function changeR(node){
// 用于点击时产生不同的验证码
node.src = "randomcode.jpg?time="+new Date().getTime() ;
}
</script>
<img style="width:150px;height:35px;vertical-align:top;cursor: pointer;" alt="random" src="randomcode.jpg" οnclick="changeR(this)" />
<input style="width:140px;height:35px;background-color:#e0e6ef;" class="imageCode" name="imageCode" placeholder="请输入验证码" />
4. 在登录验证的servlet中判断验证码是否正确
//验证码验证
private void codeCheck(HttpServletRequest request,
HttpServletResponse response) throws IOException {
//创建一个json对象
JSONObject json = new JSONObject();
//获取图片验证码上面的数据
String code = (String) request.getSession()
.getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
//获取用户输入的验证码数据
String str = request.getParameter("imageCode");
System.out.println(code+" "+str);
if(code.equals(str)){
json.put("status","true");
}else {
json.put("status","error");
}
PrintWriter out = response.getWriter();
out.print(json);
out.flush();
out.close();
}
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/81667.html