1、需求
在访问登录页面时,需要生产验证码。从而防止用户使用程序恶意登录。
2、代码实现
步骤1:修改登录页面,确定验证码图片显示的位置

步骤2:编写VerifyCodeServlet实现类
public class VerifyCodeServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
//生成图片
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//1、宽高
int width = 60;
int height = 30;
String data = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwtxyz";
Random random = new Random();
// 2、创建一个图片
BufferedImage bufferedImage = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
// 3、获得面板
Graphics graphics = bufferedImage.getGraphics();// 得到画图对象 --- 画笔
//4、填充一个矩形
// 绘制任何图形之前 都必须指定一个颜色
graphics.setColor(getRandColor(200, 250));
graphics.fillRect(0, 0, width, height);
// 绘制边框
graphics.setColor(Color.WHITE);
graphics.drawRect(0, 0, width - 1, height - 1);
// 设置输出字体
graphics.setFont(new Font("宋体", Font.BOLD, 18));
//5、 随机字
for (int i = 0; i < 4 ; i++) {
// 随机颜色
graphics.setColor(new Color(random.nextInt(225), random
.nextInt(225), random.nextInt(225)));
// 获得随机字
int index = random.nextInt(data.length());
String str = data.subString(index,index+1);
// 写入
graphics.drawString(str , width/6 * (i+1) , 20);
}
// 6、 绘制干扰线
for (int i = 0; i < 3; i++) {
// 随机颜色
graphics.setColor(new Color(random.nextInt(225), random
.nextInt(225), random.nextInt(225)));
//随机绘制线
graphics.drawOval(random.nextInt(width),random.nextInt(height), 2 , 2);
}
// 将上面图片输出到浏览器 ImageIO
ImageIO.write(bufferedImage, "jpg", response.getOutputStream());
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
步骤3:编写web.xml文件
<servlet>
<servlet-name>VerifyCodeServlet</servlet-name>
<servlet-class>com.klh.VerifyCodeServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>VerifyCodeServlet</servlet-name>
<url-pattern>/VerifyCodeServlet</url-pattern>
</servlet-mapping>
3、添加点击图片或文字,更换验证码
<img id="imgId" onclick="changImg()" style="cursor:pointer;" src="${pageContext.request.contextPath}/VerifyCodeServlet"/>
<a href="javascript:void(0)" onclick="changImg()">换一张</a>
<script type="text/javascript">
function changImg(){
$("imgId").attr("src","${pageContext.request.contextPath}/VerifyCodeServlet?t="+new Data());
}
</script>
还没有评论,来说两句吧...