Here I use the struts2 to simulate a login function to verify the Java implementation of the verification code function.
Steps for Java Implementation Verification code:
1, the creation of Randomimagegenerator.java class, this class to achieve the validation code picture generation
2, create a servlet class, Randomimageservlet.java, output the generated verification code to the page
3, create an action class, Loginaction.java, control login
4. Configure Struts.xml a Web.xml file
5, write the page
The implementation is expressed in code
1. Create Randomimagegenerator.java class
Copy Code code as follows:
Package Com.tenghu.code;
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;
/**
* Verification Code Generation class
* @author Xiaohu
*
*/
public class Randomimagegenerator {
Creating Random objects
Static Random random=new Random ();
Random build contains Authenticode string
public static String random (int num) {
Initialize seed
string[] str={"0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
"A", "B", "C", "D", "E", "F", "G", "H", "I", "J",
"K", "L", "M", "N", "P", "Q", "R", "s", "T"};
int number=str.length;
Receive random characters
String text = "";
Randomly generated 4-character string
for (int i=0;i<num;i++) {
Text+=str[random.nextint (number)];
}
return text;
}
/**
* Randomly produces the defined color
*
* @return
*/
private static Color Getrandcolor () {
Random Random = new Random ();
Color color[] = new COLOR[10];
Color[0] = new Color (32, 158, 25);
COLOR[1] = new Color (218, 42, 19);
COLOR[2] = new Color (31, 75, 208);
COLOR[3] = new Color (0, 102, 182);
COLOR[4] = new Color (171, 0, 85);
Return Color[random.nextint (5)];
}
/**
* Generate random Fonts
*
* @return
*/
private static Font GetFont () {
Random Random = new Random ();
Font font[] = new FONT[5];
Font[0] = new Font ("Ravie", Font.Bold, 30);
FONT[1] = new Font ("Antique Olive Compact", Font.Bold, 30);
FONT[2] = new Font ("Forte", Font.Bold, 30);
FONT[3] = new Font ("Wide Latin", font.bold, 30);
FONT[4] = new Font ("Gill Sans Ultra Bold", Font.Bold, 30);
Return Font[random.nextint (5)];
}
/**
* Generate pictures
* @throws IOException
*/
public static void Render (String randomstr,outputstream out,int width,int height) throws ioexception{
Create an image in memory
BufferedImage bi=new bufferedimage (width, height, bufferedimage.type_byte_indexed);
Get Graphics context
Graphics2D g= (graphics2d) bi.getgraphics ();
Word border
G.setcolor (Color.White);
G.fillrect (0, 0, width, height);
G.setfont (GetFont ());
G.setcolor (Color.Black);
Draw the authentication code, each authentication code at the different horizontal position
String str1[]=new string[randomstr.length ()];
for (int i=0;i<str1.length;i++) {
Str1[i]=randomstr.substring (i,i+1);
int w=0;
int x= (i+1)%3;
Randomly generated verification code character horizontal offset
if (X==random.nextint (7)) {
W=30-random.nextint (7);
}else{
W=30+random.nextint (7);
}
Randomly generated colors
G.setcolor (Getrandcolor ());
g.DrawString (Str1[i], 20*i+10, W);
}
Randomly generated interference points, and different colors, the image of the authentication code is not easy to be detected by other programs
for (int i=0;i<100;i++) {
int X=random.nextint (width);
int y=random.nextint (height);
Color Color=new Color (random.nextint (255), Random.nextint (255), Random.nextint (255));
Randomly draw lines of various colors
G.setcolor (color);
G.drawoval (x, y, 0, 0);
}
Draw Interference Line
for (int i=0;i<15;i++) {
int X=random.nextint (width);
int y=random.nextint (height);
int X1=random.nextint (width);
int y1=random.nextint (height);
Color Color=new Color (random.nextint (255), Random.nextint (255), Random.nextint (255));
Draw various color lines randomly
G.setcolor (color);
G.drawline (x, y, x1, y1);
}
Image effective
G.dispose ();
Output page
Imageio.write (BI, "JPG", out);
}
public static void Main (string[] args) throws FileNotFoundException, IOException {
Get a random string
String Randomstr=random (5);
System.out.println (RANDOMSTR);
Generate pictures
Render (Randomstr, New FileOutputStream ("D:\\test.jpg"), 130,40);
}
}
2. Create Randomimageservlet.java
Copy Code code as follows:
Package com.tenghu.code.servlet;
Import java.io.IOException;
Import javax.servlet.ServletException;
Import Javax.servlet.http.HttpServlet;
Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse;
Import javax.servlet.http.HttpSession;
Import Com.tenghu.code.RandomImageGenerator;
public class Randomimageservlet extends HttpServlet {
Picture width
int width=0;
Picture height
int height=0;
Number of random characters on a picture
int randomstrnum=0;
public void Destroy () {
}
public void doget (HttpServletRequest request, httpservletresponse response)
Throws Servletexception, IOException {
DoPost (request, response);
}
public void DoPost (HttpServletRequest request, httpservletresponse response)
Throws Servletexception, IOException {
Request.setcharacterencoding ("UTF-8");
Get HttpSession Object
HttpSession session=request.getsession ();
Get a random string
String Randomstr=randomimagegenerator.random (Randomstrnum);
if (null!=session) {
Setting parameters
Session.setattribute ("Randomstr", randomstr);
Set response type, output picture client not Cached
Response.setdateheader ("Expires", 1L);
Response.setheader ("Cache-control", "No-cache, No-store, max-age=0");
Response.AddHeader ("Pragma", "No-cache");
Response.setcontenttype ("Image/jpeg");
Output to Page
Randomimagegenerator.render (Randomstr, Response.getoutputstream (), width, height);
}
}
public void Init () throws Servletexception {
Get width
Width=integer.parseint (This.getinitparameter ("width"));
Get height
Height=integer.parseint (This.getinitparameter ("height"));
Get number
Randomstrnum=integer.parseint (this.getinitparameter ("num"));
}
}
3. Create Loginaction.java Class
Copy Code code as follows:
Package com.tenghu.code.action;
Import Java.io.ByteArrayInputStream;
Import Java.io.InputStream;
Import Com.opensymphony.xwork2.ActionContext;
Import Com.opensymphony.xwork2.ActionSupport;
public class Loginaction extends actionsupport{
User name
Private String UserName;
Password
private String password;
Verification Code
Private String Code;
Private InputStream InputStream;
Public InputStream GetResult () {
return inputstream;
}
Success
Public String Success () throws exception{
return SUCCESS;
}
Test Login
Public String Testlogin () throws exception{
Get the validation code for a picture
String randomstr= (String) Actioncontext.getcontext (). GetSession (). Get ("Randomstr");
if (Code.trim (). Equalsignorecase (RANDOMSTR)) {
if ("admin". Equals (Username.trim ()) && "admin". Equals (Password.trim ()) {
Success
Inputstream=new Bytearrayinputstream ("1". GetBytes ("UTF-8"));
}else{
User name or password error
Inputstream=new Bytearrayinputstream ("2". GetBytes ("UTF-8"));
}
}else{
Validation code Error
Inputstream=new Bytearrayinputstream ("0". GetBytes ("UTF-8"));
}
return "result";
}
Public String GetUserName () {
return userName;
}
public void Setusername (String userName) {
This.username = UserName;
}
Public String GetPassword () {
return password;
}
public void SetPassword (String password) {
This.password = password;
}
Public String GetCode () {
return code;
}
public void Setcode (String code) {
This.code = code;
}
}
4, configure Struts.xml, web.xml files
Copy Code code as follows:
<?xml version= "1.0" encoding= "UTF-8"?>
<! DOCTYPE struts public
"-//apache Software foundation//dtd struts Configuration 2.3//en"
"http://str Uts.apache.org/dtds/struts-2.3.dtd ">
<struts>
<package name=" installs "extends=" Struts-default ">
<action name=" Login "class=" com.tenghu.code.action.LoginAction ">
<!--Login succeeded to success.jsp page-->
<result name= "Success" >success.jsp </result>
<!--Login Validation returns the data-->
<result name= "Result" type= Stream ">
<param name=" ContentType ">text/html</param>
<param name= "InputName" >result</param>
</result>
</action>
</package>
</struts>
Copy Code code as follows:
<?xml version= "1.0" encoding= "UTF-8"?>
<web-app version= "2.5"
Xmlns= "Http://java.sun.com/xml/ns/javaee"
Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"
Xsi:schemalocation= "Http://java.sun.com/xml/ns/javaee
Http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd ">
<servlet>
<description>this is the description i-Java component</description>
<display-name>this is the display name of my Java EE component</display-name>
<servlet-name>RandomImageServlet</servlet-name>
<servlet-class>com.tenghu.code.servlet.RandomImageServlet</servlet-class>
<!--initialize picture width-->
<init-param>
<param-name>width</param-name>
<param-value>130</param-value>
</init-param>
<!--initialize picture height-->
<init-param>
<param-name>height</param-name>
<param-value>40</param-value>
</init-param>
<!--initialization picture random number of-->
<init-param>
<param-name>num</param-name>
<param-value>4</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>RandomImageServlet</servlet-name>
<url-pattern>/verification.do</url-pattern>
</servlet-mapping>
<!--Configure Struts core filter-->
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
5, write the test page
Copy Code code as follows:
<%@ page language= "java" import= "java.util.*" pageencoding= "UTF-8"%>
<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >
<base href= "<%=basePath%>" >
<title>my JSP ' index.jsp ' starting page</title>
<script type= "Text/javascript" src= "Js/jquery-1.10.2.min.js" ></script>
<script type= "Text/javascript" src= "Js/jquery.form.js" ></script>
<script type= "Text/javascript" >
$ (document). Ready (function () {
Code.initcode ();
Validating input
function Checkinput () {
if ($ (' #userName '). val () = = ') {
Alert (' User name cannot be empty! ');
return false;
}
if ($ (' #password '). val () = = ') {
Alert (' Password cannot be empty! ');
return false;
}
if ($ (' #code '). val () = = ') {
Alert (' Verify code cannot be empty! ');
return false;
}
return true;
}
Click on the button
$ (' #btn '). Click (function () {
if (Checkinput () ==true) {
$ (' #login_request '). Ajaxsubmit ({
URL: ' Login!testlogin ',
Cache:false,
Type: ' POST ',
Success:function (data) {
if (data==0) {
Alert (' Authentication code Error! ');
Change the verification code
Code.initcode ();
}else if (data==1) {
Alert (' Login successful! ');
Submit to Login Success page
$ (' #login_request ') [0].submit ();
}else if (data==2) {
Alert (' Username or password is wrong! ');
Change the verification code
Code.initcode ();
}
},
Error:function (e) {
Alert (' A mistake! ');
}
});
}
});
});
var code={
Initialize Verification code
Initcode:function () {
$ ("#code_img"). attr ("src", "verification.do?rmd=" +new Date (). GetTime ())//If you need to click the picture to change the contents of the picture, you must add time to rub
. Click (function () {
$ (this). attr ("src", "verification.do?rmd=" +new Date (). GetTime ());
});
}};
</script>
<body>
<form action= "login!success" id= "Login_request" method= "POST" >
Username:<input type= "text" id= "UserName" name= "UserName"/><br/>
Password:<input type= "Password" id= "Password" name= "Password"/><br>
Verification_code:<input type= "text" id= "code" name= "code"/><br>
<input type= "button" id= "btn" value= "Login"/>
</form>
</body>
The success page is posted on the ministry, just a paragraph of text
Show Results: