JavaWeb后端简单实现注册+登录demo

1.创建UserDao类实现与数据库进行交互

package cn.imyjs.dao;

import cn.imyjs.domain.User;
import cn.imyjs.utils.JDBCutils;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

public class UserDao {
    //声明JDBCtemplate对象公用
    private JdbcTemplate template = new JdbcTemplate(JDBCutils.getDataSource());
    /**
     * 登录方法实现
     * @param loginUser
     * @return 用户全部数据或者NULL
     */
    public User login(User loginUser){
        try {
            //编写SQL语句
            String sql = "select * from user where username = ? and upassword = ?";
            //调用Query方法执行SQL语句
            User user = template.queryForObject(sql, new BeanPropertyRowMapper<User>(User.class), loginUser.getUsername(), loginUser.getUpassword());
            return user;
        } catch (DataAccessException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 注册方法实现
     * @param registerUser
     * @return false or true
     */
    public int register(User registerUser){
        try {
            int count = 0;
            String sql = "select count(*) from user where username = ? or uemail = ?";
            count = template.queryForObject(sql,Integer.class,registerUser.getUsername(),registerUser.getUemail());
            System.out.println(count);
            if(count != 0){
                return 0;
            }
            //编写SQL语句
            sql = "INSERT INTO USER(username,upassword,uemail,usex,uphone) VALUES(?,?,?,?,?)";
            //调用execute方法执行SQL语句
            count = template.update(sql,registerUser.getUsername(),registerUser.getUpassword(),
                    registerUser.getUemail(),registerUser.getUsex(),registerUser.getUphone());
            System.out.println(count);
            return count;
        } catch (DataAccessException e) {
            e.printStackTrace();
            return -1;
        }
    }
}

2.创建LoginServlet登录类

package cn.imyjs.web;

import cn.imyjs.dao.UserDao;
import cn.imyjs.domain.User;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;
import org.apache.commons.beanutils.BeanUtils;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.设置编码
//        req.setCharacterEncoding("utf-8");
        //2.获取请求参数
//        String username = req.getParameter("username");
//        String password = req.getParameter("upassword");
        //3.封装user对象
//        User loginUser = new User();
//        loginUser.setUsername(username);
//        loginUser.setUpassword(password);

        Map<String, String[]> parameterMap = req.getParameterMap();

        User loginUser = new User();
        try {
            BeanUtils.populate(loginUser,parameterMap);
            //populate封装对象时,实际上是调用了该对象所属类的set方法,因此页面表单内元素的name属性值一定要与实体类中的属性名一致.
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        System.out.println(loginUser.getUsername()+ loginUser.getUpassword());

        //4.调用UserDao的login方法
        UserDao dao = new UserDao();
        User user = dao.login(loginUser);

        //5.判断user
        if (user == null) {
            //登录失败
//            req.getRequestDispatcher("/failServlet").forward(req, resp);
            //设置编码
            resp.setContentType("text/html;charset=utf-8");
            //输出
            resp.getWriter().write("登录失败,用户名或密码错误");
        } else {
            //登录成功
            //存储数据
            req.setAttribute("user", user);
            //转发
//            req.getRequestDispatcher("/successServlet").forward(req, resp);
            //设置编码
            resp.setContentType("text/html;charset=utf-8");
            //输出
            resp.getWriter().write("登录成功!" + user.getUsername() + ",欢迎您");
        }
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        super.doPost(req, resp);
        this.doGet(req,resp);

    }
}

 

3.创建RegisterServlet注册类

package cn.imyjs.web;

import cn.imyjs.dao.UserDao;
import cn.imyjs.domain.User;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.beanutils.BeanUtils;

import javax.swing.plaf.synth.SynthOptionPaneUI;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

@WebServlet("/RegisterServlet")
public class RegisterServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.设置编码
        req.setCharacterEncoding("utf-8");
        //2.获取请求参数
//        String username = req.getParameter("username");
//        String password = req.getParameter("upassword");

        //3.封装user对象
//        User registerUser = new User();
//        registerUser.setUsername(username);

        Map<String, String[]> parameterMap = req.getParameterMap();
        User registerUser = new User();
        try {
            BeanUtils.populate(registerUser,parameterMap);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        System.out.println(registerUser.getUsername() + '\n'+ registerUser.getUpassword()+ '\n'+ registerUser.getUsex()+ '\n'+ registerUser.getUemail()+ '\n'+ registerUser.getUphone());
        //4.调用UserDao的login方法
        UserDao dao = new UserDao();
        int count = dao.register(registerUser);
        System.out.println(count);
        //5.判断user
        if (0 == count) {
            //登录失败邮箱或用户名已被注册
            //设置编码
            resp.setContentType("text/html;charset=utf-8");
            //输出
            resp.getWriter().write("邮箱或用户名已被注册!");
        } else if(-1 == count){
            //登录失败
            //设置编码
            resp.setContentType("text/html;charset=utf-8");
            //输出
            resp.getWriter().write("未知错误,注册失败!");
        }else {
            //存储数据
            req.setAttribute("user", registerUser);
            //设置编码
            resp.setContentType("text/html;charset=utf-8");
            //输出
            resp.getWriter().write("注册成功!" + registerUser.getUsername() + ",欢迎您");
        }
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        super.doPost(req, resp);
        this.doGet(req,resp);

    }
}

 

微信关注

阅读剩余
THE END