package ? com.hull.validatecode; ?
? ?
? import ? java.util.*; ?
? import ? java.io.*; ?
? import ? java.awt.*; ?
? import ? java.awt.image.*; ?
? ?
? import ? javax.servlet.*; ?
? import ? javax.servlet.http.*; ?
? ?
? import ? com.sun.image.codec.jpeg.*; ?
? ?
? public ? class ? ValidateCode ? extends ? HttpServlet ?
? { ?
? private ? Font ? imgFont ? = ? new ? Font("宋體",Font.BOLD,16); ? //設置字體 ?
? ?
? public ? void ? doGet(HttpServletRequest ? request,HttpServletResponse ? response) ?
? ? ? throws ? ServletException,IOException ?
? { ?
? doPost(request,response); ?
? } ?
? ?
? public ? void ? doPost(HttpServletRequest ? request,HttpServletResponse ? response) ? ?
? ? ? throws ? ServletException,IOException ?
? { ?
? String ? vCode ? = ? ""; ?
? int ? ? intCode ? = ? 0; ?
? ?
? ?
? intCode ? = ? (new ? Random()).nextInt(9999); ?
? if(intCode<1000) ? ?
? ? ? ? intCode ? += ? 1000; ?
? vCode ? = ? intCode+""; ?
? ?
? /* ?
? ? * ? 繪圖 ?
? ? */ ?
? response.setContentType("image/gif"); ?
? ServletOutputStream ? vout ? = ? response.getOutputStream(); ?
? BufferedImage ? image ? = ? new ? BufferedImage(50,20,BufferedImage.TYPE_INT_RGB); ?
? Graphics ? graph ? = ? image.getGraphics(); ?
? ?
? // ? 設置背景顏色 ?
? graph.setColor(Color.white); ?
? graph.fillRect(1,1,48,18); ?
? ?
? //設置字體顏色 ?
? graph.setColor(Color.black); ?
? graph.setFont(imgFont); ?
? ?
? char ? c; ?
? for(int ? i=0;i<4;i++) ?
? { ?
? c ? = ? vCode.charAt(i); ?
? graph.drawString(c+"",9*i+4,16); ? ?
? } ?
? ?
? JPEGImageEncoder ? encoder ? = ? JPEGCodec.createJPEGEncoder(vout); ?
? encoder.encode(image); ?
? ?
? // ? 對session賦值 ?
? HttpSession ? session ? = ? request.getSession(true); ?
? session.removeAttribute("VerifyCode"); ?
? session.setAttribute("VerifyCode",vCode); ?
? ?
? vout.close(); ?
? } ?
? ?
? } ?
? ?
? 調用: ?
? <img ? src="ValidateCode" ? align="center">