Login Verification Code-----Implementation

Source: Internet
Author: User
Tags http post rand set background

method One (via servlet mode):

===========start================

public class Authimg extends HttpServlet {
private static final String Content_Type = "text/html; Charset=utf-8 ";

Private font mfont = new Font ("Times New Roman", Font.plain, 18);

Initialize Global Variables
public void init (ServletConfig conf) throws Servletexception {
Super.init (conf);
}

Process the HTTP Get request
public void doget (HttpServletRequest request, httpservletresponse response)
Throws Servletexception, IOException {
Response.setcontenttype ("Image/jpeg");
Response.setheader ("Pragma", "No-cache");
Response.setheader ("Cache-control", "No-cache");
Response.setdateheader ("Expires", 0);


Servletoutputstream out = Response.getoutputstream ();

int width =, height = 20;
BufferedImage image = new BufferedImage (width, height,
BUFFEREDIMAGE.TYPE_INT_RGB);

Graphics g = image.getgraphics ();
Random random = new random ();

G.setcolor (Getrandcolor (200, 250));
G.fillrect (0, 0, width, height);

G.setfont (Mfont);

G.setcolor (Getrandcolor (160, 200));
for (int i = 0; i < 155; i++) {
int x = random.nextint (width);
int y = random.nextint (height);
int xl = Random.nextint (12);
int yl = Random.nextint (12);
G.drawline (x, y, X + xl, y + yl);
}

String rand = Randomchar.getchars (3,4);
char c;
for (int i = 0; i < 4; i++) {
c = Rand.charat (i);
G.setcolor (New Color (+ random.nextint), + random
. Nextint (+), + random.nextint (110)); The call function comes out with the same color, possibly because the seed is too close, so it can only be generated directly
g.DrawString (String.valueof (c), * i + 6, 16);
}
HttpSession seesion = Request.getsession ();
Seesion.setattribute ("Authcode", Rand);
JPEGImageEncoder encoder = Jpegcodec.createjpegencoder (out);
Encoder.encode (image);
Out.close ();
}

Process the HTTP Post request
public void DoPost (HttpServletRequest request, httpservletresponse response)
Throws Servletexception, IOException {
Doget (request, response);
}

Clean up resources
public void Destroy () {
}

Private color Getrandcolor (int fc, int BC) {//given range get random color
Random random = new random ();
if (FC > 255) {
FC = 255;
}
if (BC > 255) {
BC = 255;
}
int r = FC + Random.nextint (BC-FC);
int g = FC + Random.nextint (BC-FC);
int B = FC + Random.nextint (BC-FC);
return new Color (R, G, b);
}

}

Configure------------web. xml

<servlet>
<servlet-name>authimg</servlet-name>
<servlet-class>com.ue.common.util.AuthImg</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>authimg</servlet-name>
<url-pattern>/authimg</url-pattern>
</servlet-mapping>

<servlet>

----------------JSP page and JS------------------

---js----

function getImage (URL)
{
$ ("#imgCode"). Removeattr ("src");
$ ("#authCode"). attr ("src", url+ "it=" +math.random ());
$ ("#imgCode"). attr ("src", url);
Document.forms[0].authcode.src=url;

}
---jsp----

<ul>
<li><li><li></ul>

-------------------
=========end===========

Method Two (action mode):

/**
* Verification Code generation
*/
public class Validatecodeaction extends Action {
/*
* Generated Methods
*/
/**
* Method Execute
* @param mapping
* @param form
* @param request
* @param response
* @return Actionforward
*/
Public Actionforward Execute (actionmapping mapping, Actionform form,
HttpServletRequest request, HttpServletResponse response) {

String operation = Request.getparameter (constants.operation_para_name);
New
try {
int width = 50;
int height = 18;
Get a 4-bit random alphanumeric string
String s = Randomstringutils.random (4, False, true);

Save in session to compare with user's input.
Note The session is cleared after the comparison is complete.
HttpSession session = Request.getsession (true);
Session.setattribute ("Validatecode", s);

Response.setcontenttype ("Images/jpeg");
Response.setheader ("Pragma", "No-cache");
Response.setheader ("Cache-control", "No-cache");
Response.setdateheader ("Expires", 0);

Servletoutputstream out = Response.getoutputstream ();
BufferedImage image = new BufferedImage (width, height,
BUFFEREDIMAGE.TYPE_INT_RGB);
Graphics g = image.getgraphics ();
Set Background color
G.setcolor (Getrandcolor (100, 250));
G.fillrect (0, 0, width, height);

Set font
Font mfont = new Font ("Arial", Font.Italic, 18);//Set Font
G.setfont (Mfont);

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

Randomly generated interference lines, so that the authentication code in the image is not easily detected by other programs
G.setcolor (Getrandcolor (160, 200));
Generating random classes
Random random = new random ();
for (int i = 0; i < 155; i++) {
int x2 = random.nextint (width);
int y2 = random.nextint (height);
int x3 = Random.nextint (12);
int y3 = Random.nextint (12);
G.drawline (x2, y2, x2 + x3, y2 + y3);
}

Display the authentication code to the image
G.setcolor (New Color (+ random.nextint), + random
. Nextint (+), + random.nextint (110));

g.DrawString (S, 2, 16);

Image effective
G.dispose ();
Output image to Page
Imageio.write ((bufferedimage) image, "JPEG", out);
Out.close ();
} catch (Exception e) {
E.printstacktrace ();
}
return null;
}
Private color Getrandcolor (int fc, int BC) {//given range get random color
Random random = new random ();
if (FC > 255)
FC = 255;
if (BC > 255)
BC = 255;
int r = FC + Random.nextint (BC-FC);
int g = FC + Random.nextint (BC-FC);
int B = FC + Random.nextint (BC-FC);
return new Color (R, G, b);
}
}

-----configuration-------in Struts-config.xml

<!--photo verification code--
<action path= "/pubvalidatecode" scope= "Request" type= "Admin.action.ValidatecodeAction" validate= "false" >
<forward name= "new" path= "/web-inf/admin/adminuser/edit.jsp"/>
</action>

----------------JSP page and JS------------------

---js----

<script type= "Text/javascript" >
function Changeimage () {
Location.href= "Pubvalidatecode.do?";
$ ("#aimage"). Removeattr ("src");
$ ("#aimage"). attr ("src", "pubvalidatecode.do?");
}
</script>

---jsp----

<li>
<span> Verification Code:</span>
&nbsp;<a href= "#" onclick= " Changeimage () "style=" FONT-SIZE:12PX; " > can not see clearly. Change a </a>
</li>

-------------------

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.