利用servlet产生随机数,原理是获取Graphics对象进行绘图

时间:2022-04-19 15:50:10

public class ResonpeRandomImgDemo extends HttpServlet {

int width=100;

int height=30;

public void doGet(HttpServletRequest request, HttpServletResponse response)    throws ServletException, IOException {

response.setContentType("text/html;charset=utf-8");

//获取BufferedImage对象,并设置画布的大小还有类型

BufferedImage img=new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

//获取绘图对象

Graphics2D g =(Graphics2D)img.getGraphics();

//设置背景颜色

setBackgroudColor(g);

//产生随机数

getNum(g);

//把图形写给浏览器

response.setContentType("image/jpeg");

ImageIO.write(img, "jpg", response.getOutputStream());

}

private void getNum(Graphics2D g) {

String str="0123456789qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM";

g.setColor(Color.BLUE);

for (int i = 0; i < 4; i++) {

//产生随机数,%30为了产生随机数-30-30之间,这个也是旋转角度

int degee=new Random().nextInt()%30;

//进行旋转

g.rotate(degee*Math.PI/180 , 20+(i*12), 15);

g.setFont(new Font("宋体",Font.BOLD, 20));

g.drawString(str.charAt(new Random().nextInt(str.length()))+"", 20+(i*12), 15);

//旋转回来

g.rotate(-degee*Math.PI/180 , 20+(i*12), 15);

}

}

private void setBackgroudColor(Graphics2D g) {

g.setBackground(Color.WHITE);

g.fillRect(0, 0, width, height);

}

public void doPost(HttpServletRequest request, HttpServletResponse response)    throws ServletException, IOException {

doGet(request, response);

}

}

//jsp页面

<script type="text/javascript">
  function changeImg(){
   var img= document.getElementById("img");
   img.src=img.src+"?";
  }
 </script>

验证码:<img alt="" src="/ServletTest/servlet/ResonpeRandomImgDemo" id="img" onclick="changeImg()" style="cursor: pointer;">///ServletTest/servlet/ResonpeRandomImgDemo获取servelt页面的信息