JAVA Verification Code tool instance code, java Verification Code instance
Tool class:
Package com. lhy. web. servlet; import java. awt. basicStroke; import java. awt. color; import java. awt. font; import java. awt. graphics2D; import java. awt. image. bufferedImage; import java. io. fileNotFoundException; import java. io. fileOutputStream; import java. io. IOException; import java. io. outputStream; import java. util. random; import javax. imageio. imageIO; public class VerifyCode {private int w = 70; // picture length private int H = 35; // Image Width private Random r = new Random (); // Random number generated by the Random class // list the font type of the verification code in the image // {" ", "文 ", ""," 文 ", "文 "," ", "_ GB2312"} private String [] fontNames = {""," 文 ", "_ GB2312 "}; // optional characters of the Verification Code: private String codes = "23456789 abcdefghjkmnopqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ"; // background Color private Color bgColor = new Color (255,255,255); // The text private String text on the verification code; // generate Machine Color private Color randomColor () {int red = r. nextInt (150); int green = r. nextInt (150); int blue = r. nextInt (150); return new Color (red, green, blue);} // generate a random Font private Font randomFont () {int index = r. nextInt (fontNames. length); String fontName = fontNames [index]; // generate a random font name int style = r. nextInt (4); // generate a random style, 0 (no style), 1 (BOLD), 2 (italic), 3 (bold + italic) int size = r. nextInt (5) + 24; // generate random font size, 24 ~ 28 return new Font (fontName, style, size);} // draw interference line private void drawLine (BufferedImage image) {int num = 3; // draw 3 Graphics2D g2 = (Graphics2D) image in total. getGraphics (); for (int I = 0; I <num; I ++) {// generates coordinates of two points, that is, four values: int x1 = r. nextInt (w); int y1 = r. nextInt (h); int x2 = r. nextInt (w); int y2 = r. nextInt (h); g2.setStroke (new BasicStroke (1.5F); g2.setColor (Color. BLUE); // The interference line is BLUE g2.drawLine (x1, y1, x2, y2); // draw line }}// generate a random character private char randomChar () {int index = r. nextInt (codes. length (); return codes. charAt (index) ;}// create BufferedImage private BufferedImage createImage () {// width, height, image type BufferedImage image = new BufferedImage (w, h, BufferedImage. TYPE_INT_RGB); Graphics2D g2 = (Graphics2D) image. getGraphics (); g2.setColor (this. bgColor); g2.fillRect (0, 0, w, h); return image;} // return the public String getText () {return text ;} // Save the image to the specified output stream public static void output (BufferedImage image, OutputStream out) throws IOException {ImageIO. write (image, "JPEG", out);} // call this method to obtain the verification code public BufferedImage getImage () {BufferedImage image = createImage (); // create the image buffer Graphics2D g2 = (Graphics2D) image. getGraphics (); // obtain the drawing environment StringBuilder sb = new StringBuilder (); // use it to load the generated Verification Code text // draw a 4 character for (int I = 0; I <4; I ++) {// cyclically four times. Each time a character String s = randomChar () + ""; // a random sb letter is generated. append (s); // Add the letter to sb float x = I * 1.0F * w/4; // set the x axis coordinate g2.setFont (randomFont () of the current character ()); // set random font g2.setColor (randomColor (); // set random color g2.drawString (s, x, h-5); // draw} this. text = sb. toString (); // assign the generated string to this. text drawLine (image); // Add interference line return image;} public static void main (String [] args) throws FileNotFoundException, IOException {VerifyCode vc = new VerifyCode (); // create the VerifyCode Class Object BufferedImage bi = vc. getImage (); // call the getImge () method to obtain a BufferedImage object VerifyCode. output (bi, new FileOutputStream ("C:/Verification Code 3.jpg"); // call the static method output () to save the image to the file output stream System. out. println (vc. getText (); // print the text value of the verification code on the console }}
VerifyCodeServlet:
Package com. lhy. web. servlet; import java. awt. image. bufferedImage; import java. io. IOException; import javax. servlet. servletException; import javax. servlet. http. httpServlet; import javax. servlet. http. httpServletRequest; import javax. servlet. http. httpServletResponse; public class VerifyCodeServlet extends HttpServlet {public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {/** 1. generate image * 2. save the text on the image to the session domain * 3. send the image to the client */VerifyCode vc = new VerifyCode (); BufferedImage image = vc. getImage (); request. getSession (). setAttribute ("session_vcode", vc. getText (); // Save the text on the image to the session domain VerifyCode. output (image, response. getOutputStream ());}}
LoginServlet:
Package com. lhy. web. servlet; import java. io. IOException; import javax. servlet. requestDispatcher; import javax. servlet. servletException; import javax. servlet. http. cookie; import javax. servlet. http. httpServlet; import javax. servlet. http. httpServletRequest; import javax. servlet. http. httpServletResponse; import javax. servlet. http. httpSession; public class LoginServlet extends HttpServlet {public void doPost (Ht TpServletRequest request, HttpServletResponse response) throws ServletException, IOException {/** Verification Code * 1. obtain the correct verification code from the session * 2. obtain the verification code entered by the user from the form * 3. for comparison! * 4. if the same, run down. Otherwise, save the error message to the request domain and forward it to login. jsp */String sessionCode = (String) request. getSession (). getAttribute ("session_vcode"); String paramCode = request. getParameter ("verifyCode"); if (! ParamCode. inclusignorecase (sessionCode) {request. setAttribute ("msg", "Verification code error! "); Request. getRequestDispatcher ("/login. jsp "). forward (request, response); return;}/** 1. obtain the form data * // process the Chinese request. setCharacterEncoding ("UTF-8"); // obtain String username = request. getParameter ("username"); String password = request. getParameter ("password");/** 2. verify that the user name and password are correct */if ("itcast ". inclusignorecase (username) {// login successful/** additional item: Save the user name to the cookie and send it to the client browser * When login is opened again. in jsp, login. re will be read in jsp Cookie in quest, which is displayed in the username text box */Cookie cookie = new Cookie ("uname", username); // create Cookie. setMaxAge (60*60*24); // set the cookie life cycle to 1 day response. addCookie; // Save the cookie/** 3. if user information is successfully saved to the session *> redirected to succ1.jsp */HttpSession session = request. getSession (); // get the session. setAttribute ("username", username); // Save the user name response to the session domain. sendRedirect ("/Test/succ1.jsp");} else {// Logon Failed /** 4. If the error message fails *> Save the error message to the request domain *> forward it to login. jsp */request. setAttribute ("msg", "incorrect user name or password! "); RequestDispatcher qr = request. getRequestDispatcher ("/login. jsp "); // get the forwarder qr. forward (request, response); // forward }}}
Login. jsp:
<% @ Page language = "java" import = "java. util. * "pageEncoding =" UTF-8 "%> <% String path = request. getContextPath (); String basePath = request. getScheme () + ": //" + request. getServerName () + ":" + request. getServerPort () + path + "/"; %> <! Doctype html public "-// W3C // dtd html 4.01 Transitional // EN">
Loginsuccess:
<Body>
Welcome, warm welcome, welcome<%=username %>Leaders guide the work!
</body>
Configuration file:
<servlet> <servlet-name>LoginServlet</servlet-name> <servlet-class>com.lhy.web.servlet.LoginServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>LoginServlet</servlet-name> <url-pattern>/servlet/LoginServlet</url-pattern> </servlet-mapping> <servlet> <servlet-name>VerifyCodeServlet</servlet-name> <servlet-class>com.lhy.web.servlet.VerifyCodeServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>VerifyCodeServlet</servlet-name> <url-pattern>/servlet/VerifyCodeServlet</url-pattern> </servlet-mapping>
Suggestion: it is best to set the Servlet that generates the verification code to not cache, so that you do not need to add a timestamp when requesting the verification code image on the page, the timestamp is used to trick the browser into preventing the browser from reading the image of the verification code in the cache, but it does not respond after you click another one. This is not a good idea. Every time you click another image, the browser caches the newly acquired image to the local device. If you do not cache the image in the Servlet, the image will not be cached locally.
Summary
The above is an example code of the JAVA Verification Code tool introduced by xiaobian. I hope it will help you. If you have any questions, please leave a message and I will reply to you in a timely manner. Thank you very much for your support for the help House website!