码迷,mamicode.com
首页 > Web开发 > 详细

使用Ajax的异步登陆

时间:2016-05-07 08:26:10      阅读:271      评论:0      收藏:0      [点我收藏+]

标签:

使用Ajax的异步登陆

1.其实大家也经常遇到这样的情况,进行注册时,当光标放到第二个输入框时,会出现已被注册或使用,或者是可以注册的字样。页面不用跳转,直接可以返回数据。
2.当点击免费发送短信的按钮,发送到手机上的验证码。页面也不用跳转。
以上两种功能,均可以用Ajax来完成
技术分享

下面就用Ajax来实现这个功能
1.Ajax的原理: Ajax的原理就是:通过javascript的方式,将前台数据通过xmlhttp对象传递到后台,
后台在接收到请求后,将需要的结果,再传回到前台,这样就可以实现不需要页面的转发,
数据实现来回传递,从而实现页面无刷新。 基于这个原理,我想到使用Ajax传输登录的信息,包括错误信息,功能很强大,保证绝对的用户友好型。 
2.使用Ajax异步提交登录可以实现功能:可以提示用户名错误,可以提示用户名正确但是密码不正确...等等一切错误信息。

项目简介:
 jsp+mysql+servlet
技术分享
DAO层(数据库连接层)
CustomerDaoImo.java
package com.ajax.dao;

import java.sql.SQLException;

import com.ajax.entity.Customer;

public class CustomerDaoImo  extends JdbcConnection {
	public Customer selectByName(String custname){
		Customer cust=null;
		String sql="select * from customer where custname= ?";
		try {	
			getconnection();
			psmt=conn.prepareStatement(sql);
			psmt.setString(1, custname);
			rs=psmt.executeQuery();
			if(rs.next()){
			cust=new Customer(rs.getString(1), rs.getString(2), rs.getInt(3), rs.getString(4));	
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			System.out.println("发生错误");
			e.printStackTrace();
		}finally{
			closeAll();
		}
		return cust;
	}
	
}
JdbcConnection.java
package com.ajax.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class JdbcConnection {
	private final static String  CLS="com.mysql.jdbc.Driver";
	private final static String  URL="jdbc:mysql://localhost:3306/books";
	private final static String USER="root";
	private final static String PWD="122198";
	public static Connection conn=null;
	public static PreparedStatement psmt=null;
	public static ResultSet rs=null;
	public static void getconnection(){
		try {
			Class.forName(CLS);
			conn=DriverManager.getConnection(URL,USER,PWD);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	public static void closeAll(){
		
			try {
				if(rs!=null){
				rs.close();
				}
				if(psmt!=null){
					psmt.close();
				}
				if(conn!=null){
					conn.close();
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		
	}
	
}
Bean层(实体类)
package com.ajax.entity;

public class Customer {
	private String custname;
	private String pwd;
	private int age;
	private String address;
	public String getCustname() {
		return custname;
	}
	public void setCustname(String custname) {
		this.custname = custname;
	}
	public String getPwd() {
		return pwd;
	}
	public void setPwd(String pwd) {
		this.pwd = pwd;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public String getAddress() {
		return address;
	}
	public void setAddress(String address) {
		this.address = address;
	}
	public Customer(String custname, String pwd, int age, String address) {
		super();
		this.custname = custname;
		this.pwd = pwd;
		this.age = age;
		this.address = address;
	}
	
<span style="color:#ff0000;">}
</span>
servlet层(控制层)
AJax提交的页面
package com.ajax.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;

import com.ajax.dao.CustomerDaoImo;
import com.ajax.entity.Customer;

public class RegisterServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
	throws ServletException, IOException {

		System.out.println("nihjao");
		PrintWriter out=response.getWriter();
		CustomerDaoImo dao=new CustomerDaoImo();
		System.out.println("值"+request.getParameter("custname"));
		String a=	request.getParameter("custname");
		Customer c=dao.selectByName(a);
		System.out.println("cuowu");
		boolean passed=(c==null);
		response.setContentType("text/xml");
		response.setHeader("Cache-Control", "no-cache");
		<span style="color:#ff0000;">//账号已被注册,请重新输入</span>
		String message="The custname already be registered";
		if(passed){
			<span style="color:#ff0000;">//可以注册</span>
			message="You have entered a valid custname.";
		}
		out.write("<response>");
		out.write("<passed>"+Boolean.toString(passed)+"</passed>");
		out.write("<message>"+message+"</message>");
		out.write("</response>");
		out.close();
	}
	public void doPost(HttpServletRequest request, HttpServletResponse response)
	throws ServletException, IOException {


	}

}
View层(视图)
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>My JSP 'index.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">
		<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
		<script type="text/javascript"> <span style="color:#ff0000;"> <!--异步登陆!--></span>
	var xmlHttp;
	function createXMLHttpRequest(){
		if(window.ActiveXObject){
		xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
	}else if(window.XMLHttpRequest){
		xmlHttp=new XMLHttpRequest();
	}
}
	function validate(){
	 createXMLHttpRequest();
	 var name=document.getElementById("custname");
	 var url="registerajax?custname="+escape(name.value);
	// alert("地址"+url);
	 xmlHttp.open("GET",url,true);
	 xmlHttp.onreadystatechange=callback;
	 xmlHttp.send(null);
	}
	function callback(){
		if(xmlHttp.readyState==4){
		//	alert(xmlHttp.status);
			if(xmlHttp.status==200){
		   var mes=xmlHttp.responseXML.getElementsByTagName("message")[0].firstChild.data;
		    alert(mes);
		   var val=xmlHttp.responseXML.getElementsByTagName("passed")[0].firstChild.data;
		 setMessage(mes,val);	
			}
		}
	}
	function setMessage(message,isValid){
	//alert(message);
	var messageArea=document.getElementById("custnameerror");
	var fontColor="red";
	  if(isValid=="true"){
	   fontColor="green";
	  }
	  messageArea.innerHTML="<font  color="+fontColor+">"+message+"</font>";
	}
</script>
	</head>

	<body>
		<form action="registera" method="post">
			<table>
			   <tr>
			     <td> Your custname:</td>
			     <td>
			      <input type="text" name="custname" onchange="validate()">
			    <font id="custnameerror"> </font>
			      </td>
			      
			   </tr>
			  <tr>
			    <td>  Your password:</td>
			    <td><input type="password" name="pwd"></td>
			  </tr>
			   <tr>
			    <td>  Your age:</td>
			    <td><input type="text" name="address"></td>
			  </tr>
			  <tr>
			  <td > <input type="submit" value="Register"></td>
			 
			  </tr>
			</table>
			 
		</form>
	</body>
</html>
最后别忘了配置参数web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
	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 
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>RegisterServlet</servlet-name>
    <servlet-class>com.ajax.servlet.RegisterServlet</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>RegisterServlet</servlet-name>
    <url-pattern>/registerajax</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>
最后项目运行结果图展示:
                                 可以被注册
技术分享
                   该账号已被注册
技术分享
下面是项目源码,附带数据库。http://pan.baidu.com/s/1i5yHzBf

使用Ajax的异步登陆

标签:

原文地址:http://blog.csdn.net/zhupengqq/article/details/51330704

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!