作者:Justin Lee
开发工具:myeclipse 6.5
运用技术:ajax,hibernate,jsp/servlet ,javascript,and so on;
数据库:mysql 5.0.18
所需工具包:Hibernate3.2,mysqlDriver
项目名:ajax_app
目录结构:
+ajax_app
+src:里面有:
四个文件夹:action/MemberServlet.java(servlet主要业务处理:注册,登录,验证用户名)
biz/MemberBiz.java(主要与数据库主互:插入会员,根据用户名或者用户名与密码进行查询)
util/HiberSessionFactory.java(系统自动生成,还是挺好用的,可自主化)
entity/Member.java(会员实体)
三个文件:hibernate.cfg.xml/log4j.properties/database.sql(Hibernate配置文件,日志配置文件,数据库脚本)
具体如下图所示:(simpleServlet.java是多余的)
+webroot:目录结构如下图所示:
核心文件源代码:
client.js(ajax核心运用文件,它讲述了如何获取XMLHttpRequest对象)
/**
*@author Justin Lee
*/
function getXMLHttpRequest(){
var client = XMLHttpRequestFromIE();
//非IE浏览器
if(client == null){
client = new XMLHttpRequest()
}
return client;
}
function XMLHttpRequestFromIE(){
var namePrefixes = ["Msxml3","Msxml2","Msxml","Microsoft"];
for(var i = 0; i < namePrefixes.length; i++){
try{
var name = namePrefixes[i] + ".XMLHTTP";
return new ActiveXObject(name);
}catch(e){
}
}
return null;
}
Web.xml:核心配置
<web-app version="2.5"
<servlet>
<description>会员SERVLET</description>
<display-name>会员SERVLET</display-name>
<servlet-name>MemberServlet</servlet-name>
<servlet-class>action.MemberServlet</servlet-class>
</servlet>
register-1.jsp(用户注册核心页面代码)
<%@page contentType="text/html;charset=UTF-8" %>
<!DOCTYPE html PUBLIC
"-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script type="text/javascript" src="${pageContext.request.contextPath}/js/calendar.js"></script>
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/style/style.css"></link>
<script type="text/javascript" src="${pageContext.request.contextPath }/js/client.js" ></script>
<script type="text/javascript">
var client = getXMLHttpRequest();
function checkUsername(){
//第一步获取数据;
var username = document.getElementById("username").value;
//第二步设置连接地址;
var requestUrl = "${pageContext.request.contextPath}";
requestUrl += "/checkUsername.do?username="+username+"&time="+new Date().getTime();
//第三步打开地址;
client.open("GET",requestUrl,true);
//第四步状态判断;
client.onreadystatechange = function(){
if(client.readyState == 4){
var result = client.responseText;
if(result == 1){
document.getElementById("reg_err_msg").innerHTML = "用户:"+username+"已经存在,请更换!";
//alert(username+"已经存在,请更换!");
}else{
document.getElementById("reg_err_msg").innerHTML = "用户:"+username+"可以使用!";
}
}else{
//alert("client.readystate != 4");
}
};
//第五步,发送数据;
client.send(null);
}
function cleanMsg(){
document.getElementById("reg_err_msg").innerHTML = "";
}
</script>
<style type="text/css">
form{
margin: 5px 0;
}
fieldset{
padding: 0 1em 1em 1em;
margin: auto;
width: 400px;
display: block;
}
fieldset div{
margin: 5px 0;
}
legend {
padding: 1em;
}
label{
float: left;
width: 100px;
}
#content div input{
width: 200px;
}
fieldset.buttons{
border: solid 1px #ffffff;
text-align: center;
display:block;
margin-top: 20px;
}
</style>
<title>新用户注册第一步</title>
</head>
<body>
<div id="container">
<jsp:include page="/common/header.jsp" />
<div id="content">
<form method="post" action="<%= request.getContextPath()%>/registe.do">
<div id="reg_err_msg" style="align:center"></div>
<fieldset>
<legend>登录信息[必选]</legend>
<div>
<label for="username">用户名</label>
<input type="text" name="username" id="username"
onblur="checkUsername()" onfocus="cleanMsg()"/>
</div>
<div>
<label for="password">密码</label>
<input type="password" name="password" id="password" />
</div>
<div>
<label for="password2">重复密码</label>
<input type="password" name="password2" id="passwor2" />
</div>
</fieldset>
<fieldset>
<legend>联系信息[可选]</legend>
<div>
<label for="name">真实姓名</label>
<input type="text" name="name" id="name"/>
</div>
<div>
<label for="phone">联系电话</label>
<input type="text" name="phone" id="phone"/>
</div>
<div>
<label for="email">电子邮件</label>
<input type="text" name="email" id="email"/>
</div>
</fieldset>
<fieldset class="buttons">
<input type="submit" value="注册" />
</fieldset>
</form>
</div>
<hr />
<jsp:include page="/common/footer.jsp" />
</div>
</body>
</html>
<servlet-mapping>
<servlet-name>MemberServlet</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
</web-app>
Login.jsp(用户登录核心代码)
<%@page contentType="text/html;charset=gbk" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath }/style/style.css"></link>
<title>登录</title>
<script type="text/javascript" src="${pageContext.request.contextPath }/js/client.js" ></script>
<script type="text/javascript">
var client = getXMLHttpRequest();
function checkUsername(){
//第一步获取数据;
var username = document.getElementById("username").value;
//第二步产生地址;
var requestUrl = "${pageContext.request.contextPath}";
requestUrl += "/checkUsername.do?username="+username+"&time="+new Date().getTime();
//第三步打开地址;
client.open("GET",requestUrl,true);
//第四步状态判断;
client.onreadystatechange = function(){
if(client.readyState == 4){
var result = client.responseText;
if(result == 1){
//document.getElementById("reg_err_msg").innerHTML = "用户:"+username+"可以使用!";
//alert(username+"可使用!");
}else{
document.getElementById("login_msg").innerHTML = "用户:"+username+"不存在,请检查!";
alert(username+"不可使用!");
}
}else{
//alert("client.readystate != 4");
}
};
//第五步,发送数据;
client.send(null);
}
function cleanMsg(){
document.getElementById("login_msg").innerHTML = "";
}
</script>
<style type="text/css">
#content div{
margin: 10px 0px;
}
div.submit{
text-align:center;
}
label{
width:80px;
display:block;
float:left;
}
fieldset{
width:300px;
margin:auto;
margin-top:20px;
display:block;
}
fieldset select{
width:120px;
}
fieldset input{
width:120px;
}
</style>
</head>
<body>
<div id="container">
<jsp:include page="/common/header.jsp" />
<div id="content">
<form action="${pageContext.request.contextPath }/login.do"
method="post" >
<fieldset>
<div id="login_msg">test</div>
<legend>登录信息</legend>
<div>
<label for="username">用户名</label>
<input type="text" name="username" id="username"
onblur="checkUsername()" onfocus="cleanMsg()"/>
</div>
<div>
<label for="password">密码</label>
<input type="text" name="password" id="password" />
</div>
</fieldset>
<div class="submit">
<input type="submit" value="登录" />
<p>如果您还没注册,请<a href="${pageContext.request.contextPath }/register-1.jsp" >点击这里注册</a>成为会员。</p>
</div>
</form>
</div>
<hr />
<jsp:include page="/common/footer.jsp" />
</div>
</body>
</html>
Member.java(会员实体代码)
package entity;
/**
*@author Justin Lee
*/
public class Member {
private static final long serialVersionUID = 立-2755656468981950911L;
private String id;
private String username;
private String password;
private String name;
private String email;
private String phone;
//getter/setter略系统自动生成
}
MemberBiz.java(核心DAO代码)
package biz;
import org.hibernate.Query;
import org.hibernate.Session;
import entity.Member;
/**
* @author Justin Lee
*/
public class MemberBiz {
public void add(Member m){
Session session = null;
try{
session = util.HibernateSessionFactory.getSessionFactory().getCurrentSession();
session.getTransaction().begin();
session.save(m);
session.getTransaction().commit();
}catch(Exception e){
session.getTransaction().rollback();
e.printStackTrace();
}
}
public Member findByUsername(String username){
Session session = null;
try{
session = util.HibernateSessionFactory.getSessionFactory().getCurrentSession();
session.getTransaction().begin();
String hql = "select m from Member m " +
"where m.username=?";
Query query = session.createQuery(hql);
Member m = (Member) query.setParameter(0, username).uniqueResult();
session.getTransaction().commit();
return m;
}catch(Exception e){
session.getTransaction().rollback();
e.printStackTrace();
throw new RuntimeException(e);
}
}
public Member findByUsernameAndPassword(String username,String password){
Session session = null;
try {
session = util.HibernateSessionFactory.getSessionFactory().getCurrentSession();
session.getTransaction().begin();
String hql = "select m from Member m where m.username=? and m.password=?";
Query query = session.createQuery(hql);
Member m = (Member) query.setParameter(0, username).setParameter(1,
password).uniqueResult();
session.getTransaction().commit();
return m;
} catch (Exception e) {
e.printStackTrace();
session.getTransaction().rollback();
throw new RuntimeException(e);
}
}
}
MemberServlet.java(核心业务逻辑代码)
package action;
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 entity.Member;
import biz.MemberBiz;
/**
* @author Justin Lee
*/
public class MemberServlet extends HttpServlet {
private MemberBiz mb;
@Override
public void init() throws ServletException {
mb = new MemberBiz();
}
public void processRequest(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String path = request.getServletPath();
path.substring(0,path.indexOf("."));//得到路径
if(path.equals("/registe.do")){
System.out.println("路径是:"+path);
//registe
this.registe(request, response);
}else if(path.equals("/login.do")){
//login
this.login(request, response);
System.out.println("路径是:"+path);
}else if(path.equals("/checkUsername.do")){
this.checkUsername(request, response);
System.out.println("路径是:"+path);
}
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.processRequest(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.processRequest(request, response);
}
public void login(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
Member m = mb.findByUsernameAndPassword(username, password);
if(m ==null){
//用户名或密码有误!
System.out.println("用户名或密码有误!");
request.setAttribute("login_msg", "用户名或密码有误!");
super.getServletContext().getRequestDispatcher("/login.jsp").forward(request, response);
}else{
//request.getSession().setAttribute("user", m);
super.getServletContext().getRequestDispatcher("/memberCenter.jsp").forward(request, response);
}
}
public void registe(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Member m = new Member();
m.setEmail(request.getParameter("email"));
m.setName(request.getParameter("name"));
m.setPassword(request.getParameter("password"));
m.setPhone(request.getParameter("phone"));
m.setUsername(request.getParameter("username"));
//判断一下
Member member = mb.findByUsernameAndPassword(request.getParameter("username"), request.getParameter("password"));
if(member == null){
mb.add(m);
super.getServletContext().getRequestDispatcher("/register-2.jsp").forward(request, response);
}else{
//request.setAttribute("reg_msg", "该用户已经存在啦!!");
super.getServletContext().getRequestDispatcher("/register-1.jsp").forward(request, response);
}
}
public void checkUsername(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//设置下返回内容
response.setContentType("text/plain;charset=UTF-8");
//reg_err_msg
PrintWriter out = response.getWriter();
String username = request.getParameter("username");
Member m = mb.findByUsername(username);
//0 ok 1 notok
//没有找到,就是说可以用
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if(m == null){
out.println(0);
}else{
out.println(1);
}
out.close();//用了要关掉
}
}