Java实现验证码制作之一自己动手
以前弄验证码都是现找现用,下面是自己跟着敲代码弄好的,记录一下,分享给大家。
我这里用的是Servlet ,Servlet代码如下
import java.awt.Color;
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;
public class ImageServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
BufferedImage bi=new BufferedImage(68,22, BufferedImage.TYPE_INT_RGB);
Graphics g=bi.getGraphics();
Color c=new Color(200,150,255);
g.setColor(c);
g.fillRect(0, 0, 68, 22);//宽高
//设定验证码的字符
char[] ch="QWERTYUIOPASDFGHJKLZXCVBNM0123456789".toCharArray();
Random r=new Random();
int len=ch.length,index;
StringBuffer sb=new StringBuffer();
for(int i=0;i<4;i++){
index=r.nextInt(len);
//设置每个字体的颜色都不一样
g.setColor(new Color(r.nextInt(88),r.nextInt(188),r.nextInt(255)));
g.drawString(ch[index]+"", (i*15)+3,18);//画图
sb.append(ch[index]);//记录验证码
}
req.getSession().setAttribute("piccode", sb.toString());//保存到session作用域当中
ImageIO.write(bi, "JPG", resp.getOutputStream()); //写入到对应的页面
super.doGet(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doGet(req, resp);
}
}
//上面servlet 中把每次生成的验证码都保存在session中
// req.getSession().setAttribute("piccode", sb.toString());
//当用户提交的我们就可以通过
//String code=req.getSession().getAttribute("piccode");
//来取得生成的验证码和用户填写的验证码来对比
//web.xml中的配置
<servlet>
<servlet-name>ImageServlet</servlet-name>
<servlet-class>com.test.servlet.ImageServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ImageServlet</servlet-name>
<url-pattern>/image.do</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
//index.jsp页面代码
<form action="<%=request.getContextPath()%>/login.do" method="get" >
<center>
<div>
验证码:<input type="text" name="code1" />
<img alt="验证码" src="<%=request.getContextPath()%>/image.do" id="code1" onclick="relodCode(this,'image.do')"/>
</div>
<input type="submit" value="提交"/>
</center>
</form>
<script type="text/javascript">
function relodCode(obj,url){
var time=new Date();
obj.src="<%=request.getContextPath()%>/"+url+"?time="+time;
}
</script>
效果图(点击验证码刷新)
上面介绍的是自己来写,但是我们一般用要用的验证码的时候一般都会用一些插件,下一篇来介绍一下 kaptcha验证码的使用