JavaWeb连接数据库实现简单注册和登录功能

JavaWeb连接数据库实现简单注册和登录功能_第1张图片

后台

一、首先要建包

划分包,不同的包放不同的类

controller,dao,domain,file,service,utils,validate

二、不同包的使用

controller

封装对象并获取前台数据


import org.apache.commons.beanutils.BeanUtils;

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;
import java.lang.reflect.InvocationTargetException;
import java.net.URLEncoder;
import java.util.Map;

@WebServlet("/UserController")
public class UserController extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");

        User user = new User();
        try {
            //使用BeanUtils工具快速封装对象
            BeanUtils.populate(user, req.getParameterMap());
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

        //获取登录的错误信息
        Map error = ValidateDemo.vailDate(user);
        //获取注册的错误信息
        Map error1 = ValidateDemo1.vailDaet(user);

        //获取到隐藏的表单,分别执行注册和登录
        String str = req.getParameter("hidden");
        Register register = new Register();

        //注册
        if ("register".equals(str)) {
            if (error1.isEmpty()) {
                int register1 = register.register(user);
                if (register1 == 0) {
                    resp.sendRedirect("/web2/registerfail.jsp");
                } else if (register1 == 1) {
                    resp.sendRedirect("/web2/registersucc.jsp");
                } else if (register1 == 2) {
                    String test = URLEncoder.encode("用户已存在", "UTF-8");
                    resp.sendRedirect("/web2/register.jsp?test=" + test);
                }

            } else {
                req.setAttribute("error1", error1);
                req.getRequestDispatcher("/register.jsp").forward(req, resp);
            }
        }

        //登录
        if ("login".equals(str)) {
            if (error.isEmpty()) {
                Boolean bool = register.login(user);
                if (bool) {
                    String encode = URLEncoder.encode(user.getUsername(), "UTF-8");
                    resp.sendRedirect("/web2/index.jsp?encode=" + encode);
                } else {
                    req.setAttribute("error", error);
                    req.setAttribute("fail", "注册失败");
                    req.getRequestDispatcher("login.jsp").forward(req, resp);
                }
            } else {
                req.setAttribute("error", error);
                req.getRequestDispatcher("login.jsp").forward(req, resp);
            }
        }

    }
}

dao

操作数据库

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 操作数据库
 */

public class UserDao {
    /**
     * 登录
     * @param username
     * @param password
     * @return
     */
    public boolean findUsernameAndPassword(String username,String password){
        boolean flag = false;
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            conn = DBUtils.dbutils();
            String sql = "SELECT id FROM USER WHERE username = ? AND password = ?";
            ps = conn.prepareStatement(sql);
            ps.setString(1,username);
            ps.setString(2,password);
            rs = ps.executeQuery();
            while (rs.next()){
                if (rs.getInt(1) > 0){
                    flag = true;

                }

            }

        } catch (SQLException e) {
            e.printStackTrace();
        }

        DBUtils.dbClose(conn,ps,rs);
        return flag;
    }


    /**
     * 注册
     * @param username
     * @return
     */
    public boolean findUserByName(String username){
        boolean flag = false;
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            conn = DBUtils.dbutils();
            String sql = "SELECT id FROM USER WHERE username = ?";
            ps = conn.prepareStatement(sql);
            ps.setString(1,username);
            rs = ps.executeQuery();
                while (rs.next()){
                    if (rs.getInt(1) > 0){
                        flag = true;

                    }

                }

        } catch (SQLException e) {
            e.printStackTrace();
        }

        DBUtils.dbClose(conn,ps,rs);
        return flag;
    }


    /**
     * 添加用户
     * @param user
     * @return
     */
    public int addUser(User user){
        int i = 0;
        Connection conn = null;
        PreparedStatement ps = null;
        try {
            conn = DBUtils.dbutils();
            String sql = "INSERT INTO USER (username,password,age,gender,hobby,address,remark) values(?,?,?,?,?,?,?)";
            ps = conn.prepareStatement(sql);
            ps.setString(1,user.getUsername());
            ps.setString(2,user.getPassword());
            ps.setInt(3,user.getAge());
            ps.setString(4,user.getGender());
            ps.setString(5,user.getHobby());
            ps.setString(6,user.getAddress());
            ps.setString(7,user.getRemark());
            i = ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        DBUtils.dbClose(conn,ps,null);

        return i;
    }
}

file

存储文件

drive=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/test_1
username=root
password=root

utils

工具类

import java.sql.*;
import java.util.Properties;


public class DBUtils {


    //因为dao层有多个方法要调用所有改写为静态,减少内存
    static String drive;
    static String url;
    static String username;
    static String password;
    static Connection conn;
    static {
        Properties p = ReadFileDome.readFile();
        drive = p.getProperty("drive");
        url = p.getProperty("url");
        username = p.getProperty("username");
        password = p.getProperty("password");
        try {
            Class.forName(drive);
        } catch (ClassNotFoundException e1) {
            e1.printStackTrace();
        }
    }


    /**
     * 注册驱动
     */
    public static Connection dbutils() {
        try {
            conn = DriverManager.getConnection(url,username,password);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }

    /**
     * 关闭资源
     * @param conn
     * @param ps
     * @param rs
     */
    public static void dbClose(Connection conn, PreparedStatement ps, ResultSet rs){
        if (conn != null){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (ps != null){
            try {
                ps.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (rs != null){
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

    }
    }
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * 使用类加载去读取文件
 */
public class ReadFileDome {
    public static Properties readFile(){
        InputStream is = ReadFileDome.class.getClassLoader().getResourceAsStream("com/xuexi/file/db.properties");
        Properties p = new Properties();
        try {
            p.load(is);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return p;
    }
}

service

业务逻辑

import com.xuexi.dao.UserDao;
import com.xuexi.domain.User;

import java.util.List;

/**
 * 业务逻辑
 */
public class Register {
   

    //登录
    public boolean login(User user){
        UserDao ud = new UserDao();
        boolean uap = ud.findUsernameAndPassword(user.getUsername(), user.getPassword());
        return uap;
    }

    //注册
    public int register(User user){
        int num;
        UserDao ud = new UserDao();
        boolean userByName = ud.findUserByName(user.getUsername());
        if (userByName){
            num = 2;
        }else {
            if (!userByName){
                num = 1;
                ud.addUser(user);
            }else {
                num = 0;
            }

        }
        return num;
    }
}

validate

验证表单

import java.util.HashMap;
import java.util.Map;

/**
 * 登录验证
 */
public class ValidateDemo {
    public static Map vailDate(User user) {


        //Map集合用来收集不同的错误数据,然后在前台进行使用
        Map error = new HashMap<>();

        //使用正则表达式来对表单数据进行限制
        //判断用户名
        if (user.getUsername() == null || "".equals(user.getUsername().trim())) {
            error.put("username", "用户名不能为空");
        } else if (!(user.getUsername().matches("\\w{6,18}"))) {
            error.put("username", "用户名不合法");
        }

        //判断密码
        if (user.getPassword() == null || "".equals(user.getPassword().trim())) {
            error.put("password", "密码不能为空");
        } else if (!(user.getPassword().matches("[0-9a-zA-Z]{6,18}"))) {
            error.put("password", "密码不合法");
        }

        //判断邮箱
        if (user.getEmail() == null || "".equals(user.getEmail().trim())) {
            error.put("email", "邮箱不能为空");
        } else if (!(user.getEmail().matches("\\w+[@][0-9a-zA-Z]+[.][0-9a-zA-Z]+"))) {
            error.put("email", "邮箱不合法");
        }

        //判断电话
        if (user.getTell() == null || "".equals(user.getTell().trim())) {
            error.put("tell", "电话不能为空");
        } else if (!(user.getTell().matches("^1[0-9]{10}"))) {
            error.put("tell", "电话不合法");
        }

        return error;
    }
}
import java.util.HashMap;
import java.util.Map;

/**
 * 注册验证
 */
public class ValidateDemo1 {
    public static Map vailDaet(User user){
        //Map集合用来收集不同的错误数据,然后在前台进行使用
        Map error1 = new HashMap<>();

        //使用正则表达式来对表单数据进行限制
        //判断用户名
        if (user.getUsername() == null || "".equals(user.getUsername().trim())) {
            error1.put("username", "用户名不能为空");
        } else if (!(user.getUsername().matches("\\w{6,18}"))) {
            error1.put("username", "用户名不合法");
        }

        //判断密码
        if (user.getPassword() == null || "".equals(user.getPassword().trim())) {
            error1.put("password", "密码不能为空");
        } else if (!(user.getPassword().matches("[0-9a-zA-Z]{6,18}"))) {
            error1.put("password", "密码不合法");
        }
        return error1;
    }
}

domain

实体

public class User {
    private String username;
    private String password;
    private String gender;
    private int age;
    private String email;
    private String tell;
    private String hobby;
    private String address;
    private String remark;

    public User(String username,String password,int age,String gender,String hobby,String address,String remark){
        this.username = username;
        this.password = password;
        this.age = age;
        this.gender = gender;
        this.hobby = hobby;
        this.address = address;
        this.remark = remark;
    }

    public User(){

    }


    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getTell() {
        return tell;
    }

    public void setTell(String tell) {
        this.tell = tell;
    }

    public String getHobby() {
        return hobby;
    }

    public void setHobby(String hobby) {
        this.hobby = hobby;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getRemark() {
        return remark;
    }

    public void setRemark(String remark) {
        this.remark = remark;
    }

    @Override
    public String toString() {
        return "User{" +
                "username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", gender='" + gender + '\'' +
                ", age=" + age +
                ", hobby='" + hobby + '\'' +
                ", address='" + address + '\'' +
                ", introduce='" + remark + '\'' +
                '}';
    }
}

前台

准备注册页面,登录页面,注册成功页面,注册失败页面,首页

注册页面



    $Title$
    



<%--获取错误数据--%>
<%
    HashMap error1 = (HashMap) request.getAttribute("error1");
    String test = request.getParameter("test");
%>
<%=test == null ? "" : test%>
<%--隐藏表单--%>
注册信息
用户名: <%=error1 == null ? "" : error1.get("username") == null ? "" : error1.get("username")%>
密码: <%=error1 == null ? "" : error1.get("password") == null ? "" : error1.get("password")%>
年龄:
出生日期:
性别
爱好 篮球
住址
备注:

登录页面



    Title


<%--获取错误数据--%>
<%
    HashMap error = (HashMap) request.getAttribute("error");
    String fail =  (String )request.getAttribute("fail");
%>
用户名:<%=fail == null ? "" : fail%><%=error == null ? "" : error.get("username") == null ? "" : error.get("username")%>
密码:<%=error == null ? "" : error.get("password") == null ? "" : error.get("password")%>
邮箱:<%=error == null ? "" : error.get("email") == null ? "" : error.get("email")%>
电话:<%=error == null ? "" : error.get("tell") == null ? "" : error.get("tell")%>

注册成功页面



    Title


注册成功

登录

注册失败页面



    Title


注册失败

返回

首页



    Title


<%
    String encode = request.getParameter("encode");
%>
欢迎 <%=encode%> 登录

你可能感兴趣的:(数据库,java)