Servlet的验证码功能

1.导入ValidateCode 依赖包 (下载)

后端代码: 

package com.utils;

import cn.dsna.util.images.ValidateCode;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;


//验证码的功能(导入ValidateCode.jar 包)
@WebServlet("/validate")
public class Validate extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        ValidateCode vc = new ValidateCode(100,30,4,10); //宽,高,验证码个数,行数的个数
        String code = vc.getCode(); //拿到验证码

        //把验证码放到session 里面去(Session与Cookie的区别在于Session是记录在服务端的,而Cookie是记录在客户端的。)
        HttpSession session = request.getSession(); //如果有session 就不出创建,没有就创建
        session.setAttribute("code",code);
        //响应给客服端
        vc.write(response.getOutputStream());

    }

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

前端代码

     <input type="text" name="inputVcode" >
     <img src="/src/validate" alt="验证码" />&nbsp; <br><br>
     <a href=" http://localhost:8080/src/addtion.html"/>注册

 

   String inputVcode =request.getParameter("inputVcode");
        String codes = (String)request.getSession().getAttribute("code");


          //不判断字母大小写  equalsIgnoreCase
            if( !inputVcode.isEmpty() & inputVcode.equalsIgnoreCase(codes)){
                 System.out.println("验证码成功");
            }else{
               System.out.println("验证码失败");
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值