前端数字验证码与登陆后台代码

验证码生成工具类

看代码:

package com.doing.utils;

import org.apache.commons.codec.binary.Base64;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Random;

/**
 * 生成验证码
 */
public class CheckCode {

    //验证码图片大小
    private int width = 50;
    private int height = 20;
    //验证码个数
    private int length = 4;
    //随机验证码集合
//    private String checkCode = "QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm1234567890";
    private String checkCode = "0123456789";
    private String result = "";

    public void setCheckCode(String checkCode) {
        this.checkCode = checkCode;
    }

    public void setLength(int length) {
        this.length = length;
    }

    public String getResult() {
        return result;
    }

    public CheckCode() {
        result = generateCode();
    }

    public CheckCode(String checkCode) {
        this.checkCode = checkCode;
        result = generateCode();
    }

    public CheckCode(int width, int height) {
        this();
        this.width = width;
        this.height = height;
    }

    public CheckCode(int width, int height, int length) {
        this(width,height);
        this.length = length;
    }

    private String generateCode(){
        StringBuilder sb = new StringBuilder("");
        for (int i = 0; i < length; i++) {
            int randomNum = new Random().nextInt(checkCode.length());
            //根据随机数将字母强制转换为字符串
            String randomChar = String.valueOf(checkCode.charAt(randomNum));
            sb.append(randomChar);
        }
        return sb.toString();

    }

    public void toOutputStream(OutputStream os) throws IOException {
        //创建一个图片缓冲,图片类型为RGB
        BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        //拿到图片的画笔
        Graphics2D g2d = (Graphics2D) img.getGraphics();
        //将缓冲图片默认的黑色改为白色
        g2d.fillRect(0, 0, width, height);
        //画出验证码
        for (int i = 0; i < length; i++) {
            //字体颜色
            g2d.setColor(Color.BLACK);
            //设置字体大小
            Font font = new Font("Arial", Font.PLAIN,(int)(height*0.8));
            g2d.setFont(font);
            //画出一个验证码
            g2d.drawString(String.valueOf(result.charAt(i)), 5 + (((width-5)/length) * i), (int)(height*0.8));
        }

        /**
         * 对验证码增加干扰,可以是点也可以是线等
         */
        for (int i = 0; i < 3; i++) {
            //随机产生划线坐标
            int x1 = new Random().nextInt(width);
            int y1 = new Random().nextInt(height);
            int x2 = new Random().nextInt(width);
            int y2 = new Random().nextInt(width);
            RandomColor(g2d);
            g2d.drawLine(x1, y1, x2, y2);
        }
        //向客户端发送jpg图片
        ImageIO.write(img, "jpg", os);
    }

    /**
     * 设置画笔颜色为随机颜色
     *
     * @param g2d
     */
    public void RandomColor(Graphics2D g2d) {
        //RGB三色参数
        int r = new Random().nextInt(255);
        int g = new Random().nextInt(255);
        int b = new Random().nextInt(255);
        //设置颜色
        g2d.setColor(new Color(r, g, b));
    }

    public String toBase64() {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        String result = "";
        try {
            toOutputStream(os);
            result = Base64.encodeBase64String(os.toByteArray());
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    public static void main(String[] args) throws IOException {
        int width = 100;
        int height = 30;
        String name = "";
        for (int i = 1; i <= 10; i++) {
            name = "code"+i;
            outputCode(width, height, name);
        }
    }

    public static void outputCode(int width, int height, String name) throws IOException {
        CheckCode checkCode = new CheckCode(width,height);
        String userDir = System.getProperty("user.dir");
        String resourcePath = "\\src\\main\\resources";
        System.out.println(userDir.concat(resourcePath).concat("\\"+name+".jpg"));
        checkCode.toOutputStream(new FileOutputStream(userDir.concat(resourcePath).concat("\\"+name+".jpg")));
        System.out.println(checkCode.getResult());
    }
}

调用

      CheckCode checkCode = new CheckCode(100, 30);
        String code = checkCode.getResult();
        String base64 = checkCode.toBase64();
        model.addAttribute("checkCode",base64);
        request.getSession().setAttribute("code",code);

html

    
"yonghu" style=""> 用户名
"username" type="text" name="" placeholder="用户名"/>
"yonghu">密码
"pwd" type="password" name="密码" placeholder="密码" />
"">
"yonghu"> "check_img" style="width: 100px;height: 30px" src="" alt="加载中..."/>
"check_code" type="text" placeholder="输入验证码"/>

js


<script>
    var  ctx = [[@{/}]];
</script>
    <script>

        $(function () {
            $('#check_img').attr("src", "data:image/png;base64,[[${checkCode}]]");
            $('#check_img').click(function () {
                getChick();
            });
            $('#subm').click(function () {
               var name=$.trim($('#username').val());
                var pwd=$.trim($('#pwd').val());
                var check=$.trim($('#check_code').val());
                if(name=="" || pwd==""|| check==""){
                    alert("输入信息不能为空!");
                    return;
                }
                if(name==null || pwd==null|| check==null){
                    alert("输入信息不能为空!");
                    return;
                }
                $.ajax({
                    url :ctx+"checkindex",
                    type :"post",
                    dataType :"json",
                    data :{username:name,pwd:pwd,check:check},
                    success : function(data){
                    debugger
                        if(data.state=="ok"){
                            location.href = ctx + 'index';
                        }else{
                            getChick();
                            alert(data.msg);
                        }
                    }
                })
            });
        })
function getChick() {
    $.ajax({
        url :ctx+"checkCode",
        type :"post",
        dataType :"json",
        success : function(data){
        debugger
            if(data.state=="ok"){
                $('#check_code').val("");
                $('#check_img').attr("src", "data:image/png;base64,"+data.msg);
            }else{
                alert(data.msg);
            }
        }
    })
}

    </script>

后台代码


    @Autowired
    private UserMapper mapper;
    @Autowired
    private HttpSession session;


 public Boolean loginUser(String name,String password) {
        Example example=new Example(AppUser.class);
        Example.Criteria criteria= example.createCriteria();
        criteria.andEqualTo("userid",name);
        AppUser user= mapper.selectOneByExample(example);
        if(user==null){
            throw new DoingNullException("用户不存在");
        }
        if(user.getStatus().equals(0)){
            throw new DoingNullException("账号无效,请管理员");
        }
        if(user.getStatus().equals(2)){
            throw new DoingNullException("账号已被锁定,请第二日登陆");
        }
        if(!PasswordUtils.toHash(user.getId(),password).equals(user.getPassword())){
           Integer num=user.getLock5();
           num++;
           log.error("密码错误,用户:"+user.getUserid()+"第"+num+"此登陆");
           if(num.equals(5)){
            mapper.byLogin(user.getId(),num,Short.parseShort("2"));
           }else {
               mapper.byLogin(user.getId(),num,Short.parseShort("1"));
           }
            int a=5-num;
            throw new DoingNullException(String.format("密码错误再错误输入:%s 次,此账号将被锁定", a));
        }
        if(session==null){
            throw new DoingNullException("未获取到session请联系系统管理员");
        }
        mapper.byLogin(user.getId(),0,Short.parseShort("1"));
        session.setAttribute("user_id",user.getId());

        return true;
    }

控制器

    @ResponseBody
    public RequseBo checkCode(HttpServletRequest req){
        CheckCode checkCode = new CheckCode(100, 30);
        String code = checkCode.getResult();
        String base64 = checkCode.toBase64();
        req.getSession().setAttribute("code",code);
        return RequseBo.ok("msg",base64);
    }

 public RequseBo showIndex(HttpServletRequest req, String username, String pwd, String check){
    
        String code= req.getSession().getAttribute("code").toString().toLowerCase();
        req.getSession().removeAttribute("code");
        if(!code.equals(check.toLowerCase())){
            return RequseBo.fail("msg","验证码错误");
        }
        try{
        userService.loginUser(username,pwd);
            return RequseBo.ok();
        }catch (Exception e){
            if(e instanceof DoingNullException){
                log.error("登陆异常"+e.getMessage());
                return RequseBo .fail("msg",e.getMessage());
            }else {
                log.error("登陆异常,未知错误"+e.getMessage());
                return RequseBo.fail("msg","未知错误");
            }

        }


XML

  
    update USER set status=#{status},LOCK5=#{num} where id=#{uid}

  

SQL定时器,每天凌晨执行

create or replace procedure user_status as
begin
    update user set status=1 where status=2;
end;



declare
  i Integer;
  begin 
    dbms_job.submit(i,'user_status;',sysdate,'trunc(sysdate+1)+1/(24*60)'); 
    end;	 
	 

你可能感兴趣的:(验证码,jAVA工具,java,html)