这篇文章主要介绍了使用AJAX(包含正则表达式)验证用户登录的步骤,本文给大家介绍的非常详细,具有一定的参考借鉴价值,需要的朋友可以参考下
我们来分一下步骤吧:
1.HTML代码,采集软件,页面先写出来;
2.正则表达式验证输入的用户名密码是否正确,失去焦点验证
3.Ajax异步提交
4.servlet这是后台处理代码获取数据并对比响应,站群系统,然后跳转成功页面
效果图:
结构:
代码如下:
table {
width: 360px;
height: 45px:
text-align: center;
margin-top: 120px;
border-collapse: collapse;
}
input {
width: 280px;
height: 30px;
}
用户名: | οnblur="verifyName()" /> | |
密码: | οnblur="verifyPwd()" /> | |
type="button" value="提交登录验证" /> |
function verifyName() {
//用户名校验
var verifyName = document.getElementById("username").value;
var name = /^[A-Z][0-9A-Za-z_][a-zA-Z0-9_]{5,19}$/; // 大写字母开头 6-20位字符(不允许有符号但是允许有_)
if (!name.test(verifyName)) {
//$("#username").after("大写字母开头6-20位字符(不允许有符号但是允许有_)");
$("#username").css("border-color", "red");
return false;
} else {
return true;
}
}
function verifyPwd() {
//密码
var verifyPwd = document.getElementById("mypwd").value;
var pwd = /^[A-Z][A-Za-z0-9]\w{7,14}.{1,20}$/; //大写开头 数字字母符号混合 8-15位
if (!pwd.test(verifyPwd)) {
$("#username").css("border-color", "red");
return false;
} else {
return true;
}
}
$(function() {
$(":button").on("click", function() {
$.ajax({
type : "post",
url : "AJAXServlet",
data : {
name : $("#username").val(),
pwd : $("#mypwd").val()
},
dataType : "text",
success : function(data) {
if (data == "ok") {
window.location.href = "show.jsp";
} else {
alert("登录失败!");
$("#mypwd").val("");
$("#username").focus().select();
}
}
});
});
});
servlet代码:
package com.chaz.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class AJAXServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
request.setCharacterEncoding("utf-8");
PrintWriter out = response.getWriter();
String name = "ZhangSan";
String pwd = "Zhang123456";
String ajaxName = request.getParameter("name");
String ajaxPwd = request.getParameter("pwd");
System.out.println(ajaxName+":"+ajaxPwd);
if(name.equals(ajaxName)&&pwd.equals(ajaxPwd)){
out.print("ok");
}else{
out.print("Error");
}
out.flush();
out.close();
}
}
web.xml:
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee ">
This is the description of my J2EE component
This is the display name of my J2EE component
AJAXServlet
com.chaz.servlet.AJAXServlet
AJAXServlet
/AJAXServlet
跳转成功页面就这个:
总结
相关报道:
近日,在某酒吧节目上,一位名为“林侧”的女子邀请现场观众上台摸她的胸,活动持续了30分钟。该女子称“观众很 更多
GoodSmile推出了古惑狼的粘土人,售价7273日元(不含税,约467元),预计明年6月发售。此次的商品是以《古惑狼4:时 更多