<记录>ajax异步刷新验证码及登录验证

<记录>ajax异步刷新验证码及登录验证

前端:使用thymeleaf、html、JavaScript

  <div class="form-group has-error">
                        <label class="control-label" for="inputError1" >
                         <!-- ${msg==null? '欢迎使用本系统!':msg}欢迎使用本系统-->
                            欢迎使用本系统
                        </label>

                      </div>
                    <input type="text" class="form-control uname"  id="uname" name="uname" placeholder="用户名" />
                     <div class="form-group has-error">
                        <label class="control-label" for="inputError1" id="u_inputErrorid" style="display: none;">用户名不能为空</label>
                     </div> 
                    <input type="password" class="form-control pword m-b" id="pwd"  name="pwd" width="50%" placeholder="密码" />
                    <div class="form-group has-error">
                       <label class="control-label" for="inputError1" id="p_inputErrorid" style="display: none;" >密码不能为空</label>
                    </div>
                    <input type="text" class="form-control  code  m-b" id="rand"  name="rand" placeholder="验证码" />
                    <div class="form-group has-error">
                       <label class="control-label" for="inputError1" id="r_inputErrorid" style="display: none;" >验证码不能为空</label>
                    </div>
                    <span>
<!--
                        <img alt="图片不存在"  id="code" height="30px"  th:src="@{/imgCode}">
-->
                        <img alt="图片不存在"  id="code" height="30px"  th:src="@{/imgCode}">
                    </span>
                    <a href="javascript:void(0)" id="imgCode">看不清?点击图片更换</a>
                    <input type="submit" id="login" class="btn btn-success btn-block" value="登录" >
                    <a href="#">忘记密码了?</a>
                </form>
            </div>
        </div>
        <div class="signup-footer">
            <div class="pull-left">
                &copy; 2016  
            </div>
        </div>
    </div>


js:

<script>
    function check_rand(){

        var rand = $("#rand").val().trim();

        $.ajax({
            type:"post",
            url:"/sysuser/login_rand",
            data:{"rand":rand},
            success:function (data){
                if (data.code==301){
                    check_login();

                }else {
                    $(".control-label").html(data.message)
                    $("#code").attr("src","imgCode?p=" + Math.random());
                }
            }
        })
    }
    function check_login(){
        var user = {};
        user.name = $("#uname").val();
        user.pwd = $("#pwd").val();
        //user.rand = $("#rand").val();
        $.ajax({
            type:"post",
            url:"/sysuser/login",
            data:JSON.stringify(user),
            contentType:"application/json;charset=utf-8",
            success:function (data){
                if (data.code==200){
                    $(".control-label").html(data.message)
                    window.location.href="/home.html";
                }else {
                    $(".control-label").html(data.message)
                    $("#code").attr("src","imgCode?p=" + Math.random());
                }
            }
        })
    }
    $("#login").click(function (){
        check_rand();
        return false;
    })
</script>

后端:Springboot、SpringMVC、mybatis

生成随机验证码


@Controller
public class RandomCode {
    private static final long seriaLVersionUID = 1L;
    private static int WIDTH =102;
    private static int HEIGHT = 50;
    @RequestMapping("/imgCode") //取得验证码的路径
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        response.setContentType("image/ipeg");
        ServletOutputStream sos=response.getOutputStream();
        response.setHeader("Pragma","No-cache");
        response.setHeader("Cache-Control","no-cache");
        response.setDateHeader("Expires",0);
        BufferedImage image=new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
        Graphics g = image.getGraphics();
        char[] rands=generateCheckCode();
        drawBackground(g);
        drawRands(g,rands);
        g.dispose();
        ByteArrayOutputStream bos=new ByteArrayOutputStream();
        ImageIO.write(image,"JPEG",bos);
        byte[] buf=bos.toByteArray();
        response.setContentLength(buf.length);
//将生成的验证码以流的形式发送到页而指定的元素中显示(以图片的形式显示)
        sos.write(buf);
        bos.close();
        sos.close();
        //将生成的验证码保存到session内置对象
        session.setAttribute("rand", new String(rands));
}
    private void drawBackground(Graphics g) {
        g.setColor(new Color(0xDCDCDC));
        g.fillRect(0, 0, WIDTH, HEIGHT);
        for (int i = 0; i < 120; i++) {
            int x = (int) (Math.random() * WIDTH);
            int y = (int) (Math.random() * HEIGHT);
            int red = (int) (Math.random() * 255);
            int green = (int) (Math.random() * 255);
            int blue = (int) (Math.random() * 255);
            g.setColor(new Color(red, green, blue));
            g.drawOval(x, y, 1, 0);
        }
    }

    private void drawRands(Graphics g,char[] rands){
        //g.setcolor(Color.BLUE);
        Random random=new Random();
        int red=random.nextInt(110);
        int green=random.nextInt(50);
        int blue=random.nextInt(50);
        g.setColor(new Color(red,green,blue));
        g.setFont(new Font(null,Font.ITALIC|Font.BOLD,30));
        g.drawString("" + rands[0],5,35);
        g.drawString("" + rands[1],25,34);
        g.drawString("" + rands[2],45,36);
        g.drawString("" + rands[3],65,33);
    }

    private char[] generateCheckCode() {
        String chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        char[] rands = new char[4];
        for (int i = 0; i < 4; i++) {
            int rand = (int) (Math.random() * 36);
            rands[i] = chars.charAt(rand);
        }
        return rands;
    }
        public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
        }
}

控制层代码


@Controller
@RequestMapping("/sysuser/*")
public class SysUserController {
    @Resource
    private SysUserService sysUserService;

    @RequestMapping("/login_rand")
    @ResponseBody
    public ResultData login_rand(HttpServletRequest request) throws Exception {
        String rand = request.getParameter("rand");
        System.out.println(rand);
        if (rand == null || "".equals(rand)) {
            System.out.println("到这了");
            return new ResultData(300, "验证码为空");
        }
        if (!rand.equalsIgnoreCase((String) request.getSession().getAttribute("rand"))) {
            return new ResultData(300, "您输入的验证码有误,请重试");

        }
        return new ResultData(301, "验证码正确");
    }
    @RequestMapping("/login")
    @ResponseBody
    public ResultData login(@RequestBody SysUser user,HttpServletRequest request) throws Exception {
        if (user.getName() == null||user.getPwd()==null||"".equals(user.getName())||"".equals(user.getPwd())) {
            ResultData resultData = new ResultData(100,"请输入用户名或密码");
            System.out.println(resultData);
            return resultData;
        }
        SysUser userData = sysUserService.findLogin(user.getName(), user.getPwd());
        if (userData != null) {
            request.getSession().setAttribute("user",user);
            ResultData resultData = new ResultData("登录成功");
            System.out.println(resultData);
            return  resultData;
        }else {
           // request.setAttribute("msg","用户名或密码不正确");
            ResultData resultData = new ResultData(100, "用户名或密码不正确");
            System.out.println(resultData);
            return resultData;
        }

    }

  • 这篇博客: 后端渲染之基于SpringBoot与Thymeleaf的JavaScript中的 1.4 Ajax 部分也许能够解决你的问题, 你可以仔细阅读以下内容或跳转源博客中阅读:
  • jquery提供了多个Ajax方法,我们可以直接请求服务获取数据,比较常用的是调用HTTP的GET与POST方法。

    1. Ajax调用GET方法
    	
    	$(document).ready(function(){
    			// 使用Thymeleaf内联语法,设置请求路径
    			var url = "[[@{/服务器映射地址}]]";
    			// 调用GET方法获取数据
    			$.get(url,function(datas,status){
    					//简单输出数据,可将数据写入table等列表中;
    				}
    			});
    		});
    
    2. Ajax调用POST方法
    	
    	向服务器端发送POST请求,可以使用$.ajax和$.post方法。
    	
    	a.使用$.ajax
    		function 方法名(){
                var url = "[[@{/服务器映射地址}]]";
                var data = {属性:"值"};
                $.ajax({
                    type:"POST",
                    dataType:"json",
                    contentType:"application/json;charset=utf-8",
                    url:url,
                    data:JSON.stringify(data),
                    success:function(data){
                        执行的行为;
                    }
                });
    		}
    
    	b.使用$.post,需要额外设置contentType,否则服务器将无法接收数据
    		$.ajaxSetup({
    			contentType:"application/json;charset=utf-8"
    		});
    
    		function send(){
    			var url = "[[@{/服务器映射地址}]]";
    			var data = {属性:"值"};
    			$.post(url,JSON.stringify(data),function(data){
    				执行的行为;
    			});
    		}
    	
    注 1. 服务器映射地址指@GetMapping或@PostMapping中的value值.
       2. 简单来说,有@ResponseBody标记表示该方法返回数据,没有则表示跳转页面.
       3. 调用GET方法在服务器方法上写@GetMapping和@ResponseBody,调用POST方法在服务器方法上写@PostMapping和@ResponseBody.