标签:
一.jsp页面
<script language="javascript" type="text/javascript">
//刷新验证码
function showRand(){
document.getElementById("random").src = "<%=path%>/common/image.jsp?date=" + new date();
}
</script>
<body>
<p class="test" id="p_randCode" style="display:none">
<b>验证码</b>
<input type="text" value="" class="txt_change" id="confirmCode" name="confirmCode">
<img align="middle" border=0 src="image.jsp" id="random" height="20">
<a style="cursor: pointer;align:left" onclick="showRand();" >换一张</a>
<input type="hidden" id="confirmRand" name="confirmRand" />
</p>
</body>
二.显示验证码图片的image.jsp
<%@ page contentType="image/jpeg" import="com.sun.image.codec.jpeg.*,java.awt.image.*,java.awt.*,java.util.*"%>
<%
request.setCharacterEncoding("GBK");
response.setContentType("text/html; charset=GBK");
String rand = "0000";//随机生成验证码
if(request.getParameter("rand") != null){
rand = (String)request.getParameter("rand");
request.getSession().setAttribute("rand",rand);
}
try{
out.clear();
response.setContentType("image/jpeg");
response.addHeader("pragma", "NO-cache");
response.addHeader("Cache-Control", "no-cache");
response.addDateHeader("Expries", 0);
int width = 60, height = 20;
BufferedImage image = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
Random random = new Random();
int fc = 200, bc = 255;
if (fc > 255) {
fc = 255;
}
if (bc > 255) {
bc = 255;
}
int red = fc + random.nextInt(bc - fc);
int green = fc + random.nextInt(bc - fc);
int blue = fc + random.nextInt(bc - fc);
Color color = new Color(red, green, blue);
g.setColor(color);
g.setFont(new Font("Times New Roman", Font.PLAIN, 18));
g.fillRect(0, 0, width, height);
for (int i = 0; i < 100; 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);
}
int stringLength = 4;
String sRand="";
for (int i = 0; i < stringLength; i++) {
String randStr = String.valueOf(rand.charAt(i));
sRand+=randStr;
g.setColor(new Color(20 + random.nextInt(110), 20 + random
.nextInt(110), 20 + random.nextInt(110)));
g.drawString(randStr, 13 * i + 6, 16);
}
session.setAttribute("ccode",sRand);
g.dispose();
ServletOutputStream outStream = response.getOutputStream();
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(outStream);
encoder.encode(image);
outStream.close();
out.clear();
out = pageContext.pushBody();
} catch (Exception e){
}
%>
标签:
原文地址:http://www.cnblogs.com/songjinduo/p/4642072.html