页面代码
<script type="text/javascript" src="E:\01\web\js\jquery.js"></script>
<script type="text/javascript">
//点击看不清重新刷新图片,但是流浪其带有缓存功能,不会多次请求相同数据
$(function () {
$("a").click(function () {
$("img").attr("src","validcode?date="+new Date());
return false;
})
})
</script>
</head>
<body>
<form action="" method="post">
用户名:<input type="text" name="username"/></br>
密码:<input type="text" name="username"/></br>
验证码:<input type="text" size="1" /><img src="validcode" width="80" height="40"><a href="">看不清</a></br>
<input type="submit" value="登录">
<input type="reset" value="重置">
</form>
这里的js需要导入个jquery-1.7.2,百度下载即可;
主要代码
@WebServlet("/validcode")
public class ValidCodeServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//创建一张图片
BufferedImage image=new BufferedImage(200,100,BufferedImage.TYPE_INT_RGB);
Graphics2D gra = image.createGraphics();
gra.setColor(Color.WHITE);
//填充,前两个为从哪个坐标开始填充。后两个区域为举行区域
gra.fillRect(0,0,200,100);
List<Integer> randList=new ArrayList<Integer>();
Random random=new Random();
for (int i=0;i<4;i++){
randList.add(random.nextInt(10));
}
//设置字体
gra.setFont(new Font("宋体",Font.BOLD,40));
Color[] colors=new Color[]{Color.RED,Color.BLUE,Color.YELLOW,Color.PINK,Color.GRAY,Color.GREEN};
for (int i = 0; i<randList.size(); i++){
gra.setColor(colors[random.nextInt(colors.length)]);
gra.drawString(randList.get(i)+"",i*40,70+(random.nextInt(21)-10));
}
gra.drawString("",0,50);
for (int i=0;i<2;i++){
gra.setColor(colors[random.nextInt(colors.length)]);
//画横线
gra.drawLine(0,random.nextInt(101),200,random.nextInt(101));
}
ServletOutputStream outputStream = resp.getOutputStream();
ImageIO.write(image,"jpg",outputStream);
Comments | 1 条评论
一言不合就上代码。