Java Implementation Verification Code login

Source: Internet
Author: User
Tags gettext

To implement a verification code in Java:

1. Create the entity class for the verification code as follows :

  1. Import Java.awt.BasicStroke;
  2. Import Java.awt.Color;
  3. Import Java.awt.Font;
  4. Import Java.awt.Graphics2D;
  5. Import Java.awt.image.BufferedImage;
  6. Import java.io.IOException;
  7. Import Java.io.OutputStream;
  8. Import Java.util.Random;
  9. Import Javax.imageio.ImageIO;
  10. public class Verifycode {
  11. /**
  12. * Nan accommodating heals scythe?
  13. * @author blemish lee Carpenter Å?
  14. */
  15. private int w = 50;
  16. private int h = 25;
  17. Private random r = new Random ();
  18. Private string[] fontnames = {"Yue ã 綋", "Å bond po 妤 bee 綋", "Hazel Contact 綋", "Atlas Jiang boss 呴 din Daeng", "妤 Bee 綋 _gb2312"};
  19. Private String codes = "23456789abcdefghjkmnpqrstuvwxyzABCEFGHIJKLMNPQRSTUVWXYZ";
  20. Private color bgColor = new Color (255,255,255);
  21. private String text;
  22. Private Color Randomcolor () {
  23. int red = r.nextint (200);
  24. int green = r.nextint (200);
  25. int blue = r.nextint (200);
  26. return new Color (Red,green,blue);
  27. }
  28. Private Font Randomfont () {
  29. int index = r.nextint (fontnames.length);
  30. String fontname = Fontnames[index];
  31. int style = r.nextint (4);
  32. int size = r.nextint (6) +15;
  33. return new Font (fontname,style,size);
  34. }
  35. private void DrawLine (BufferedImage image) {
  36. int num = 3;
  37. graphics2d g2 = (graphics2d) image.getgraphics ();
  38. for (int i=0;i<num;i++) {
  39. int x1 = r.nextint ();
  40. int y1 = r.nextint ();
  41. int x2 = r.nextint ();
  42. int y2 = r.nextint ();
  43. G2.setstroke (New Basicstroke (1.5F));
  44. G2.setcolor (Color.Blue);
  45. G2.drawline (X1,Y1,X2,Y2);
  46. }
  47. }
  48. Private char Randomchar () {
  49. int index = r.nextint (codes.length ());
  50. Return Codes.charat (index);
  51. }
  52. Private BufferedImage createimage () {
  53. BufferedImage image = new BufferedImage (W,H,BUFFEREDIMAGE.TYPE_INT_RGB);
  54. graphics2d g2 = (graphics2d) image.getgraphics ();
  55. G2.setcolor (This.bgcolor);
  56. G2.fillrect (0, 0, W, h);
  57. return image;
  58. }
  59. Public BufferedImage GetImage () {
  60. BufferedImage image = createimage ();
  61. graphics2d g2 = (graphics2d) image.getgraphics ();
  62. StringBuilder sb = new StringBuilder ();
  63. for (int i= 0;i<4;i++) {
  64. String s = Randomchar () + "";
  65. Sb.append (s);
  66. float x = I*1.0F*W/4;
  67. G2.setfont (Randomfont ());
  68. G2.setcolor (Randomcolor ());
  69. G2.drawstring (S, x, h-5);
  70. }
  71. This.text = sb.tostring ();
  72. DrawLine (image);
  73. return image;
  74. }
  75. Public String GetText () {
  76. return text;
  77. }
  78. public static void Output (BufferedImage image,outputstream out) throws ioexception{
  79. Imageio.write (Image, "JPEG", out);
  80. }
  81. }

2. Create a servlet for the verification code

  1. Import Java.awt.image.BufferedImage;
  2. Import java.io.IOException;
  3. Import Java.io.PrintWriter;
  4. Import Javax.imageio.ImageIO;
  5. Import javax.servlet.ServletException;
  6. Import Javax.servlet.annotation.WebServlet;
  7. Import Javax.servlet.http.HttpServlet;
  8. Import Javax.servlet.http.HttpServletRequest;
  9. Import Javax.servlet.http.HttpServletResponse;
  10. Import util. Verifycode;
  11. @WebServlet ("/verifycodeservlet")
  12. public class Verifycodeservlet extends HttpServlet {
  13. /**
  14. * Servlet
  15. * @author Weiqiang
  16. */
  17. public void doget (HttpServletRequest request, httpservletresponse response)
  18. Throws Servletexception, IOException {
  19. Verifycode VC = new Verifycode ();
  20. Response.setheader ("Cache-control", "No-cache");
  21. Response.setcontenttype ("Image/jpeg");
  22. BufferedImage bim = vc.getimage ();
  23. Imageio.write (BIM, "JPEG", Response.getoutputstream ());
  24. String Verifycode = vc.gettext ();
  25. Request.getsession (). SetAttribute ("Verifycode", Verifycode);
  26. }
  27. public void DoPost (HttpServletRequest request, httpservletresponse response)
  28. Throws Servletexception, IOException {
  29. Doget (request, response);
  30. }
  31. public void Destroy () {
  32. Super.destroy ();
  33. }
  34. public void Init () throws servletexception{
  35. }
  36. }
  37. 3. Configuring in XML
  38. Servlet>
    <servlet-name>VerifyCodeServlet</servlet-name>
    <servlet-class>cn.com.shxt.servlet.VerifyCodeServlet</servlet-class>
    </servlet>
    <servlet-mapping>
    <servlet-name>VerifyCodeServlet</servlet-name>
    <url-pattern>/VerifyCodeServlet</url-pattern>
    </servlet-mapping>


3. Use the following code where you need to use the verification code:

[HTML]View PlainCopy
  1. <!--It's not clear what the Refresh function is.
  2. <script>
  3. function Changeverifycode () {
  4. document.getElementById ("Validatecodeimg"). src="verifycodeservlet?t=" +math.random ();
  5. }
  6. </Script>
  7. <!--This is the input box for entering the verification code--
  8. <INPUT id=txtsn size=4 name=txtsn>
  9. <!--This is the display of the captcha, shown in pictures--
  10. <!--Src's road strength is the servlet's way--
  11. <img src= "<%=basepath%>verifycodeservlet"  border=0 id= "validatecodeimg"  style= "height: 25px; width: 57px" span class= "tag" >/><a href= "#"  onclick= " Changeverifycode () "> can't see clearly? Change a </a></ td>  


4. The actual effect is as follows

String code = request.getparameter ("code");
String verifycode = (string) request.getsession (). getattribute ("Verifycode");

else if (!code.equals (Verifycode)) {//Login failed
Request.setattribute ("message", "Captcha error");
Request.getrequestdispatcher ("/login.jsp"). Forward (request, response);

The code of the foreground and the verification code in the session are compared to realize the function of verification code.

Java Implementation Verification Code login

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.