logo.html代码:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
function changeCode(){
//得到图片元素
var img = document.getElementsByTagName("img")[0];
img.src = "http://localhost:8080//Httpservletresponde/servletdemo4?time="+new Date().getTime();
}
</script>
</head>
<body>
<form action="#" method="post">
用户名:<input type="text" name="username"><br/>
密码:<input type="password" name="userpwd"><br/>
验证码:<input type="text" value=" " name="yzm">
<img src="http://localhost:8080//Httpservletresponde/servletdemo4" onclick="changeCode()"/><a href="javascript:changeCode()" >看不清换一张</a><br>
<br/>
<input type="submit" value="登录">
</form>
</body>
</html>
servletdemo4.java代码:
package com.haidi8.servlet;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class servletdemo4 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//在内存中创建图形对象
int height=25;
int width=110;
BufferedImage img=new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
//创建一个画笔
Graphics g=img.getGraphics();
//给图片添加背景颜色
g.setColor(Color.PINK);
g.fillRect(1, 1, width-2, height-2);
//给边框加颜色
g.setColor(Color.red);
g.drawRect(0, 0, width-1, height-1);
//设置文本样式
g.setColor(Color.BLUE);
g.setFont(new Font("黑体", Font.BOLD|Font.ITALIC, 15));
//给图片添加文本
Random rand=new Random();
int position=20;
for (int i = 0; i < 4; i++) {
g.drawString(rand.nextInt(10)+"", position, 20);
position+=20;
}
//添加干扰线
for (int i = 0; i < 9; i++) {
g.drawLine(rand.nextInt(width), rand.nextInt(height), rand.nextInt(width), rand.nextInt(height));
}
//将图像以流的形式输出到客户端
ImageIO.write(img, "jpg", response.getOutputStream());
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
}
web.xml代码:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<display-name></display-name>
<servlet>
<servlet-name>servletdemo4</servlet-name>
<servlet-class>com.haidi8.servlet.servletdemo4</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>servletdemo4</servlet-name>
<url-pattern>/servletdemo4</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
运行效果:
|