视频演示

链接:https://pan.baidu.com/s/14RGCj92dzSPj_Em1iYegPg
提取码:1111

项目源码:

loginregister.7z(点击下载)

 

环境搭建:

  1. jdk 1.8
  2. 开发工具:IntelliJ IDEA 20.2
  3. 存储文件:xml
  4. 开发平台:Windows 10

功能介绍:

登录:

1. 判断用户名是否已经存在,若不存在给出提示(ajax)

2. 若登录成功,跳转至登录成功界面,显示“欢迎XXX,登录成功”
3. 若登录失败,跳转至登录失败界面,显示“哦豁,登录失败了”

注册:

4. 判断用户名是否已经存在,如果存在给出提示“该用户名已注册”,若不存在给出提示“此用户名可用”,若为空则不给出提示
           
5. 若注册成功,跳转至成功界面,显示“恭喜您,注册成功”
6. 若注册失败,跳转至失败界面,显示“哦豁,注册失败了”
 


 

源代码

项目目录结构:


 

ajax技术:

《ajax.js》


/*
ajax的四步:
 第一步获取xmlHttp对象
 第二步打开连接
 第三步发送连接
 第四步为onreadystatechange添加监听
*/
var createXMLHttpRequest = function () {
    try {
        return new XMLHttpRequest();
    } catch (e) {
        try {
            return new ActiveXObject("Msxml2.XMLHttp");
        } catch (e) {
            try {
                return new ActiveXObject("Microsoft.XMLHttp");
            } catch (e) {
                alert("浏览器不支持……");
                return e;
            }
        }
    }
}
window.onload = function () {
    /**
     * 登录时,查询用户存不存在
     * */
    var loginusername = document.getElementsByName("username")[0];
    loginusername.onblur = function () {
        var xmlHttp = createXMLHttpRequest();
        xmlHttp.open("POST", "CheckUserExistServlet", true);
        // 设置请求体
        xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        xmlHttp.send("username=" + loginusername.value);
        xmlHttp.onreadystatechange = function () {
            if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
                var result = xmlHttp.responseText;
                var span = document.getElementsByName("usernamespan")[0];
                if (result == "0" || result == "1") {
                    span.innerHTML = ""
                } else {
                    span.innerHTML = "此用户名不存在";
                }
            }
        }
    }
    /**
     * 注册时查询用户存不存在
     * */
    var registerusername = document.getElementsByName("username")[1];
    registerusername.onblur = function () {
        var xmlHttp = createXMLHttpRequest();
        xmlHttp.open("POST", "CheckUserExistServlet", true);
        // 设置请求体
        xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        xmlHttp.send("username=" + registerusername.value);
        xmlHttp.onreadystatechange = function () {
            if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
                var result = xmlHttp.responseText;
                var span = document.getElementsByName("usernamespan")[1];
                if (result == "1") {
                    span.innerHTML = "该用户名已注册";
                } else if (result == "0") {
                    span.innerHTML = ""
                } else {
                    span.innerHTML = "此用户名可用";
                }
            }
        }
    }
}

 

 
《CheckUserExistServlet》


package cn.onedraw.web.servlet;
import cn.onedraw.service.UserService;
import cn.onedraw.service.UserServiceImpl;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
 * 检查用户名是否已存在
 * 存在返回:“1”
 * 不存在返回:"-1"
 * 输入为空返回:“0”
 * */
@WebServlet("/CheckUserExistServlet")
public class CheckUserExistServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        // 获取用户名
        String username = request.getParameter("username");
        // 用户名为空,返回“0”
        if ("".equals(username)) {
            response.getWriter().print("0");
            return;
        }
        UserService userService = new UserServiceImpl();
        // 用户存在
        if (userService.isUserExist(username)) {
            response.getWriter().print("1");
        } else {
            response.getWriter().print("-1");
        }
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    }
}

 
 

登录处理:

《LoginServlet》


package cn.onedraw.web.servlet;
import cn.onedraw.service.UserService;
import cn.onedraw.service.UserServiceImpl;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
 * 处理登录请求,将登录结果发送到page/result.jsp文件
 *
 * */
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        // 获取用户名和密码
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        UserService userService = new UserServiceImpl();
        // 设置操作类型为login
        request.getSession().setAttribute("option", "login");
        // 登录成功
        if (userService.login(username, password)) {
            request.getSession().setAttribute("login", "true");
            request.getSession().setAttribute("username", username);
        } else {
            request.getSession().setAttribute("login", "false");
        }
        // 请求转发
        request.getRequestDispatcher("page/result.jsp").forward(request, response);
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    }
}

 

注册处理:

《RegisterServlet》


package cn.onedraw.web.servlet;
import cn.onedraw.domain.User;
import cn.onedraw.service.UserService;
import cn.onedraw.service.UserServiceImpl;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
/**
 * 处理注册请求,将注册结果发送到page/result.jsp
 * */
@WebServlet("/RegisterServlet")
public class RegisterServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String phone = request.getParameter("phone");
        User user = new User(username, password, phone);
        UserService userService = new UserServiceImpl();
        request.getSession().setAttribute("option", "register");
        if (userService.addUser(user)) {
            request.getSession().setAttribute("register", "true");
            request.getSession().setAttribute("username", username);
        } else {
            request.getSession().setAttribute("register", "false");
        }
        request.getRequestDispatcher("page/result.jsp").forward(request, response);
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    }
}

 

XML存储文件操作:

《UserDaoImpl》


package cn.onedraw.dao;
import cn.onedraw.domain.User;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import java.io.*;
import java.util.List;
public class UserDaoImpl implements UserDao {
    /**
     * 项目要操作的xml文件路径
     * */
    private final String path = "E:\\IdeaProject\\web\\loginregister\\src\\user.xml";
    /**
     * 根据用户名查询用户是否在系统中
     * 是:返回true
     * 否:返回false
     * */
    @Override
    public boolean isUserExist(String username) {
        SAXReader saxReader = new SAXReader();
        try {
            // 解析xml
            Document document = saxReader.read(path);
            // 查询所有用户的名字,用户名在标签的属性中
            List<Attribute> list = document.selectNodes("//user/@name");
            for (Attribute attribute : list) {
                // 如果存在,返回true
                if (attribute.getValue().equals(username)) {
                    return true;
                }
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return false;
    }
    /**
     * 增加一个用户
     * 成功:返回true
     * 失败:返回false
     * */
    @Override
    public boolean addUser(User user) {
        SAXReader saxReader = new SAXReader();
        try {
            // 解析xml
            Document document = saxReader.read(this.path);
            // 获取根元素
            Element root = document.getRootElement();
            // 在根元素下创建新的元素
            Element newUser = root.addElement("user");
            // 设置属性
            newUser.addAttribute("name", user.getUsername());
            newUser.addAttribute("password", user.getPassword());
            newUser.addAttribute("phone", user.getPhone());
            // 写回html
            try {
                // 输出漂亮的格式
                OutputFormat outputFormat = OutputFormat.createPrettyPrint();
                outputFormat.setEncoding("utf-8");
                XMLWriter xmlWriter = new XMLWriter(new OutputStreamWriter(new FileOutputStream(this.path), "UTF-8"), outputFormat);
                xmlWriter.write(document);
                xmlWriter.close();
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        } catch (DocumentException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }
    /**
     * 登录操作,进行查询用户名和密码
     * 成功返回true
     * 失败返回false
     * */
    @Override
    public boolean login(String username, String password) {
        // 创建解析器
        SAXReader saxReader = new SAXReader();
        try {
            // 解析xml文件
            Document document = saxReader.read(this.path);
            // 获取根元素
            Element rootElement = document.getRootElement();
            // 获取根元素下的所有元素,得到列表
            List<Element> elements = rootElement.elements();
            // 遍历列表
            for (int i = 0; i < elements.size(); i++) {
                Element element = elements.get(i);
                // 得到用户名和密码,进行判断
                String name = element.attribute("name").getValue();
                String pwd = element.attribute("password").getValue();
                if (name.equals(username) && pwd.equals(password)) {
                    return true;
                }
            }
        } catch (DocumentException e) {
            e.printStackTrace();
            return false;
        }
        return false;
    }
}

 
注:项目前端登录注册界面来自源码之家


代码编译器:IntelliJ IDEA 20.02
 

您必须 登录 才能发表评论