Photo validation is often used in relation to registering and publishing messages. I have written a JSP here, for your reference. Com.sun.image is not a standard package for Java. Additional downloads are required. Related address: http://java.sun.com/products/ java-media/jai/
1. random.jsp (generates four-bit random characters, consisting of 0-9,a-z,a-z.) and put the final string in session to save for subsequent pages to verify authenticity.
The code is as follows:
<%@ page autoflush= "false" import= "java.util.*,java.awt.*,java.awt.image.*,com.sun.image.codec.jpeg.*, Java.util.* "%>
<%@ page import= "contenttype=" text/html; charset=gb2312 "%>
<%
String chose= "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
Char display[]={' 0 ', ', ' 0 ', ', ' 0 ', ', ' 0 '},ran[]={' 0 ', ' 0 ', ' 0 ', ' 0 '},temp;
Random rand=new Random ();
for (int i=0;i<4;i++)
{
Temp=chose.charat (Rand.nextint (Chose.length ()));
Display[i*2]=temp;
Ran[i]=temp;
}
String random=string.valueof (display);
Session.setattribute ("Random", String.valueof (RAN));
%>
<%
out.clear ();
response.setcontenttype ("Image/jpeg");
Response.AddHeader ("Pragma", "no-cache");
Response.AddHeader ("Cache-control", "No-cache");
response.adddateheader ("Expries", 0);
int width=47, height=15;
bufferedimage image = new BufferedImage (width, height, BUFFEREDIMAGE.TYPE_INT_RGB);
Graphics g = image.getgraphics ();
//below fill background color
G.setcolor (Color.green);
g.fillrect (0, 0, width, height);
//Set font color
&nbsP G.setcolor (color.red);
g.drawstring (random,3,10);
g.dispose ();
Servletoutputstream outstream = Response.getoutputstream ();
JPEGImageEncoder encoder =jpegcodec.createjpegencoder (OutStream);
Encoder.encode (image);
outstream.close ();
%>
2. img.jsp (display verification picture.) Because this program is simple to let the verification program together.
The code is as follows:
<%@ page contenttype= "text/html; charset=gb2312 "Language=" Java%>
<%
String num=request.getparameter ("num");
String random= (String) session.getattribute ("random");
if (num!=null&&random!=null)
{
if (!num.equals (random))
{
Out.println ("<script>alert code Error!") Please try again. ') </script> ");
Out.println ("<script>history.go ( -1) </script>");
Response.sendredirect ("img.jsp");
}
Else
{
Out.println ("<center> Verification success!") </center> ");
}
}
%>
<title> Photo Validation </title>
<meta http-equiv= "Content-type" content= "text/html; charset=gb2312 ">
<body>
<form action= "img.jsp" method= "POST" >
<table>
<tr>
<td>
<input type= "text" name= "num" size=10>
</td>
<td>
</td>
</tr>
</table>
<input type= "Submit" value= "OK" >
</form>
</body>