博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
JavaEE----登陆界面验证码实现
阅读量:7123 次
发布时间:2019-06-28

本文共 8012 字,大约阅读时间需要 26 分钟。

主要使用后端验证,调用awt API ,会简单调用即可,绘图代码已封装到LoginVerifyUtils中。


界面展示:

 

 

LoginVerifyUtils全部代码

1 import java.awt.Color; 2 import java.awt.Font; 3 import java.awt.Graphics2D; 4 import java.awt.font.FontRenderContext; 5 import java.awt.geom.Rectangle2D; 6 import java.awt.image.BufferedImage; 7 import java.io.ByteArrayOutputStream; 8 import java.io.IOException; 9 import java.util.Random;10 11 import javax.imageio.ImageIO;12 13 public class LoginVerifyUtils {14 15     private static LoginVerifyUtils loginVerifyUtils = new LoginVerifyUtils(); 16 17     private LoginVerifyUtils() {18     }19     20     public static LoginVerifyUtils getInstance() {21         return loginVerifyUtils;22     }23     24     /**25      * 绘画验证码26      * @param output27      * @return28      */29     public String drawImg(ByteArrayOutputStream output) {30         String code = "";31         // 随机产生4个字符32         for (int i = 0; i < 4; i++) {33             code += randomChar();34         }35         int width = 70;36         int height = 25;37         BufferedImage bi = new BufferedImage(width, height,38                 BufferedImage.TYPE_3BYTE_BGR);39         Font font = new Font("Times New Roman", Font.PLAIN, 20);40         // 调用Graphics2D绘画验证码41         Graphics2D g = bi.createGraphics();42         g.setFont(font);43         Color color = new Color(66, 2, 82);44         g.setColor(color);45         g.setBackground(new Color(226, 226, 240));46         g.clearRect(0, 0, width, height);47         FontRenderContext context = g.getFontRenderContext();48         Rectangle2D bounds = font.getStringBounds(code, context);49         double x = (width - bounds.getWidth()) / 2;50         double y = (height - bounds.getHeight()) / 2;51         double ascent = bounds.getY();52         double baseY = y - ascent;53         g.drawString(code, (int) x, (int) baseY);54         g.dispose();55         try {56             ImageIO.write(bi, "jpg", output);57         } catch (IOException e) {58             e.printStackTrace();59         }60         return code;61     }62     63     /**64      * 随机获取一个字符65      * @return66      */67     public char randomChar() {68         Random r = new Random();69         String s = "ABCDEFGHJKLMNPRSTUVWXYZ0123456789";70         return s.charAt(r.nextInt(s.length()));71     }72 }
View Code

 

login.jsp

账号
密码
验证码

View Code

 

依赖ui库

 

javascript

$("#loginButton").click(function () {            if($("#adminId").val()==''&&$("#passwd").val()==''){                $("#info").text("提示:账号和密码不能为空");            }            else if ($("#adminId").val()==''){                $("#info").text("提示:账号不能为空");            }            else if($("#passwd").val()==''){                $("#info").text("提示:密码不能为空");            }else if($("#verifyCode").val()==''){                $("#info").text("提示:请输入验证码");            }            else {                //验证码                $.ajax({                    type: "GET",                    url: "${APP_PATH}/admin/verifyCode",                    data: {                        verifyCode:$("#verifyCode").val() ,                    },                    dataType: "json",                    success: function(data) {                        if(data.stateCode.trim() == "1003") {                            $("#info").text("提示:服务器异常");                            flag = false;                        } else if(data.stateCode.trim() == "1002") {                            $("#info").text("提示:验证码错误");                        } else{                            userLogin()                        }                    }                 });                            }        })        function userLogin(){            $.ajax({                type: "POST",                url: "${APP_PATH}/admin/login",                data: {                    username:$("#adminId").val() ,                    password: $("#passwd").val()                },                dataType: "json",                success: function(data) {                    if(data.stateCode.trim() == "1003") {                        $("#info").text("提示:该用户不存在");                    } else if(data.stateCode.trim() == "1002") {                        $("#info").text("提示:密码错误");                    } else if(data.stateCode.trim() == "1001"){                        $("#info").text("提示:登陆成功,跳转中...");                        window.location.href="${APP_PATH}/main";                    }else{                        $("#info").text("提示:服务器出错");                    }                }            });        }
View Code

 

loginController参考

 

/**     * 获取验证码     * @param response     * @param session     */    @GetMapping("/getVerifyCode")    public void generate(HttpServletResponse response, HttpSession session) {                ByteArrayOutputStream output = new ByteArrayOutputStream();                LoginVerifyUtils loginVerifyUtils = LoginVerifyUtils.getInstance();        String verifyCodeValue =loginVerifyUtils.drawImg(output);                session.setAttribute("verifyCodeValue", verifyCodeValue);                try {            ServletOutputStream out = response.getOutputStream();            output.writeTo(out);        } catch (IOException e) {            e.printStackTrace();        }    }        //验证    @GetMapping("/verifyCode")    public @ResponseBody AJAXResult verifyCode(@RequestParam("verifyCode") String verifyCode ,HttpSession session) {        AJAXResult result = new AJAXResult();        try {            String verifyCodeValue = (String) session.getAttribute("verifyCodeValue");            if(verifyCode.trim().toUpperCase().equals(verifyCodeValue)) {                result.setStateCode("1001");            }        } catch (Exception e) {            e.printStackTrace();            result.setStateCode("1003");        }        return result;    }   @ResponseBody    @PostMapping("/login")    public Object login(Admin admin ,HttpServletRequest request) {        AJAXResult result = new AJAXResult();        try {            Wrapper
wrapper = new EntityWrapper
(); wrapper.eq("username", admin.getUsername()); boolean isName = adminService.selectOne(wrapper) == null ? true: false; if(isName) { result.setStateCode("1003");//用户名不存在 }else { Wrapper
wrapper2 = new EntityWrapper
(); wrapper2.eq("username", admin.getUsername()); wrapper2.eq("password", admin.getPassword()); Admin loginAdmin = adminService.selectOne(wrapper2); if(loginAdmin != null ) { request.getSession().setAttribute("loginAdmin", loginAdmin); LoginLog loginLog = new LoginLog(); loginLog.setAdminId(loginAdmin.getId()); loginLog.setLoginDate(new Date() ); loginLog.setLoginIp(request.getRemoteAddr()); loginLogService.insert(loginLog ); result.setStateCode( "1001");//登陆成功 }else { result.setStateCode( "1002");//用户名或密码错误 } } } catch (Exception e) { e.printStackTrace(); result.setStateCode( "1004");//服务器出错 } return result ; }
View Code

 

 ps:主要逻辑就是把随机生成的验证码放到session域,当用户提交请求时,获取表单数据然后进行比对<(^-^)>

效果图

 

 提供的代码尽量以参考为主,如有疑问,欢迎提出

 

转载于:https://www.cnblogs.com/tmlh/p/9311150.html

你可能感兴趣的文章
Memcache 查看列出所有key的方法
查看>>
DataBinding初识
查看>>
CentOS Docker 安装
查看>>
python set(集合)
查看>>
(C#)把磁盘目录树加载在窗体菜单中
查看>>
centos6中三台物理机配置nginx+keepalived+lvs
查看>>
apache
查看>>
file_get_contents()采集不到原因
查看>>
FFmpeg常用基本命令
查看>>
Linux vmstat命令实战详解
查看>>
zip压缩工具、tar打包、打包并压缩
查看>>
PHP日期转星期(英文/数字)
查看>>
python 逻辑运算符
查看>>
Hibernate技术
查看>>
js实现限制输入框只能输入数字
查看>>
CentOS下杀毒工具ClamAV安装
查看>>
编译参数查看
查看>>
httpd学习:http基础
查看>>
硬盘结构与工作原理
查看>>
改动过.gitignore文件之后设置生效
查看>>