利用ajax和Java實現登錄驗證的小例子

1.javabean

package com.jia.bean;

public class Student {
	private String id;
	private String name;
	private String sex;
	private String password;
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getSex() {
		return sex;
	}
	public void setSex(String sex) {
		this.sex = sex;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
}

這裏設置的是一個Student類,包括了編號、姓名、性別和密碼四個屬性,驗證只用到了編號和密碼這兩個屬性。

2.賬號密碼檢驗

public int checkStudent(String  id,String password) {
		// TODO Auto-generated method stub
		int result = 0;
		Connection con=null;
		PreparedStatement ps=null;
		ResultSet rs=null;
		Student student=null;
		String sql="select * from student where id=?"; //表格名稱爲student
		try {
			con=Conjdbc.getCon(); //這個地方單獨編寫了一個獲取連接的方法
			ps=con.prepareStatement(sql);
			ps.setString(1, id);
			rs=ps.executeQuery();			
			if (rs.next()) {
				student=new Student();
				student.setId(rs.getString(1));
				student.setPassword(rs.getString(4));
			}
			if (student==null) {
				return 0;
			}
			else if (!student.getPassword().equals(password)) {
				return -1;
			}
			else {
				return 1;
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Conjdbc.closeCon(rs, ps, con);
		return result;
	}

檢驗分成了三種情況1.用戶不存在,返回0     2.用戶存在密碼錯誤,返回-1    3.用戶和密碼都正確。

3.對應的Servlet

public class LoginCheck extends HttpServlet {
	

	private static final long serialVersionUID = 1L;

	public void doGet(HttpServletRequest request, HttpServletResponse response)  {
		this.doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)  {
		PrintWriter pw = null;
		int result=0;		
		try {
			request.setCharacterEncoding("utf-8");
			response.setCharacterEncoding("utf-8");
			response.setContentType("text/html;charset=utf-8"); 
			pw=response.getWriter();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}		
		String id="", password="";
		id = request.getParameter("u");
		password = request.getParameter("p");
		result = ConStudentDAO.getInstance().checkStudent(id, password); //單例	
		if (result==0) {					 
			pw.print("用戶不存在!");
		} 
		else if (result==-1) {
			pw.print("密碼錯誤!");
		}
		else {
			pw.print("登錄成功!");
		}
	}
}

這個部分對前臺傳過來的數據進行數據庫查詢,判斷屬於哪種情況將信息返回給前臺。其中一定要注意字符編碼問題,一般網頁都使用的utf-8來編碼。

4.前端設計

<div class="login" >
	<h1>Login</h1>
	<form > 
		<input type="text" id="uname" name="u" placeholder="用戶名" required="required" />
		<input type="password" id="pword" name="p" placeholder="密碼" required="required" />
		<button type="button" class="btn btn-primary btn-block btn-large" onclick="loadCheck()">登錄</button>
		<div id="insert" style="color:red;padding:10px;font-size:12px"></div>
	</form>
</div>

這部分是表單,其中最下面的div用來顯示後臺返回的信息。

<script type="text/javascript">
	var xmlhttp;
	function loadCheck(){
		var uname=document.getElementById('uname').value;
		var pword=document.getElementById('pword').value;
		if(uname.length==0||pword.length==0){alert("賬號或密碼爲空");return;}
		if (window.XMLHttpRequest) {xmlhttp=new XMLHttpRequest();}
		else{xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");}	
		xmlhttp.onreadystatechange=getResult;
		xmlhttp.open("POST","Demo",true);
		xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
		xmlhttp.send("u="+uname+"&p="+pword);		
	}
	
	function getResult(){
		if (xmlhttp.readyState==4) {		
			if(xmlhttp.status==200){
				var rec=xmlhttp.responseText;
				document.getElementById("insert").innerHTML=rec;
			}
			else{
				alert("連接失敗");
			}
		}
	}
</script>

這部分的js將表單的數據傳到後臺,接收後臺的信息嵌入到前面的div中,有個要注意的問題是xmlhttp.resposeText應該寫在200d的判斷條件下,不然可能接收到的數據可能會變成問號。

5.結果展示

6.總結

在這個小例子的編寫中學到了很多,例如關於Servlet,每一個servlet都只會創建一個實例,而多線程是用在其中的如doPost方法中的,servlet類中的成員變量是所有連接共享的。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章