"Javaweb" (one) Java implementation Verification Code production

Source: Internet
Author: User

1. Using the servlet to implement the verification Code

First create the project, implement the JSP code:

<script type= "Text/javascript" >function Reloadcode () {var time = new Date (). GetTime ();d Ocument.getelementbyid (" Image_code "). src =" <%=path%>/servlet/imageservlet?d= "+ Time;} </script>
The reload function has a parameter of D, which is to prevent the browser from being flushed with the same address. It can be seen that our IMG tag is populated with Servlets, followed by our Imageservlet:
<span style= "White-space:pre" ></span>protected void Doget (HttpServletRequest req, HttpServletResponse RESP) throws Servletexception, IOException {bufferedimage bi = new BufferedImage (BUFFEREDIMAGE.TYPE_INT_RGB); Graphics g = bi.getgraphics (); Color c = new color (255), G.setcolor (c), G.fillrect (0, 0, 68, 22);//Generate 26 English alphabet array char[] ch = "Abcdefghijklmnopqrst Uvwxyz ". ToCharArray ();//randomly get 4 characters of random r = new random (); int len = Ch.length;int index = 0; StringBuffer sb = new StringBuffer (); for (int i = 0; i < 4; i++) {index = R.nextint (len); G.setcolor (New Color (r.nextint (n), R.nextint (188), R.nextint (255)), g.drawstring (Ch[index] + "", I * 3 +); Sb.append (Ch[index]);} Req.getsession (). SetAttribute ("Check_code", sb.tostring ()); Imageio.write (BI, "JPG", Resp.getoutputstream ());}
It is only possible to rewrite the servlet's Doget method.

Next is the verification code:

public void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException { Request.setcharacterencoding ("UTF-8"); Response.setcontenttype ("Text/html;charset=utf-8"); String checkcode = (string) request.getsession (). getattribute ("Check_code"); String Usercode = Request.getparameter ("Check_code"); PrintWriter out = Response.getwriter (), if (Checkcode.equals (Usercode)) {out.print ("Verify code entered correctly");} else {Out.print (" Verification code input Error ");} Out.close ();}
If you do not want to be case-sensitive, you can convert the Usercode to uppercase when you get it.


2. Using the Jcaptcha component to implement the verification CodeJcaptcha is a Java open source component used to generate graphical verification codes, which is also very easy to use. Often used in combination with spring, you can generate multiple forms of verification code. Jcaptcha is an open-source component,first, the JSP code:

<form action= "Submit.action" method= "POST" >      <input type= "text" Name= " Japtcha "value=" "/>     <input type=" Submit "/></form>
then you need to import several of these open source jar packages, which are available in the project behind.

Then configure the Web. xml

<web-app><display-name>simple Image Captcha Servlet sample</display-name><servlet>< Servlet-name>jcaptcha</servlet-name><servlet-class> com.octo.captcha.module.servlet.image.simpleimagecaptchaservlet</servlet-class></servlet>< Servlet><servlet-name>submit</servlet-name><servlet-class> com.octo.captcha.module.servlet.image.sample.submitactionservlet</servlet-class></servlet>< servlet-mapping><servlet-name>jcaptcha</servlet-name><url-pattern>/jcaptcha.jpg</ Url-pattern></servlet-mapping><servlet-mapping><servlet-name>submit</servlet-name> <url-pattern>/submit.action</url-pattern></servlet-mapping></web-app>
Finally, the code that submits the servlet:

protected void DoPost (HttpServletRequest request,httpservletresponse response) throws Servletexception, IOException { Response.setcontenttype ("Text/html;charset=utf-8"); String usercaptcharesponse = Request.getparameter ("Japtcha"); Boolean captchapassed = Simpleimagecaptchaservlet.validateresponse (Request, Usercaptcharesponse), if (captchapassed) Response.getwriter (). Write ("Captcha passed"), else {response.getwriter (). Write ("Captcha failed");} Response.getwriter (). Write ("<a href= ' index.jsp ' >try again</a>");}
is also very simple.


3. Using Kaptcha to implement verification codeKaptcha is also a very useful verification code generation tool, with it, you can generate various styles of verification code, because it is configurable.

(1). First, the combination of alphabetic array validation

Import Package kaptcha-2.3.jar,index.jsp First:

<form action= "check.jsp" > <input type= "text" name= "R" ><input type= " Submit "Name=" S "> <br></form>
in the Web. config reconfiguration:

<servlet><servlet-name>kaptcha</servlet-name><servlet-class> Com.google.code.kaptcha.servlet.kaptchaservlet</servlet-class></servlet><servlet-mapping> <servlet-name>kaptcha</servlet-name><url-pattern>/randomcode.jpg</url-pattern></ Servlet-mapping>
check.jsp The verification code is correct:

<%//Check if the verification code is correct String k = (string) session.getattribute (Com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY); String str = request.getparameter ("R"), if (K.equals (str)) {Out.print ("true");} Out.print (k + "---" + str);%>
(2). Detailed configuration of the. Kaptcha

You can configure multiple settings within the <init-param> tab of the <servlet> tag in Web. xml:

1). Whether to add a border:

<description> picture border, legal value:yes,no</description><param-name>kaptcha.border</param-name>< Param-value>yes</param-value>
2). Set the border color:
<description> border color, legal value: White, black, blue and other </description><param-name>kaptcha.border.color</ Param-name><param-value>black</param-value>

3). Border Thickness:

<description> border thickness, legal value: 0 </description><param-name>kaptcha.border.thickness</param-name ><param-value>1</param-value>

3). Picture width:

<description> Picture Width </description><param-name>kaptcha.image.width</param-name>< Param-value>100</param-value>

4). Picture height:

<description> Picture Height </description><param-name>kaptcha.image.height</param-name>< Param-value>50</param-value>

5). Picture Implementation class:

<description> Picture Implementation Class </description><param-name>kaptcha.producer.impl</param-name>< Param-value>com.google.code.kaptcha.impldefaultkaptcha</param-value>

6). Text Implementation class:

<description> Text Implementation class </description><param-name>kaptcha.textproducer.impl</param-name>< Param-value>com.google.code.kaptcha.text.impldefaulttextcreator</param-value>

7). Verification Code Configuration:

<description> text collection, validating code values get </description><param-name>kaptcha.textproducer.char.string</from this collection Param-name><param-value>abcde234567gfmnopq</param-value>

8). Verification Code Length:

<description> Verification Code Length 5</description><param-name>kaptcha.textproducer.char.length</param-name ><param-value>2</param-value>

9). Captcha Font:

<description> Font arial,courier</description><param-name>kaptcha.textproducer.font.names</ Param-name><param-value>arial, courier</param-value>

10). captcha Font Size:

<description> Font Size 40px</description><param-name>kaptcha.textproducer.font.size</param-name ><param-value>40</param-value>

11). Captcha Font Color:

<description> font Color, legal value: white, black and other </description><param-name>kaptcha.textproducer.font.color </param-name><param-value>black</param-value>

12). Captcha Text interval:

<description> text Interval </description><param-name>kaptcha.textproducer.char.space</param-name ><param-value>2</param-value>

13). Verification Code interference implementation class:

<description> interference Implementation Class </description><param-name>kaptcha.noise.impl</param-name>< Param-value>com.google.code.kaptcha.impl.defaultnoise</param-value>

14). Interference Color:

<description> interference color, legal value: R, G, B or black </description><param-name>kaptcha.noise.color</ Param-name><param-value>black</param-value>

15). Captcha Picture Style:

<description> Picture Style: Watermark com.google.code.kaptcha.impl.WaterRipple, fish eye com.google.code.kaptcha.impl.FishEyeGimpy , shadow Com.google.code.kaptcha.impl.ShadowGimpy, etc. </description><param-name>kaptcha.obscurificator.impl </param-name><param-value>com.google.code.kaptcha.impl.WaterRipple</param-value>

16). Background implementation class:

<description> Background Implementation class </description><param-name>kaptcha.background.impl</param-name>< Param-value>com.google.code.kaptcha.impl.defaultbackground</param-value>

17). Background color Gradient-start color:

<description> Color Gradient-Start color </description><param-name>kaptcha.background.clear.from</param-name ><param-value>green</param-value>

18). Background color Gradient-end color:

<description> Color Gradient-end color </description><param-name>kaptcha.background.clear.to</param-name ><param-value>white</param-value>

19). Text renderer:

<description> Text Renderer </description><param-name>kaptcha.word.impl</param-name>< Param-value>com.google.code.kaptcha.text.impl.defaultwordrenderer</param-value>

20). Verification code in session to store the verification code key key configuration:

Key key to store verification code in <description>session </description><param-name>kaptcha.session.key</param-name ><param-value>KAPTCHA_SESSION_KEY</param-value>

(3). Implementation of Chinese verification Code

The first is the class in which we generate Chinese:

public class Chinesetext extends configurable implements Textproducer {public String getText () {int length = GetConfig (). g Ettextproducercharlength (); String Finalword = "", FirstWord = ""; int tempint = 0; String[] Array = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "B", "C", "D", "E", "F"}; Random rand = new Random (), for (int i = 0, i < length; i++) {switch (Rand.nextint (array.length)) {Case 1:tempint = Rand . Nextint (+) + 65;firstword = string.valueof ((char) tempint); Break;case 2:int r1,r2,r3,r4; String strh,strl;//high&lowr1 = Rand.nextint (3) + 11; Front closed open [11,14] if (r1 = =) {r2 = Rand.nextint (7);} else {r2 = Rand.nextint (16);} R3 = Rand.nextint (6) + 10;if (R3 = =) {R4 = Rand.nextint (+ 1),} else if (r3 = =) {R4 = Rand.nextint);} else {R4 = Rand.nextint (16);} STRH = Array[r1] + Array[r2];strl = Array[r3] + array[r4];byte[] bytes = new Byte[2];bytes[0] = (byte) (Integer.parseint (s TrH)); bytes[1] = (byte) (Integer.parseint (StrL, +)); FirstWord = new String (byTES); break;default:tempint = Rand.nextint (+) + 48;firstword = string.valueof ((char) tempint); break;} Finalword + = FirstWord;} return Finalword;}}
You need to inherit the configurable class to implement the Textproducer interface. Then configure it in Web. xml:

<init-param><description> Text Implementation class </description><param-name>kaptcha.textproducer.impl</ Param-name><param-value>com.thr.text.chinesetext</param-value></init-param>
Note that we are here to specify the full name of the class.

If the input Chinese detection is garbled, modify the check.jsp:

<%//Check if the verification code is correct String k = (string) session.getattribute (Com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY); String str = Request.getparameter ("R"), str = new String (str.getbytes ("iso-8859-1"), "UTF-8"), if (K.equals (str)) { Out.print ("true");} Out.print (k + "---" + str);%>
(4). Implementation of verification code for calculation We're going to write a servlet to implement:
public class Kaptchaservlet extends HttpServlet implements Servlet {private Properties props;private Producer Kaptchaprod Ucer;private String sessionkeyvalue;public Kaptchaservlet () {this.props = new Properties (); this.kaptchaproducer = null; This.sessionkeyvalue = null;} public void init (ServletConfig conf) throws Servletexception {super.init (conf); Imageio.setusecache (false); Enumeration initparams = Conf.getinitparameternames (); while (Initparams.hasmoreelements ()) {string key = (string) Initparams.nextelement (); String value = Conf.getinitparameter (key); This.props.put (key, value);} Config config = new config (this.props); this.kaptchaproducer = Config.getproducerimpl (); this.sessionkeyvalue = Config.getsessionkey ();} public void Doget (HttpServletRequest req, HttpServletResponse resp) throws Servletexception, IOException { Resp.setdateheader ("Expires", 0L), Resp.setheader ("Cache-control", "No-store, No-cache, must-revalidate"); Resp.addheader ("Cache-control", "post-check=0, pre-check=0"); Resp.setheaDer ("Pragma", "No-cache"); Resp.setcontenttype ("Image/jpeg"); String Captext = This.kaptchaProducer.createText (); String S1 = captext.substring (0, 1); String s2 = captext.substring (1, 2), int r = integer.valueof (S1). Intvalue () + integer.valueof (S2). Intvalue (); Req.getsession (). SetAttribute (This.sessionkeyvalue, string.valueof (R)); BufferedImage bi = this.kaptchaProducer.createImage (S1 + "+" + s2+ "=?"); Servletoutputstream out = Resp.getoutputstream (): Imageio.write (bi, "JPG", out), try {Out.flush ();} finally {Out.close () ;}}}
then replace the servlet that we used earlier in Web. Xml.


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

"Javaweb" (one) Java implementation Verification Code production

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.