知识点jQuery ajax
$.ajax({
url:'url',//url为请求地址,服务器地址
type:'post/get',//请求方式一般为post或get
data:{ //传向服务器的参数,格式如下
name:$('[name=name]').val(),
pwd:$('[name=pwd]').val(),
},
dataType:'text',//服务器响应的数据类型
success:function (data) {//请求成功后要执行的方法,data为服务器响应的数据 }
});
效果展示
css代码jquery代码html代码写在js项目里面
servlet代码写在web的servlet里面
css代码
<style>
*{
text-align: center;
}
body{
background: url("images/b.png") no-repeat;
background-size: 100% auto;
}
.loginDiv{
margin: auto;
margin-top: 170px ;
width: 300px;
height: 350px;
background: #6FBD9F;
border-radius: 30px;
opacity: 0.6;
padding-top: 10px;
}
input{
width: 80%;
height: 30px;
margin: 10px;
background: none;
text-align: left;
padding-left: 10px;
color: white;
border-radius: 10px;
opacity: 0.6;
border:2px solid;
}
h1{
color: white;
}
.button{
width: 80%;
height: 30px;
border:none;
text-align: center;
font-size: 25px;
}
</style>
html代码
<body>
<div class="loginDiv">
<h1>UserLogin</h1>
<input type="text" value="用户名" name="name"><br>
<input type="text" value="密码" name="pwd"><br>
<input class="button" type="button" value="Login"><br>
<img src="images/xiahuangya.gif">
</div>
jquery代码
<script src = 'https://code.jquery.com/jquery-3.3.1.min.js'></script>
<script >
var flag=0;
$(function () {
$("[name=name]").blur(function () {
var zName = /^[A-Z]{1}\w{5,19}$/;//请输入以大写字母开头6-20位
if(zName.test($(this).val())){
$(this).css("border-color","green");
flag+=1;//如果通过正则表达式就加1
}else{
$(this).css("border-color","red");
}
});
$("[name=pwd]").blur(function () {
var zPwd = /^[A-Z]{1}.{7,14}$/;//请输入以大写开头 数字字母符号混合 8-15位
if(zPwd.test($(this).val())){
$(this).css("border-color","green");
flag+=1;//如果通过正则表达式就加1
}else{
$(this).css("border-color","red");
}
});
$('.button').on('click',function () {//判断账号密码是否正确
if (flag>=2){
$.ajax({
url:'http://localhost:8080/Demo/servlet/LoginServlet',
type:'post',
data:{
name:$('[name=name]').val(),
pwd:$('[name=pwd]').val(),
},
dataType:'text',
success:function (data) {
if (data=='true'){
window.location.href=('农场.html');
}else{
$('[name=pwd]').select();
}
}
});
}
});
});
servlet代码
public class LoginServlet 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.setHeader("Access-Control-Allow-Origin","*");
response.setContentType("text/html");
PrintWriter out = response.getWriter();
request.setCharacterEncoding("utf-8");
String name = request.getParameter("name");
String pwd = request.getParameter("pwd");
System.out.println(name+pwd);
String n = "M123456789";
String p = "M123456789";
if(n.equals(name)&&p.equals(pwd)){
out.print("true");
System.out.println("true");
}else{
out.print("false");
System.out.println("false");
}
out.flush();
out.close();
}
}