Java implementation Click on the image text verification code

Source: Internet
Author: User

Original: http://blog.csdn.net/qq_26680031/article/details/51168527

Above

Package Cn.gdin.captcha;

Import Java.awt.Color;
Import Java.awt.Font;
Import Java.awt.Graphics2D;
Import Java.awt.Image;
Import Java.awt.image.BufferedImage;
Import Java.io.File;
Import java.io.IOException;
Import Java.io.InputStream;
Import java.io.UnsupportedEncodingException;
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 Jcaptchaservlet extends HttpServlet {
Random random = new random ();
public void doget (HttpServletRequest request, httpservletresponse response)
Throws Servletexception, IOException {

int height = 220; Picture High
int width = 220; Picture width
BufferedImage image = new BufferedImage (WIDTH,HEIGHT,BUFFEREDIMAGE.TYPE_INT_RGB);
Graphics2D g = (graphics2d) image.getgraphics ();
String picpath= JcaptchaServlet.class.getClassLoader (). GetResource ("..  /image/"+ (Random.nextint (4) +1) +". jpg "). GetPath (); Read local pictures, do background pictures


G.drawimage (Imageio.read (New File (Picpath)), 0, width, height, null); Start the background picture from height 20


G.setcolor (Color.White); Set color
G.drawrect (0, 0, width-1, height-1); Draw Border

G.setfont (New Font ("Arial", font.bold,20)); Set font
Integer X=null,y=null; Used to record coordinates
String Target=null; Used to record text
for (int i=0;i<4;i++) {//randomly generates 4 text, coordinates, colors are different
G.setcolor (New Color (Random.nextint) +200, Random.nextint (+100, Random.nextint (50) +200));
String Str=getrandomchinesechar ();
int A=random.nextint (width-100) +50;
int B=random.nextint (height-70) +55;
if (x==null) {
X=a; Record the first x-coordinate
}
if (y==null) {
y=b;//record the first y-coordinate
}
if (target==null) {
TARGET=STR; Record the first type of text
}
g.DrawString (str, a, b);
}
G.setcolor (Color.White);
g.DrawString ("Click" +target, 0,20);//write the verification code the first line of text "click ..."
Request.getsession (). SetAttribute ("Gap", x+ ":" +y);//place coordinates into session
5. Releasing Resources
G.dispose ();
6. Using ImageIO for output
Imageio.write (image, "JPG", Response.getoutputstream ()); Output the picture

}
A method for randomly producing Chinese characters on the Internet
Public String Getrandomchinesechar ()
{
String str = NULL;
int HS, LS;
Random random = new random ();
HS = (176 + math.abs (Random.nextint (39)));
ls = (161 + math.abs (Random.nextint (93)));
Byte[] B = new byte[2];
B[0] = (new Integer (HS). Bytevalue ());
B[1] = (new Integer (LS). Bytevalue ());
Try
{
str = new String (b, "GBk"); Turn into Chinese
}
catch (Unsupportedencodingexception ex)
{
Ex.printstacktrace ();
}
return str;
}
public void DoPost (HttpServletRequest request, httpservletresponse response)
Throws Servletexception, IOException {
Doget (request, response);
}

}

Front-end Code

<script type= "Text/javascript" src= "${pagecontext.request.contextpath}/js/jquery-1.11.3.min.js" ></ Script>
<script type= "Text/javascript" >

$ (function () {
$ ("#image"). Click (Function (event) {
var obj=this;
var x=event.offsetx;//gets the mouse relative picture coordinates when clicked
var y=event.offsety;
$.ajax ({
URL: "login.shtml",//ajax submit
Type: "Post",
data:{' x ': x, ' y ': y},
Success:function (data) {

Alert (data)
obj.src=obj.src+ "? date=" +new date ();
}
})
});
})


</script>

<body>

</body>

Service side

Package Cn.gdin.captcha;

Import java.io.IOException;
Import java.util.Enumeration;
Import Java.util.Map;
Import Java.util.Map.Entry;

Import javax.servlet.ServletException;
Import Javax.servlet.annotation.WebServlet;
Import Javax.servlet.http.HttpServlet;
Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse;
Import javax.servlet.http.HttpSession;

/**
* Servlet Implementation Class Login
*/
@WebServlet ("/login")
public class Login extends HttpServlet {
Private static final long serialversionuid = 1L;


protected void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {
TODO auto-generated Method Stub
Response.setcontenttype ("Text/html;charset=utf-8"); Set encoding
Get the coordinates coming from the front end

String xs=request.getparameter ("x");
String ys=request.getparameter ("Y");
HttpSession session = Request.getsession ();

String str = (string) session.getattribute ("gap");//Get Gap in session
if (str==null) {
Response.getwriter (). Write ("Verification Code timeout");
Return
}
string[] Split2 = Str.split (":");
int x= Integer.parseint (XS);
int Y=integer.parseint (YS);
int x1= integer.parseint (split2[0]);
int Y1=integer.parseint (split2[1]);
if (x1-2<x && x<x1+22 && y1-22<y && y<y1+2) {//if the coordinates of the front-end upload are within a certain range of coordinates recorded in the session, validation succeeds
Response.getwriter (). Write ("verify success");
}else{
Response.getwriter (). Write ("validation failed");
}
}

/**
* @see Httpservlet#dopost (httpservletrequest request, httpservletresponse response)
*/
protected void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {
TODO auto-generated Method Stub
Doget (request, response);
}

}

----------------------------------------------The following is my own makeover------------------------------

@Action ("/test")     Public voidTest ()throwsIOException {random random=NewRandom (); intheight = 220;//Picture High        intwidth = 220;//Picture WidthBufferedImage image =NewBufferedImage (WIDTH,HEIGHT,BUFFEREDIMAGE.TYPE_INT_RGB); Graphics2D g=(graphics2d) image.getgraphics (); String Picpath= "D:/a.png";//read local pictures, do background picturesg.drawimage (Imageio.read (NewFile (Picpath)), 0, width, height,NULL);//start the background picture from height 20G.setcolor (Color.White); //Set ColorG.drawrect (0, 0, width-1, height-1);//Draw BorderG.setfont (NewFont ("Song Body", font.bold,20));//Set FontInteger x=NULL, y=NULL;//used to record coordinatesString target=NULL;//used to record text         for(inti=0;i<4;i++) {//randomly produces 4 words, coordinates, colors are differentG.setcolor (NewColor (Random.nextint (+200), Random.nextint (+100), Random.nextint (50) +200)); String Str=Getrandomchinesechar (); intA=random.nextint (width-100) +50; intB=random.nextint (height-70) +55; if(x==NULL) {x=a;//record the first x-coordinate            }            if(y==NULL) {y=b;//record the first y-coordinate            }            if(target==NULL) {target=STR;//record the first type of text} g.drawstring (str, a, b);          } g.setcolor (Color.White); g.DrawString ("Click" +target, 0,20);//Write verification code The first line of text "click ..."Request.getsession (). SetAttribute ("Gap", x+ ":" +y);//Place coordinates into sessionSystem.out.println ("Gap:" +x+ ":" +y); Servletoutputstream out=Response.getoutputstream (); //5. Releasing ResourcesG.dispose (); //6. Using ImageIO for OutputImageio.write (image, "JPG", out);//Output the pictureOut.flush (); }         Publicstring Getrandomchinesechar () {string str=NULL; intHS, LS; Random Random=NewRandom (); HS= (176 + math.abs (Random.nextint (39))); LS= (161 + math.abs (Random.nextint (93))); byte[] B =New byte[2]; b[0] = (NewInteger (HS). Bytevalue ()); b[1] = (NewInteger (LS). Bytevalue ()); Try{str=NewString (b, "GBk");//turn into Chinese              }              Catch(Unsupportedencodingexception ex) {ex.printstacktrace (); }              returnstr; }

Java implementation Click on the image text verification code

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.