Captcha image validation in jsp/servlet
Post date: Jul 21, 2011 3:53:51 AM
Hi i plan to create my own image for doing manual captcha verification. I know it is some what difficult, but when you required security it must to implement our own program.
Following code able create the captcha image which have 5 character with it. if you required you can change it.
Once you call this servlet it will create a image of 5 character, then you need to store this captchas text into session for next request verification.
package com.boobalan.training.servlet;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.awt.image.*;
import com.sun.image.codec.jpeg.*;
import java.awt.*;
public class ImageServlet extends HttpServlet{
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException{
//
res.setContentType("image/jpeg"); //MIME
//PrintWriter out = res.getWriter(); // writer output
ServletOutputStream out = res.getOutputStream();
String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890";
String captchaText = "";
// Capture the text have 5 character
for(int i=0; i<5 ;i++){
int rno =(int)(Math.random()*str.length());
captchaText +=str.charAt(rno);
}
//AWT classes. Learn java2D for more efforts Show the Image to user
BufferedImage image = new BufferedImage(150, 75, BufferedImage.TYPE_INT_RGB);// draw image in memory
Graphics g = image.getGraphics();//pen
g.setColor(Color.ORANGE);
g.fillRect(0,0,150,75);
g.setColor(Color.BLUE);
g.setFont(new Font("French Script MT", Font.BOLD, 24));
g.drawString(captchaText, 70,30);
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
encoder.encode(image);
out.close();
}
}