//画验证码
public class ValidateCode extends HttpServlet{
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
BufferedImage img=new BufferedImage(100, 30, BufferedImage.TYPE_INT_RGB);
// 1、获取画笔
Graphics g=img.getGraphics();
Random random=new Random();
g.setColor(new Color(random.nextInt(255),random.nextInt(255),random.nextInt(255)));
g.fillRect(0, 0,100, 30);
//2获取验证码
String text=getText(5);
HttpSession session=req.getSession();
session.setAttribute("code", text);
g.setColor(new Color(0,0,0));
g.setFont(new Font(null,Font.BOLD, 24));
g.drawString(text, 5, 25);
//绘制干扰线
for(int i=0;i<8;i++){
g.setColor(new Color(random.nextInt(255),random.nextInt(255),random.nextInt(255)));
g.drawLine(random.nextInt(100),random.nextInt(30), random.nextInt(100),random.nextInt(30));
}
//绘制到网页
resp.setContentType("image/jpeg");
OutputStream output=resp.getOutputStream();
ImageIO.write(img, "jpeg", output);
output.close();
}
//获取字符随机字符串
public String getText(int size){
String str="QWERTYUIOPLKJHGFDSAZXCVBNMmnbvcxzasdfghjklpoiuytrewq0123456789";
String text="";
Random r=new Random();
for(int j=0;j<size;j++){
text+=str.charAt(r.nextInt(str.length()));
}
return text;
}
}
web.xml设置
<servlet-name>identify</servlet-name>
<servlet-class>com.edusak.identity.ValidateCode</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>identify</servlet-name>
<url-pattern>/code</url-pattern>
</servlet-mapping>
网页代码
<div >
<label >验证码:</label>
<input name="j_captcha" type="text" placeholder="请输入验证码"> <img id="captcha_img" alt="点击更换" title="点击更换" src="code" class="m img" onclick="this.src='code?'+Math.random();">
</div>