【Servlet】实现简单的验证码生成与验证

简单的四位数字验证码生成,带看不清刷新验证密码的功能

登陆界面:

验证码<input type="text" name="loginCode" id="loginCode" />
           <img src="code.do" id="codeImage" style="width:80px;height:20px">
           <input type="button" id = "getCode" value="看不清" οnclick="button_onclick()" />
           <br/>

//设置了图片大小,添加了刷新图片的button

JavaScript:

<script type="text/javascript">
function button_onclick(){
var src = "code.do/" + Math.random();
document.getElementById("codeImage").src = src;
}
</script>

//实现图片刷新功能,通过添加随机数生成不同的请求

web.xml:servlet-mapping这样设置

<servlet-mapping>
    <servlet-name>code</servlet-name>
    <url-pattern>/code.do/*</url-pattern>
  </servlet-mapping>


生成验证码的Servlet:

public class Code extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}

public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("image/jpeg");
BufferedImage image = new BufferedImage(80, 20, BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
g.setColor(Color.BLACK);
int h = 20;
int w = 80;
g.fillRect(0, 0, w, h);
g.setColor(Color.BLUE);
g.drawRect(1, 1, 78, 18);
String code = "";
Random r = new Random();
for(int i = 0; i < 4; i++){
int a = r.nextInt(9);
code += a;
}
HttpSession hs = request.getSession();
hs.setAttribute("code", code);//将随机生成的4位验证码存入会话
g.setColor(RandomColor.randomColor());
g.drawString(code, 25, 15);
//随机十条线
for(int i = 0; i < 10; i++){
int x = r.nextInt(w);
int y = r.nextInt(h);
int x1 = r.nextInt(12);
int y1 = r.nextInt(12);
g.setColor(RandomColor.randomColor());
g.drawLine(x, y, x + x1, y + y1);
}
//设置网页立刻过期
response.setDateHeader( "expries" , -1 );
response.setHeader("cache-control" , "no-cache");
response.setHeader("Pragma" , "no-cache");
//将image写给浏览器
ImageIO.write( image , "jpg" , response.getOutputStream() );
}
}

生成随机颜色的辅助类:

public class RandomColor {
public static Color randomColor(){
int r = 0;
int b = 0;
int g = 0;
Random random = new Random();
r = random.nextInt(255);
g = random.nextInt(255);
b = random.nextInt(255);
Color c = new Color(r,g,b);
return c;
}
}

进行验证的Servlet:

String code = request.getParameter("loginCode");//取JSP中的 code

code.equals(request.getSession().getAttribute("code"))//与session中的code比较

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值