利用ajax和jquery验证登录验证

本次书写的是用Ajax和jQuery来写一个用于用户登录验证用户名和密码是否一致,是否符合给定的正则表达式并且连接数据库,目前只具有登录验证功能,后续功能尽情期待。
用的是mvc结构,所用的包有bean,service,serviceImpl,servlet
1.User.java

package cn.hnpi.bear;

public class User {
	private Integer id;
	private String name;
	private String pwd;
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getPwd() {
		return pwd;
	}
	public void setPwd(String pwd) {
		this.pwd = pwd;
	}
	public User() {
		super();
		// TODO Auto-generated constructor stub
	}
	public User(Integer id, String name, String pwd) {
		super();
		this.id = id;
		this.name = name;
		this.pwd = pwd;
	}
	
}

2.UserService

package cn.hnpi.service;

import java.util.List;

import cn.hnpi.bear.User;

public interface UserService {

	/**
	 * 查询所有的用户
	 * @return
	 */
	public List<User> serlectUserAll();
}

3.UserServiceImpl

package cn.hnpi.service.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import cn.hnpi.bear.User;
import cn.hnpi.service.UserService;
import cn.hnpi.util.DBUtil;

public class UserServiceImpl implements UserService {

	public List<User> serlectUserAll() {
		Connection conn = DBUtil.getConn();
		PreparedStatement ps = null;
		ResultSet rs = null;
		List<User> users = new ArrayList<User>();
		String sql = "select * from user";
		try {
			ps = conn.prepareStatement(sql);
			rs = ps.executeQuery();
			if (rs.next()) {
				User user = new User();
				user.setId(rs.getInt(1));
				user.setName(rs.getString(2));
				user.setPwd(rs.getString(3));
				users.add(user);
			}
		} catch (SQLException e) {
			// TODO: handle exception
			e.printStackTrace();
		}finally{
			DBUtil.closeConn(conn, ps, rs);
		}
		return users;
	}
}

4.AjaxServlet

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hnpi.bear.User;
import cn.hnpi.service.UserService;
import cn.hnpi.service.impl.UserServiceImpl;


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 {

		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		//自定义用户名和密码可更改
		UserService userService = new UserServiceImpl();
		User user = new User();
		String nameAjax = request.getParameter("name");
		String pwdAjax = request.getParameter("pwd");
		String name = user.getName();
		String pwd = user.getPwd();
		if (name.equals(nameAjax) && pwd.equals(pwdAjax)) {
			out.print("ok");
		}else{
			out.print("error");
		}
		
		out.flush();
		out.close();
	}

}

jsp:index.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
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>登录页面</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">
	<script type="text/javascript" src="js/jquery.js"></script>
	<style>
		html{   
		    width: 100%;   
		    height: 100%;   
		    overflow: hidden;   
		    font-style: sans-serif;   
		}   
		body{   
		    width: 100%;   
		    height: 100%;   
		    font-family: 'Open Sans',sans-serif;   
		    margin: 0;   
		    background-color: #4A374A;   
		}   
		#login{   
		    position: absolute;   
		    top: 50%;   
		    left:50%;   
		    margin: -150px 0 0 -150px;   
		    width: 300px;   
		    height: 300px;   
		}   
		#login h1{   
		    color: #fff;   
		    text-shadow:0 0 10px;   
		    letter-spacing: 1px;   
		    text-align: center;   
		}   
		h1{   
		    font-size: 2em;   
		    margin: 0.67em 0;   
		}   
		input{   
		    width: 278px;   
		    height: 18px;   
		    margin-bottom: 10px;   
		    outline: none;   
		    padding: 10px;   
		    font-size: 13px;   
		    color: #fff;   
		    text-shadow:1px 1px 1px;   
		    border-top: 1px solid #312E3D;   
		    border-left: 1px solid #312E3D;   
		    border-right: 1px solid #312E3D;   
		    border-bottom: 1px solid #56536A;   
		    border-radius: 4px;   
		    background-color: #2D2D3F;   
		}   
		.but{   
		    width: 300px;   
		    min-height: 20px;   
		    display: block;   
		    background-color: #4a77d4;   
		    border: 1px solid #3762bc;   
		    color: #fff;   
		    padding: 9px 14px;   
		    font-size: 15px;   
		    line-height: normal;   
		    border-radius: 5px;   
		    margin: 0;   
		}  
	</style>
  </head>
  
  <body>
    <div id="login">  
        <h1>Login</h1>  
        <form method="post">  
            <input type="text" required="required" placeholder="用户名" name="name" id="name" onblur="check_name()"></input><span id="nameReg"></span>  
            <input type="password" required="required" placeholder="密码" name="pwd" id="pwd" onblur="check_pwd()"></input><span id="pwdReg"></span>
            <button class="but" type="submit">登录</button>  
        </form>  
    </div>
    <script type="text/javascript">
    	//js
    	function check_name() {
	      console.log(1);
	      //获取账号
	      var code = document.getElementById("name").value;
	      //校验其格式(\w字母或数字或下划线)
	      var span = document.getElementById("nameReg");
	      var reg = /^[a-zA-Z]{1}([a-zA-Z0-9]|[._]){4,19}$/;
	      if(reg.test(code)) {
	        //通过,增加✓样式
	        span.innerText = "✓";
	        span.style.color = "green";
	      } else {
	        //不通过,增加✗样式
	        span.innerText = "✗";
	        span.style.color = "red";
	      }
	   }
    function check_pwd(){
       console.log(2);
       var code2 = document.getElementById("pwd").value;
       var span2 = document.getElementById("pwdReg");
       var reg2 = /^(\w){6,20}$/;
       if(reg2.test(code2)) {
	        span2.innerText = "✓";
	        span2.style.color = "green";
	      } else {
	        span2.innerText = "✗";
	        span2.style.color = "red";
       } 
    }	
    $(function(){
    	$(":button").on("click",function(){
    		$.ajax({
    			url:"test",
    			type:"post",
    			data:{
    				name:$("#name").val(),
    				pwd:$("#pwd").val()
    			},
    			dataType:"text",
    			success:function(data){
    				if(data == "ok"){
    					window.location.href = "test.jsp";
    				}else{
    					alert("用户名或密码输入错误,请重新输入!");
    				}
    			}
    		});
    	});
    });
    </script> 
  </body>
</html>

如有问题请及时联系作者,会进行及时的更改

你可能感兴趣的:(Jquery)