----1,引入servlet的jar包,搭建好开发环境(eclipse+JDK等)
----2,编写主页面(输入用户、密码、验证码的页面index_demo_10.jsp)
<%@page import="com.util.JSPUtils"%>
<%@page import="java.util.ArrayList"%>
<%@page import="java.util.List"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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>在提交表单时加入验证码</title>
<%
Integer count =0;
Integer app_count =(Integer)application.getAttribute("app_count");//获取application中保存的记录数
if(app_count==null || app_count<=0){
++count;
}else{
count=app_count+1;
}
application.setAttribute("app_count", count);
%>
<script type="text/javascript">
function reloadCode(){
var time=new Date();
//这里定义时间参数是为了让浏览器认为这是一个新的请求,清空之前的缓存信息
document.getElementById("safecode").src="<%=request.getContextPath()%>/servlet/ImageServlet?d="+time;
}
function validate(obj){
var username=document.getElementById("username").value;
var password=document.getElementById("password").value;
if(username=='zhihao' && password=='123456'){
document.form1.submit();
}else{
alert("您输入的账号或密码不对!");
return;
}
}
</script>
</head>
<body>
<form name="form1" action="index_demo_11.jsp">
<!-- 注:onMouseOver与onMouseOut这里不能写在js中,否则显示不出效果,另外大小写也要注意 -->
<table>
<tr>
<td>用 户 名 :</td>
<td><div id="onMouse"><input type="text" name="username" id="username" value="" onMouseOver="this.style.background='red';" onMouseOut="this.style.background='';"></div></td>
</tr>
<tr>
<td>密 码 :</td>
<td><input type="password" name="password" value="" id="password" onMouseOver="this.style.background='blue';" onMouseOut="this.style.background='';"></td>
</tr>
<tr>
<td valign="bottom">验 证 码 :</td>
<td>
<input type="text" name="yanzhengma" value="" onMouseOver="this.style.background='green';" onMouseOut="this.style.background='';" size="6" οnblur="checkValidate();">
<img alt="验证码" src="<%=request.getContextPath()%>/servlet/ImageServlet" id="safecode" width="100" height="30" οnclick="reloadCode()">
<a href="javascript:reloadCode()">看不清楚</a>
<span id="result"></span>
</td>
</tr>
<tr>
<td colspan="2"><input type="button" name="button" value="登录" οnclick="validate(this);"></td>
</tr>
</table>
</form>
</body>
</html>
--------3,配置web.xml,将对应的servlet配置进去
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>JSP_demo2</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<!-- 在web.xml中配置全局初始化参数值,这里配置数据库连接的相关参数 -->
<context-param>
<param-name>driver</param-name>
<param-value>com.mysql.jdbc.Driver</param-value>
</context-param>
<context-param>
<param-name>url</param-name>
<param-value>jdbc:mysql://localhost:3306/proposal_info</param-value>
</context-param>
<context-param>
<param-name>username</param-name>
<param-value>root</param-value>
</context-param>
<context-param>
<param-name>password</param-name>
<param-value>b812w925</param-value>
</context-param>
<!-- 配置servlet -->
<servlet>
<servlet-name>imageServlet</servlet-name>
<servlet-class>com.servlet.ImageServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>imageServlet</servlet-name>
<url-pattern>/servlet/ImageServlet</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>ValidateServlet</servlet-name>
<servlet-class>com.servlet.ValidateServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ValidateServlet</servlet-name>
<url-pattern>/servlet/ValidateServlet</url-pattern>
</servlet-mapping>
</web-app>
----------4,编写后台ImageServlet,用来生成验证码图片并将该图片传到前端指定位置
package com.servlet;
import java.awt.image.RenderedImage;
import java.io.IOException;
import java.util.List;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.util.JSPUtils;
public class ImageServlet extends HttpServlet{
@Override
protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
//获取验证码
List<Object> list=JSPUtils.getYanZhengMa();
req.getSession().setAttribute("piccode", list.get(0));
ImageIO.write((RenderedImage)list.get(1),"jpg",res.getOutputStream());//用ImageIO将图片输出到页面
}
}
---------5,编写具体实现绘制验证码图片JSPUtils
package com.util;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class JSPUtils {
public static final String[] DATAS=new String[]{"0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"};
public static final int SIX=4;
public static final int WIDTH=65;//验证码图片的宽
public static final int HEIGHT=25;//验证码图片的高
//定义验证码的背景颜色
public static final int BK_COLOR1=200;
public static final int BK_COLOR2=200;
public static final int BK_COLOR3=255;
//创建一个方法用来生成随机验证码,6位数字与字母混合体(0-9+a-z)
public static List<Object> getYanZhengMa(){
List<Object> list=new ArrayList<Object>();
/**
* 1,使用BufferedImage对象对指定图片进行宽高透明度等设置
* 2,获得Graphics对象
* 3,使用Random获得随机数
* 4,使用Graphics绘制图像
* 5,记录验证码信息到session中
* 6,使用ImageIO输出图片
*/
BufferedImage buImage=new BufferedImage(WIDTH, HEIGHT,BufferedImage.TYPE_INT_BGR);//Type_int_Rgb表示一个图像具有合成整数像素的8位RGB颜色分量
Graphics graphics=buImage.getGraphics();
Color co=new Color(BK_COLOR1,BK_COLOR2,BK_COLOR3);//验证码的背景图片
graphics.setColor(co);
graphics.fillRect(0,0,WIDTH,HEIGHT);//绘制图片的边框
StringBuffer sb=new StringBuffer();//定义保存验证码字符串
//创建一个1-35数字的随机数数组,然后从中进行随机取数
String result="";
Random random=new Random();
for(int i=0;i<SIX;i++){
int count=random.nextInt(DATAS.length);
graphics.setColor(new Color(random.nextInt(250),random.nextInt(250),random.nextInt(250)));//为验证码字符串定义字体颜色
graphics.setFont(new Font("宋体", Font.PLAIN, 24));//设置字体样式及大小
graphics.drawString(DATAS[count],15*i+3,18);//画出字符
sb.append(DATAS[count]);
}
//将得到的字符串及图片放入list中返回
list.add(sb);
list.add(buImage);
return list;
}
public static void main(String[] args) {
System.out.println("结果为:"+getYanZhengMa());
}
}
-----------------6,编写跳转页面index_demo_11.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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>登陆成功页面</title>
</head>
<body>
欢迎<%=request.getParameter("username") %>来到此界面,您是第<%=application.getAttribute("app_count") %>用户<br>
客户信息:<br>
用户名:<%=request.getParameter("username")%>,密码:<%=request.getParameter("password") %>
</body>
</html>