练习集合(一)

91 阅读1分钟

验证码

简介

注册使用的验证码功能。页面发起请求后,servlet生成随机字符,画在验证码区域, “看不清”是使用JS再次刷新请求。

Servlet

@WebServlet("/code")
public class codeServlet 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);
		//填充一个矩形(填充坐标x,y,填充的区域x,y)
		gra.fillRect(0,0,200,100);
		//定的坐标是所化内容的左下角,所以0,0坐标开始的话看不见所见内容
		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.ITALIC|Font.BOLD,40));
		Color[] colors = new Color[] {Color.RED,Color.YELLOW,Color.BLUE,Color.GREEN,Color.PINK,Color.GRAY};
		//内容,x,y
		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));
		}
		//画横线
		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
		ImageIO.write(image, "jpg", outputStream);
	}
}

index.jsp

……
<script type="text/javascript" src="WebContent/js/jquery-1.7.2.js"></script>
<script type="text/javascript">
$(function(){
	$("a").click(function(){
		//浏览器带有缓存功能,不会多次请求相同数据,所以需要传一个不一样的请求
		$("img").attr("src","code?date="+new Date());
		return false;
	})
})
</script>
……
<form action="" method="post">
	用户名:<input type="text" name="username"><br />
	密码:<input type="password" name="password"><br />
	验证码:<input type="text" size="1"><img src="code"/><a href="">看不清 </a><br />
	<input type="submit" value="登录"><input type="reset" value="重置">
</form>
……