<html页面>. .
<tr>
<tdclass="td_left">
<labelfor="check">CAPTCHA</label>
</td>
<tdclass="td_right check">
<inputtype="text"id="check"name="check"class="check">
<imgsrc="checkCodeServlet"height="32px"alt=""onclick="changeCheckCode(this)">
<scripttype="text/javascript">
//Image click events
functionchangeCheckCode(img) {
img.src="checkCodeServlet?"+newDate().getTime();
}
</script>
</td>
</tr>//验证码拼接部分public classCheckCodeServletextendsHttpServlet{
@Override
public voiddoGet(HttpServletRequest request, HttpServletResponse response)throwsServletException, IOException{
//The server informs the browser not to cache
response.setHeader("pragma","no-cache"); response.setHeader("cache-control","no-cache"); response.setHeader("expires","0");
//Create a long one in memory80, wide30The default black background
//Parameter 1: Length
//Parameter 2: Width
//Parameter 3: Color
intwidth =80;
intheight =30; BufferedImage image =newBufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
//Get the brush
Graphics g = image.getGraphics();
//Set the brush color to gray
g.setColor(Color.GRAY);
//Fill the picture
g.fillRect(0,0, width,height);
//Produced4random verification code,12Ey
String checkCode = getCheckCode();
//Put the code inHttpSessionMedium
request.getSession().setAttribute("code",checkCode);
//Set the brush color to yellow
g.setColor(Color.YELLOW);
//Set the size of the font
g.setFont(newFont("Black body",Font.BOLD,24));
//Write a verification code to the image
g.drawString(checkCode,15,25);
//Output the picture from memory to the browser
//Parameter 1: Picture object
//Parameter 2: The format of the picture, such as:PNG,JPG,GIF
//Parameter 3: Where the picture is output
ImageIO.write(image,"PNG",response.getOutputStream());
}
/**
*Produced4Bit random string
*/
privateString getCheckCode() {
String base ="0123456789ABCDEFGabcdefg";
intsize = base.length(); Random r =newRandom(); StringBuffer sb =newStringBuffer();
for(inti=1; i<=4; i++){
//Produced0tosize-1of random values
intindex = r.nextInt(size);
//atbasestring get subscript asindexcharacters
charc = base.charAt(index);
//willcPut inStringBufferGo in the middle
sb.append(c);
}
returnsb.toString();
}
@Override
public voiddoPost(HttpServletRequest request, HttpServletResponse response) throwsServletException, IOException{
this.doGet(request,response);
}
}
How to achieve it?
|