Web在线聊天室(完结) --- 注册用户+ip地址

Posted 满眼*星辰

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Web在线聊天室(完结) --- 注册用户+ip地址相关的知识,希望对你有一定的参考价值。

注册用户

接口设计

请求:
POST /register
{
	name: xxx,
	password: xxx,
	nickName: "蔡徐坤",
	signature: "我擅长唱跳rap篮球",
}
响应:
HTTP/1.1 200 OK
{
	ok: 1,
	reason: xxx
}

前端异步回调ajax函数

        register(){
          $.ajax({
            url: 'register',
            type: 'post',
            contentType: 'application/json',
            data: JSON.stringify({
              name: app.registerForm.inputUsername,
              password: app.registerForm.inputPassword,
              nickName: app.registerForm.inputNickName,
              signature: app.registerForm.inputSignature,
            }),
            success: function(data, status) {
              if (!data.ok) {
                alert('注册失败! ' + data.reason);
                return;
              }else {
                alert("恭喜你,注册成功!")
              }
              app.registerForm.showDialog = false;
              app.login.showLoginDialog = true;
            }
          })
        }

编写servlet实现注册业务逻辑

package org.example.servlet;

import org.example.dao.UserDao;
import org.example.exception.AppException;
import org.example.model.User;
import org.example.util.Util;

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 javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.Timestamp;

/**
 * Created with IntelliJ IDEA.
 * Description:注册
 * User: starry
 * Date: 2021 -05 -31
 * Time: 16:09
 */

@WebServlet("/register")
public class RegisterServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json");
        User user = new User();
        try {
            //1. 解析请求数据:根据接口文档,需要使用反序列化操作
            User input = Util.deserialize(req.getInputStream(),User.class);
            //2. 业务处理:数据库验证账号密码,如果验证通过,创建session,保存用户信息
            if (input.getName() == null || input.getName().equals("")) {
                throw new AppException("用户名为空");
            }
            if (input.getPassword() == null || input.getPassword().equals("")) {
                throw new AppException("密码为空");
            }
            if (input.getNickName() == null || input.getNickName().equals("")) {
                throw new AppException("昵称为空");
            }
            int result = UserDao.insertUser(input);
            user = input;
            //构造操作成功的正常返回数据:ok-true,业务字段
            user.setOk(true);
        }catch (Exception e) {
            e.printStackTrace();
            //构造操作失败的错误信息:ok-false,reason:错误信息
            user.setOk(false);
            //自定义异常,自己抛,为中文信息,可以给用户看
            if (e instanceof AppException) {    //e捕获到的异常是不是自定义异常
                user.setReason(e.getMessage());
            }else { //非自定义异常,英文信息,给前端看“未知错误”
                user.setReason("未知的错误,请联系管理员");
            }
        }
        //3. 返回响应数据:从响应对象获取输出流,打印输出到响应体body中
        resp.getWriter().println(Util.serialize(user));
    }
}

操作数据库插入新用户

    /**
     * 插入注册用户
     */
    public static int insertUser(User input) {
        Connection connection = null;
        PreparedStatement statement = null;
        try {
            connection = Util.getConnection();
            String sql = "insert user(name,password,nickName,iconPath,signature,lastLogout) values(?,?,?,?,?,?)";
            statement = connection.prepareStatement(sql);
            statement.setString(1,input.getName());
            statement.setString(2,input.getPassword());
            statement.setString(3,input.getNickName());
            statement.setString(4,"");
            statement.setString(5,input.getSignature());
            Timestamp time = new Timestamp(System.currentTimeMillis());
            statement.setTimestamp(6,time);

            //将注册用户返回给前端的数据修改一下
            input.setIconPath("");
            input.setLastLogout(time);

            return statement.executeUpdate();
        }catch (Exception e) {
            throw new AppException("插入注册用户失败",e);
        }finally {
            Util.close(connection,statement);
        }
    }

实现效果

哪一栏没写会提醒 :注册失败+原因
在这里插入图片描述
点击注册后,显示注册成功
在这里插入图片描述
接下来登录duoduo账号,可以登录
在这里插入图片描述

项目发布地址

http://82.156.229.239:8080/java_chatroom/

欢迎小伙伴们点进来看看呀🤗

以上是关于Web在线聊天室(完结) --- 注册用户+ip地址的主要内容,如果未能解决你的问题,请参考以下文章

Web聊天室项目

在线聊天室 --- 需求分析及准备工作

java在线聊天项目 客户端登陆窗口LoginDialog的注册用户功能

java在线聊天项目 客户端登陆窗口LoginDialog的注册用户功能

Golang之写一个聊天室

java在线聊天项目 客户端登陆窗口LoginDialog的注册用户功能 修改注册逻辑 增空用户名密码的反馈 增加showMessageDialog()提示框