Jsp-5 Generate verification code and verify

Source: Internet
Author: User

Jsp-5 Generate verification code and verify

The last code is still the base

index.jsp

Added Verification code column

Note that his servlet is a new imageservlet.

And in the middle of a JS code to refresh the verification code

<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "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" "Http://www.w3.org/TR/html4/loose.dtd" >String username=""; String Password="";//Remove CookiesCookie [] cookie=request.getcookies (); for(inti=0;i<cookie.length;i++){  if(Cookie[i].getname (). Equals ("username") ) {username=Cookie[i].getvalue (); }  if(Cookie[i].getname (). Equals ("Password") ) {Password=Cookie[i].getvalue (); }}%><script type= "Text/javascript" >//can't see the click events of overloaded picturesfunctionReloadcode () {varTime=NewDate (). GetTime (); document.getElementById ("Imagecode"). src= "<%= Request.getcontextpath ()%>/imageservlet?d=" +Time ;}</script><form action= "<%=basepath%>/login.do" method= "POST" > <table border=0 cellpadding=0 Cellspacing=0 style= "margin:auto;border-collapse:separate; border-spacing:10px; "            > <tr align= "center" > <td colspan= "2" > <label> login </label> </td> </tr> <tr> <td>User name:</td> <td> <input type= "text" name= "username" value= "<%=username%>" > </td> </tr> <tr> <td>Password:</td> <td> <input type= "password" name= "password" value= "<%=password%>"            ; </td> </tr> <tr> <td>Verification Code:</td> <td> <input type= "text" name= "Checkcode"/> /imageservlet "/><a href=" Javascript:reloadcode (); "                > Can't see clearly </a><br> </td> </tr> <tr> <td>            <input type= "checkbox" Name= "Ischeck" > Remember me? </td> <td> &nbsp;&nbsp;<a href= "<%=basepath%>/toregister.do" > Registration &                lt;/a> </td> </tr> <tr align= "center" > <td> <input type= "Submit" value= "Login" > </td> <td> <input type= "Reset" value= "Reset" > </td> </tr> </table></form></body>

Imageservlet class

Or that one, in theory, someone must have written the bag for us.

But I didn't find it.

ha haha haha ha ha haha

 Packagecom.javaweb.action;ImportJava.awt.Color;ImportJava.awt.Graphics;ImportJava.awt.image.BufferedImage;Importjava.io.IOException;ImportJava.util.Random;ImportJavax.imageio.ImageIO;Importjavax.servlet.ServletException;ImportJavax.servlet.http.HttpServlet;Importjavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse; Public classImageservletextendshttpservlet{/**     *      */    Private Static Final LongSerialversionuid = 54354321L; @Overrideprotected voidDoget (httpservletrequest req, HttpServletResponse resp)throwsservletexception, IOException {//TODO auto-generated Method StubdoPost (req, resp); }     Public voidDoPost (httpservletrequest request,httpservletresponse response)throwsioexception{//This method implements the verification code generationBufferedImage bi=NewBufferedImage (22,BUFFEREDIMAGE.TYPE_INT_RGB);//Creating an image bufferGraphics G=bi.getgraphics ();//Create a canvas from a bufferColor c=NewColor (200,150,255);//Create color         /** Draw a rectangle based on the background*/G.setcolor (c);//add a background color to the canvasG.fillrect (0, 0, 68,22);//FillRect: Fills the specified rectangle                  Char[] ch= "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789". ToCharArray ();//an array converted to a character typeRandom r=NewRandom (); intlen=ch.length; intIndex//index is used to store random numbersStringBuffer sb=NewStringBuffer ();  for(inti=0;i<4;i++) {Index=r.nextint (len);//Generate random numbersG.setcolor (NewColor (R.nextint), R.nextint (188), R.nextint (255));//Set Colorg.DrawString (ch[index]+ "", (i*15) +3, 18);//draw numbers and positions of numberssb.append (Ch[index]); } request.getsession (). SetAttribute ("Piccode", sb.tostring ());//keep numbers in session for later useImageio.write (BI, "JPG", Response.getoutputstream ());//Output Picture    }}

Xml

Do not forget to register the new servlet statically

<?XML version= "1.0" encoding= "UTF-8"?><Web-appXmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"xmlns= "Http://java.sun.com/xml/ns/javaee"xsi:schemalocation= "Http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"ID= "webapp_id"version= "3.0">  <Display-name>Servlet_sql_mvc_cookie</Display-name>  <welcome-file-list>    <Welcome-file>index.jsp</Welcome-file>  </welcome-file-list>    <servlet>      <Servlet-name>Servletsqlmvccookie</Servlet-name>      <Servlet-class>Com.javaweb.action.ServletSqlMvcCookie</Servlet-class>  </servlet>  <servlet-mapping>      <Servlet-name>Servletsqlmvccookie</Servlet-name>      <Url-pattern>*.do</Url-pattern>  </servlet-mapping>  <servlet>        <Servlet-name>Imageservlet</Servlet-name>        <Servlet-class>Com.javaweb.action.ImageServlet</Servlet-class></servlet><servlet-mapping>        <Servlet-name>Imageservlet</Servlet-name>        <Url-pattern>/imageservlet</Url-pattern></servlet-mapping></Web-app>

Finally, just change the login method

 Public voidLogin (httpservletrequest req, HttpServletResponse resp)throwsservletexception, ioexception {User User=NewUser (); String username=req.getparameter ("username");        User.setusername (username); String Password=req.getparameter ("Password");                User.setpassword (password); String Piccode= (String) req.getsession (). getattribute ("Piccode"); String Checkcode=req.getparameter ("Checkcode");//Take value//checkcode=checkcode.touppercase (); //converts all characters to uppercase (this statement can be used to verify that the code is case-insensitive)Resp.setcontenttype ("TEXT/HTML;CHARSET=GBK");//Solve garbled problems                if(Checkcode.equals (Piccode)) {User use=userservive.login (user); if(use!=NULL) {String [] ischeck=req.getparametervalues ("Ischeck"); if(ischeck!=NULL&& "true". Equals (ischeck[0])){                    //Add cookie InformationCookie usernamecookie=NewCookie ("username"), username); Cookie Passwordcookie=NewCookie ("password"), password); Usernamecookie.setmaxage (60*60*24*1);//DayPasswordcookie.setmaxage (60*60*24*1);                    Resp.addcookie (Usernamecookie);                Resp.addcookie (Passwordcookie); } resp.sendredirect ("Loginsuccess.jsp"); }Else{resp.sendredirect ("Loginfail.jsp"); }        }Else{resp.sendredirect ("Loginfail.jsp"); }    }

The verification code is wrong.

Jsp-5 Generate verification code and verify

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.