-
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=GBK"); PrintWriter out = response.getWriter(); //ServletOutputStream out=response.getOutputStream(); //定义数组储存验证码 char[] strChar=new char[]{'a','b','c','d','e','f','g','h','k','j','想','中','天','地','华','1','2','3','4','5','6','7','8','9','0'}; //位图 BufferedImage image=new BufferedImage(60,50,BufferedImage.TYPE_INT_RGB); Graphics gra=image.getGraphics(); //设置背景色 gra.setColor(Color.white); gra.fillRect(0, 0, 60, 50); //设置字体以及大小 gra.setColor(Color.red); gra.setFont(new Font("宋体",Font.BOLD,15)); String strTest=""; char strNum=0; //生成随机种子 Random r=new Random(new Date().getTime()); //循环得到4个随机值 for (int i = 0; i < 4; i++) { //确定随机值 strNum=strChar[r.nextInt(strChar.length)]; //存储验证码 strTest+=strNum; //描绘验证码 gra.drawString(Character.toString(strNum), i*15, 35); } System.out.println(strTest); //转码上色输出 // com.sun.image.codec.jpeg.JPEGImageEncoder encoder=com.sun.image.codec.jpeg.JPEGCodec.createJPEGEncoder(out); // encoder.encode(image); //在servlet上显示有颜色,这里我保存在作用域中,注释上两行以及outputStream,49行 //在页面上加上背景图片显色,字体颜色不会显示 request.setAttribute("strTest", strTest); request.getRequestDispatcher("../main.jsp").forward(request, response); }