/**
*servlet
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
response.setCharacterEncoding("utf-8");
request.setCharacterEncoding("utf-8");
//生成随机数字
int width =80;
int height=30;
String code = "";
Random random = new Random();
//循环连接字符串
for(int i=0;i<4;i++){
code+= String.valueOf((char)(65 + random.nextInt(26)));
}
//保存这个字符到session
HttpSession session = request.getSession();
session.setAttribute("code", code);
//生成图片
BufferedImage bg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
//将验证码写到图片上
Graphics2D g = bg.createGraphics();
g.setColor(Color.white);
g.fillRect(0, 0, width, height);
g.setColor(Color.darkGray);
for(int i = 0 ; i < 5; i++){
int x1 = random.nextInt(width);
int x2 = random.nextInt(width);
int y1 = random.nextInt(height);
int y2 = random.nextInt(height);
g.drawLine(x1, y1, x2, y2);
}
g.setColor(Color.LIGHT_GRAY);
for(int i = 0 ; i < 1000 ; i++){
int x = random.nextInt(width);
int y = random.nextInt(height);
g.drawLine(x, y, x, y);
}
// 边框
g.setColor(Color.gray);
g.drawRect(0, 0, width -1, height -1);
// 写字
g.setColor(Color.GRAY);
g.setFont(new Font("微软雅黑",Font.BOLD , 18));
g.drawString(code, 10, 22);
//响应到客户端
response.setContentType("image/gif");
ServletOutputStream sos = response.getOutputStream();
ImageIO.write(bg, "gif", sos);
sos.close();
}
<!--调用的页面的javascript-->
<script type="text/javascript">
function changeCode(sender){
//在servlet后面要添加一个随机数来保证每次的点击都是获得不同的图片
sender.src = 'checkPic?rand=' + Math.random();
}
</script>
7336

被折叠的 条评论
为什么被折叠?



