1:明白前后端的信息交互原理,交互对象request response的使用
2:对servelt的理解运用,tomcat的理解
3:对配置文件的XML理解,网页/ 在tomcat的webapps下,xml中设置的url-pattern中/指的是项目的webRoot下
4:对 BufferedImage Graphics ImageIO的运用 Graphics2D AffineTransform的理解
实现步骤:
在servlet doGet/doPost方法中通过img的类创建画笔,
将内容画入buf缓存中,
通过imageIO将buf,以图片格式通过response的输入流写到网页中
代码:
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
int width=60;
int height=30;
//获得缓冲和画笔
BufferedImage bufImg=new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g=(Graphics2D)bufImg.getGraphics();
//画图
g.setColor(Color.white);
g.fillRect(0, 0, width, height);
Random r=new Random(new Date().getTime());
for(int i=0;i<2;i++){
String num=""+r.nextInt(10);
g.setColor(new Color(r.nextInt(255),r.nextInt(255),r.nextInt(255)));
AffineTransform atf=new AffineTransform();
//设置旋转
atf.rotate(Math.random(), i*20, 5 );
//设置放缩
atf.scale(0.6+Math.random(), 0.6+Math.random());
g.setTransform(atf);
g.drawString(num, 5+i*width/4, height/2);
}
for(int i=0;i<10;i++){
g.setColor(new Color(r.nextInt(255),r.nextInt(255),r.nextInt(255)));
g.drawLine(r.nextInt(width), r.nextInt(height), r.nextInt(width), r.nextInt(height));
}
g.dispose();//刷新,将内容刷入bufImg中
ImageIO.write(bufImg, "JPEG", response.getOutputStream());//写入界面
}
网页内容:
<body>
<!-- /WebStudy/Captcha 对servelt的请求,需要在web.xml配置servel的路径映射url-pattern -->
<img src="/WebStudy/Captcha"/><a href="javascript:imgUpdate()">看不清</a>
</body>
<script type="text/javascript">
function imgUpdate(){
var imgNode= document.getElementsByTagName("img").item(0);
//浏览器的缓存,对相同url的请求无效,改变参数来达到刷新
var t=new Date().getTime();
imgNode.src="/WebStudy/Captcha?"+t;
}
</script>
配置web.xml
<servlet>
<servlet-name>Captcha</servlet-name>
<display-name>This is the display name of my J2EE component</display-name>
<description>This is the description of my J2EE component</description>
<servlet-class>cn.hncu.captcha.Captcha</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Captcha</servlet-name>
<url-pattern>/Captcha</url-pattern>
</servlet-mapping>
显示网页效果图: