由后台生成验证码,传给前台,前台输入后传给后台,后台进行验证。写了这句废话,哈哈哈。
中间出了点小问题,就是<img src="image.jsp" >
,我也不知道什么情况,前面好几次点击图片都没反应。
这个image.jsp是配置在web.xml中用来指向ImgAction,而ImgAction由ValidCodeUtil产生验证码并提供validateCode()用于登录的验证码验证。
1、login.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>登录页面</title>
<script>
function loadimage() {
document.getElementById("image").src = "image.jsp?" + Math.random();
}
</script>
</head>
<body>
<form action="login!loging.action">
用户名:<input type="text" name="userName" id="userName"/><br/>
密码:<input type="password" name="password" id="password"/><br/>
输入验证码:<input type="text" name="validCode" id="validCode" class="validCode"/>
<img src="image.jsp" id="image">
<a href="javascript:loadimage()">看不清点我</a><br/>
<input type="submit" value="提交"/>
</form>
</body>
</html>
2)ImgAction(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.cmcc.db.util.ValidCodeUtil;
/**
* Servlet implementation class ImgBuilder
*/
public class ImgAction extends HttpServlet {
private static final long serialVersionUID = 1L;
public void init() throws ServletException {
super.init();
}
public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ValidCodeUtil.sendValidCodeImageToResponse(request, response);
}
}
3)ValidCodeUtil.java
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ValidCodeUtil {
private final static Logger LOGGER = LoggerFactory.getLogger(ValidCodeUtil.class);
private final static String VALID_CODE_SESSION_KEY = "verifyCode";
public static void sendValidCodeImageToResponse(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
response.setContentType("image/jpeg");
int width = 80, 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.setColor(new Color(255, 255, 255));
g.fillRect(0, 0, width - 1, height - 1);
g.drawRect(0, 0, width - 1, height - 1);
g.setFont(new Font("Times New Roman", Font.PLAIN, 18));
//随机产生干扰线
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 sRand = "";
for (int i = 0; i < 4; i++) {
String tmp = getRandomChar();
sRand += tmp;
g.setColor(new Color(20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random.nextInt(110)));
g.drawString(tmp, 15 * i + 10, 15);
}
HttpSession session = request.getSession();
session.setAttribute(VALID_CODE_SESSION_KEY, sRand);
g.dispose();
ImageIO.write(image, "JPEG", response.getOutputStream());
}
public static boolean validateCode(HttpServletRequest request, String validCode) {
String sessionCode = (String) request.getSession().getAttribute(VALID_CODE_SESSION_KEY);
request.getSession().removeAttribute(VALID_CODE_SESSION_KEY);
if (!StringUtils.isBlank(sessionCode) && sessionCode.equalsIgnoreCase(validCode))
return true;
else
return false;
}
private static String getRandomChar() {
int rand = (int) Math.round(Math.random());
long itmp = 0;
char ctmp = '\u0000';
switch (rand) {
case 1:
itmp = Math.round(Math.random() * 25 + 65);
ctmp = (char) itmp;
return String.valueOf(ctmp);
case 2:
itmp = Math.round(Math.random() * 25 + 97);
ctmp = (char) itmp;
return String.valueOf(ctmp);
default:
itmp = Math.round(Math.random() * 9);
return String.valueOf(itmp);
}
}
private static Font getMyFont() {
Font font = null;
try {
String url = Thread.currentThread().getContextClassLoader().getResource("../../font/").getPath();
File ff = new File(url, "Monaco.ttf");
font = Font.createFont(Font.PLAIN, ff).deriveFont(14f);
} catch (Exception e) {
LOGGER.error("getFontError", e);
}
return font;
}
private static Color getRandColor(int fc, int bc) {
int fcTemp = fc;
int bcTemp = bc;
Random random = new Random();
if (fcTemp > 255)
fcTemp = 255;
if (bcTemp > 255)
bcTemp = 255;
int r = fcTemp + random.nextInt(bcTemp - fcTemp);
int g = fcTemp + random.nextInt(bcTemp - fcTemp);
int b = fcTemp + random.nextInt(bcTemp - fcTemp);
return new Color(r, g, b);
}
}
还有LoginAction中对ValidCodeUtil.validateCode(request, validCode)的调用,这里就不多咯嗦啦,要是你有更好的方法,欢迎留言哦(^__^)