Java randomly generates instances of the captcha of that support uppercase and lowercase letters Numbers and random fonts
- 2020-04-01 01:53:37
- OfStack
The code is as follows:
package com.hoo.util;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* <b>function:</b> Captcha generation utility class
* @project NetWorkService
* @package com.hoo.util
* @fileName ValidCodeUtils.java
* @createDate 2010-8-3 In the afternoon 03:05:50
* @author hoojo
*/
@SuppressWarnings("unused")
public class ValidCodeUtils {
public static int WIDTH = 60;
public static int HEIGHT = 20;
public static int COLOR_FC_BG = 200;
public static int COLOR_BC_BG = 250;
public static int COLOR_FC_LINE = 160;
public static int COLOR_BC_LINE = 200;
public static int COLOR_FC_CODE = 20;
public static int COLOR_BC_CODE = 170;
private static Color getRandColor(int fc, int bc) {
Random random = new Random();
if (fc < 0)
fc = 0;
if (bc < 0)
bc = 1;
if (fc > 255)
fc = 255;
if (bc > 255)
bc = 255;
if (bc == fc)
bc += 10;
int temp = 0;
if (bc < fc) {
temp = bc;
bc = fc;
fc = temp;
}
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);
}
/**
* <b>function:</b> Image generation method
* @createDate 2010-8-3 In the afternoon 03:06:22
* @author hoojo
* @param request HttpServletRequest
* @param response HttpServletResponse
* @return boolean
* @throws Exception
*/
public static boolean getImage(HttpServletRequest request, HttpServletResponse response) throws Exception{
response.reset();
response.setContentType("image/jpeg");
//Set the page not to be cached
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
//Creating an image in memory & NBSP;
BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
//Getting the graphics context
Graphics img = image.getGraphics();
//Generate random class
Random random = new Random();
//Setting the background color
img.setColor(getRandColor(COLOR_FC_BG, COLOR_BC_BG));
img.fillRect(0, 0, WIDTH, HEIGHT);
//Set the font
img.setFont(new Font("Times New Roman", Font.PLAIN, 18));
//Picture frame
// g.setColor(new Color());
// g.drawRect(0,0,width-1,height-1);
//Randomly generated 155 interference lines, so that the authentication code in the image is not easy to be detected by other programs
img.setColor(getRandColor(COLOR_FC_LINE, COLOR_BC_LINE));
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);
img.drawLine(x, y, x + xl, y + yl);
}
//Take the randomly generated authentication code (4 digits)
String codeValue = "";
for (int i = 0; i < 4; i++) {
//String rand = String.valueOf(random.nextInt(10));
String rand = getRandomChar();
codeValue = codeValue.concat(rand);
img.setFont(getRandomFont());//Random font
//Displays the authentication code in the image
img.setColor(getRandColor(COLOR_FC_CODE, COLOR_BC_CODE));
img.drawString(rand, 13 * i + 6, 16);
}
request.getSession().setAttribute("codeValue", codeValue);
//The image effect
img.dispose();
//Output image to page
return ImageIO.write(image, "JPEG", response.getOutputStream());
}
/**
* Randomly generated characters, including uppercase, lowercase, and number
* <b>function:</b> function
* @createDate 2010-8-23 In the morning 10:33:55
* @author hoojo
* @return
*/
public static String getRandomChar() {
int index = (int) Math.round(Math.random() * 2);
String randChar = "";
switch (index) {
case 0://Uppercase characters
randChar = String.valueOf((char)Math.round(Math.random() * 25 + 65));
break;
case 1://Lowercase characters
randChar = String.valueOf((char)Math.round(Math.random() * 25 + 97));
break;
default://digital
randChar = String.valueOf(Math.round(Math.random() * 9));
break;
}
return randChar;
}
/**
* <b>function:</b> Randomly generate font, text size
* @createDate 2010-8-23 In the morning 10:44:22
* @author hoojo
* @return
*/
public static Font getRandomFont() {
String[] fonts = {"Georgia", "Verdana", "Arial", "Tahoma", "Time News Roman", "Courier New", "Arial Black", "Quantzite"};
int fontIndex = (int)Math.round(Math.random() * (fonts.length - 1));
int fontSize = (int) Math.round(Math.random() * 4 + 16);
return new Font(fonts[fontIndex], Font.PLAIN, fontSize);
}
}
Where the value of the captcha is saved in session In: request.getSession().setAttribute("codeValue", codeValue);
Compare the values entered by the user to session In the codeValue Equal or not;
The following is jsp Page calls servlet : ValidCodeServlet.java
ValidCodeServlet The above is called in ValidCodeUtils Captcha generation utility class
package com.hoo.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 com.hoo.util.ValidCodeUtils;
@SuppressWarnings("serial")
public class ValidCodeServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
ValidCodeUtils.getImage(request, response);
} catch (Exception e) {
e.printStackTrace();
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
jsp Page calls servlet Methods can be
js : reloadValidCode methods
function reloadValidCode(o) {
o.src = "${pageContext.request.contextPath }/validCodeServlet?timed=" + new Date().getMilliseconds();
}
Here, "timed=" + new Date().getMilliseconds(); Is to prevent IE Cache with
html Tags:
<img src="${pageContext.request.contextPath }/validCodeServlet" title=" It's hard to see. Hit refresh " onclick="reloadValidCode(this)"/>
Directly with Servlet name-configured url Can, and web.xml Configure the correspondence. Main invocation path ${pageContext.request.contextPath }/validCodeServlet This will bring the root directory, more safe.
web.xml In the validCodeServlet configuration
<servlet>
<servlet-name>validCodeServlet</servlet-name>
<servlet-class>com.hoo.servlet.ValidCodeServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>validCodeServlet</servlet-name>
<url-pattern>/validCodeServlet</url-pattern>
</servlet-mapping>