登录的页面布局以及js的验证,ajax的验证码验证

浏览: 183 发布日期: 2016-08-17 分类: tomcat

jsp页面:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>

<base href="<%=basePath%>">

<title>My JSP 'login.jsp' starting page</title>

<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">    
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">

 <style type="text/css">    
 body{    
  background-image:url(image/bg.jpg); 
  background-repeat: repeat-x;
    }  
    .top{
     height:250px;
     width:750px;
     margin-top:1px;
     margin-left:280px;
     background-image:url(image/logo.jpg);
    }  
 </style>

<script type="text/javascript" src="js/jquery-easyui-1.4.4/jquery.min.js"></script>
<script type="text/javascript" src="js/jquery-easyui-1.4.4/jquery.easyui.min.js"></script>
<link rel="stylesheet" href="js/jquery-easyui-1.4.4/themes/default/easyui.css" type="text/css"></link>
<link rel="stylesheet" href="js/jquery-easyui-1.4.4/themes/icon.css" type="text/css"></link>
<script type="text/javascript" src="js/jquery-easyui-1.4.4/locale/easyui-lang-zh_CN.js"></script>

<script type="text/javascript" src="myjs/login.js"></script></head>

<body>
<div class="mian">
<div class="top">
</div>
<div class="bottom">
<form action="<c:url value='/LoginStudentServlet'/>" method="post" id="formLogin">
<!-- 向Servlet传递一个method参数,其值表示servlet调用那个方法 -->
<input type="hidden" name="method" value="loginValidate"/>

<label class="errorClass" id="msg">${msg }</label>
用户名 <input class="inputClass" type="text" name="loginname" id="loginname" value="${student.loginname }"/> <label class="errorClass" id="loginnameError" >${errors.loginname }</label>
密码 <input class="inputClass" type="password" name="loginpass" id="loginpass" value="${student.loginpass }"/> <label class="errorClass" id="loginpassError">${errors.loginpass }</label>
验证码 <input class="inputClass" type="text" name="verifyCode" id="verifyCode" value="${student.verifyCode }"/> <label class="errorClass" id="verifyCodeError">${errors.verifyCode}</label>
<img id="imgVcode" src="/onlineexam/VerifyCodeServlet"/>换一张
<input type="button" value="登录" id="submit" onclick="javascript:login()"/>      <input type="reset" value="重置"/>

</form>
</div>
</div>
</body>
</html>

js代码:
$(function(){

  //得到所有的错误信息,循环遍历之。调用一个方法来确定是否显示错误信息!
    $(".errorClass").each(function() {
        showError($(this));//遍历每个元素,使用每个元素来调用showError方法
    });
     // 输入框得到焦点隐藏错误信息
     $(".inputClass").focus(function() {
         var labelId = $(this).attr("id") + "Error";//通过输入框找到对应的label的id
         $("#" + labelId).text("");//把label的内容清空!
         showError($("#" + labelId));//隐藏没有信息的label
     });
     //输入框失去焦点进行校验
     $(".inputClass").blur(function() {
         var id = $(this).attr("id");//获取当前输入框的id
         var funName = "validate" + id.substring(0,1).toUpperCase() + id.substring(1) + "()";//得到对应的校验函数名
         eval(funName);//执行函数调用,把字符串当成js代码执行
     });         
 });

function login(){

var bool = true;//表示校验通过
if(!validateLoginname()) {
    bool = false;
}
if(!validateLoginpass()) {
    bool = false;
}
if(!validateVerifyCode()){
    bool = false;
}
if(bool) {
    var loginname=$("#loginname").val();
    var loginpass=$("#loginpass").val();
    $.ajax({
        cache: false,
        async: false,
        type: "POST",
        dataType: "json",
        data: {method: "loginValidate", login: loginname,password:loginpass},
        url: "/onlineexam/LoginStudentServlet",
        success: function(data) {
              if(data.success){
                  if(data.successExam){
                      window.location.href="/onlineexam/demo.jsp";
                  }else{
                      window.location.href="/onlineexam/exam.jsp";
                  }
                  
              }else{
                  $.messager.alert('警告',data.msg);
              }
        }
    });    
}

}

// 校验登录名
function validateLoginname() {

var bool = true;
$("#loginnameError").css("display", "none");
var value = $("#loginname").val();
if(!value) {// 非空校验
    $("#loginnameError").css("display", "");
    $("#loginnameError").text("用户名不能为空!");
    bool = false;
} else if(value.length < 3 || value.length > 20) {//长度校验
    $("#loginnameError").css("display", "");
    $("#loginnameError").text("用户名长度必须在3 ~ 20之间!");
    bool = false;
}
return bool;

}
function validateLoginpass() {

var bool = true;
$("#loginpassError").css("display", "none");
var value = $("#loginpass").val();
if(!value) {// 非空校验
    $("#loginpassError").css("display", "");
    $("#loginpassError").text("密码不能为空!");
    bool = false;
} else if(value.length < 3 || value.length > 20) {//长度校验
    $("#loginpassError").css("display", "");
    $("#loginpassError").text("密码长度必须在3 ~ 20之间!");
    bool = false;
}
return bool;

}

// 校验验证码
function validateVerifyCode() {

var bool = true;
$("#verifyCodeError").css("display", "none");
var value = $("#verifyCode").val();
if(!value) {//非空校验
    $("#verifyCodeError").css("display", "");
    $("#verifyCodeError").text("验证码不能为空!");
    bool = false;
} else if(value.length != 4) {//长度不为4就是错误的
    $("#verifyCodeError").css("display", "");
    $("#verifyCodeError").text("错误的验证码!");
    bool = false;
} else {//验证码是否正确
    $.ajax({
        cache: false,
        async: false,
        type: "POST",
        dataType: "json",
        data: {method: "ajaxValidateVerifyCode", verifyCode: value},
        url: "/onlineexam/LoginStudentServlet",
        success: function(flag) {
            if(!flag) {
                $("#verifyCodeError").css("display", "");
                $("#verifyCodeError").text("错误的验证码!");
                bool = false;                    
            }
        }
    });
}
return bool;

}

// 判断当前元素是否存在内容,如果存在显示,不存在不显示!
function showError(ele) {

var text = ele.text();//获取元素的内容
if(!text) {//如果没有内容
    ele.css("display", "none");//隐藏元素
} else {//如果有内容
    ele.css("display", "");//显示元素
}

}
// 换一张验证码
function _hyz(){
var img=document.getElementById("imgVcode");
//需要给出一个参数,这个参数每次都不同,这样才不会因为浏览器的缓存,使得不能进行换一张
img.src="/onlineexam/VerifyCodeServlet?a="+new Date().getTime();

  } 

后台web.servlet层:
service层dao层就不一一写出了。

public class LoginStudentServlet extends BaseServlet {

StudentService studentService = new StudentService();
ExamService examService=new ExamService();
public String ajaxValidateLoginname(HttpServletRequest req,
        HttpServletResponse resp) throws ServletException, IOException {
    // 1. 获取用户名
    String loginname = req.getParameter("loginname");
    //2. 通过service得到校验结果
    boolean b = studentService.ajaxValidateLoginname(loginname);
    resp.getWriter().print(b);
    return null;
}

public String ajaxValidateVerifyCode(HttpServletRequest req,
        HttpServletResponse resp) throws ServletException, IOException {
    //1. 获取输入框中的验证码
    String verifyCode = req.getParameter("verifyCode");
    // 2. 获取图片上真实的校验码
    String vcode = (String) req.getSession().getAttribute("vCode");
    boolean b = verifyCode.equalsIgnoreCase(vcode);
    resp.getWriter().print(b);
    return null;
}

// 登录功能

public void loginValidate(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException, SQLException {
    String name = req.getParameter("login");
    String password = req.getParameter("password");
    Student student = studentService.login(name, password);
    Score score=examService.findStudent(name);
    Json json = new Json();
    if (student == null) {
        json.setSuccess(false);
        json.setMsg("用户名或密码错误");
        resp.getWriter().print(json.toString());
        resp.getWriter().close();
        //return "r:/loginStudent.jsp";
    } else {
        if(score!=null){
            json.setSuccessExam(true);
        }
        HttpSession session = req.getSession();
        session.setAttribute("sessionStudent",student);
        session.setAttribute("sessionScore",score);
        //String string=(String) session.getAttribute("sessionName");
        //System.out.println(string);
        json.setSuccess(true);
        json.setMsg("登录成功");
        json.setStudent(student);        
        resp.getWriter().print(json);
        resp.getWriter().close();
        //return "r:/exam.jsp";//重定向到主页
    }
}

}
注意:这里我自己编写了一个BaseServlet继承了HttpServlet然后通过获得method参数,然后通过反射调用对应的方法。

返回顶部