JavaWeb 第三章 Servlet+JDBC实现登录注册

Servlet+jdbc实现登录注册

      • 一、步骤
      • 二、封装连接数据库的工具类
          • JDBCUtils
          • config.properties
          • 引入数据库的工具类
      • 三、注册
          • register.jsp
          • User
          • BaseDao 接口
          • UserDao.java
          • RegisterServlet.java
      • 四、登录
          • login.jsp
          • LoginServlet.java

一、步骤

  1. 准备数据库 javaweb2305或者javaweb2306
  2. 创建数据库表 student
  3. 创建三层架构模块
    JavaWeb 第三章 Servlet+JDBC实现登录注册_第1张图片

二、封装连接数据库的工具类

JDBCUtils
package cn.tedu.utils;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;


public class JDBCUtils {
    public JDBCUtils(){}
    private static String driverClass;
    private static String url;
    private static String username;
    private static String passward;
    private static Connection con;

    static {

        try {
            InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("config.properties");
            Properties prop = new Properties();
            prop.load(is);

            driverClass = prop.getProperty("driverClass");
            url = prop.getProperty("url");
            username = prop.getProperty("username");
            passward = prop.getProperty("password");

            Class.forName(driverClass);


        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }


    }
    public static Connection getConnection(){
        try {
            con = DriverManager.getConnection(url,username,passward);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return con;
    }
    public static void close(Connection con, Statement sta, ResultSet rs){
        if (con != null){
            try {
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (sta != null){
            try {
                sta.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (rs != null){
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

    }
    public static void close(Connection con, Statement sta){
        if (con != null){
            try {
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (sta != null){
            try {
                sta.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}


config.properties
driverClass = com.mysql.cj.jdbc.Driver
url = jdbc:mysql://localhost:3306/javaweb
username = root
password = root
引入数据库的工具类

JavaWeb 第三章 Servlet+JDBC实现登录注册_第2张图片
JavaWeb 第三章 Servlet+JDBC实现登录注册_第3张图片

三、注册

register.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>注册页面</title>
</head>
<body>
<div style="text-align: center">
    <form action="RegisterServlet" method="post" id="registerform">
        账号:<input type="text" placeholder="手机号或邮箱" name="username"/><br>
        密码:<input type="password" placeholder="密码" name="password"/><br>
        <input type="submit" class="inputButton" value="注册" />
    </form>
</div>
</body>
</html>
User
package cn.tedu.bean;

public class User {
    private Integer id;
    private String username;
    private String password;

    public User(Integer o, String username, String password) {
        this.id=o;
        this.username=username;
        this.password=password;
    }

    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    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;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                '}';
    }
}
BaseDao 接口
package cn.tedu.dao;

import java.util.List;

public interface BaseDao<E> {
    public boolean add(E e);

    public void delete(E e);

    public void update(E e);

    public boolean findbone(String username, String passward);

    public List<E> findall();
}
UserDao.java
package cn.tedu.dao;

import cn.tedu.bean.User;
import cn.tedu.utils.JDBCUtils;

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

public class UserDao implements BaseDao<User>{
    JDBCUtils jdb = new JDBCUtils();

    @Override
    public boolean add(User user) {
        Connection con = null;
        PreparedStatement stat = null;
        int i = 0;
        try{
            con = JDBCUtils.getConnection();
            stat = con.prepareStatement("INSERT INTO student VALUES(?,?,?)");
            System.out.println(user.getUsername());
            System.out.println(user.getPassword());
            stat.setString(1,null);
            stat.setString(2, user.getUsername());
            stat.setString(3, user.getPassword());
            i = stat.executeUpdate();
            System.out.println(i);

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            JDBCUtils.close(con, stat);
        }
        if(i>0){
            return true;
        }else {
            return false;
        }
    }

    @Override
    public void delete(User user) {
        Connection con = null;
        Statement stat = null;
        try{
            con = JDBCUtils.getConnection();
            stat = con.createStatement();
            String sql = "DELETE FROM user WHERE id='"+user.getId()+"'";
            stat.executeUpdate(sql);

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            JDBCUtils.close(con, stat);
        }
    }

    @Override
    public void update(User o) {

    }

    @Override
    public boolean findbone(String username, String password) {
        Connection con = null;
        PreparedStatement stat = null;
        ResultSet rs = null;
        boolean result = false;
        try {
            con = JDBCUtils.getConnection();
            stat = con.prepareStatement("SELECT *FROM student WHERE username = ? and password = ?");
            stat.setString(1, username);
            stat.setString(2, password);
            rs = stat.executeQuery();
            if (rs.next()) {
                result =  true;
            } else {
                result = false;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.close(con, stat, rs);
        }
        return result;
    }

    @Override
    public List findall() {
        Connection con = null;
        Statement stat = null;
        ResultSet rs = null;
        ArrayList<User> list = new ArrayList<User>();
        try{
            con = JDBCUtils.getConnection();
            stat = con.createStatement();
            String sql = "SELECT *FROM student";
            rs = stat.executeQuery(sql);

            while(rs.next()){
                int id = rs.getInt("id");
                String name = rs.getString("name");
                User user = new User(id, name,null);
                list.add(user);
            }

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            JDBCUtils.close(con, stat, rs);
        }
        return list;
    }
}
RegisterServlet.java
package cn.tedu.servlet;

import cn.tedu.bean.User;
import cn.tedu.dao.UserDao;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet(name = "RegisterServlet", value = "/RegisterServlet")
public class RegisterServlet extends HttpServlet {
    UserDao userDao = new UserDao();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        System.out.println(username);
        System.out.println(password);
        User user = new User(null,username,password);
        System.out.println(user);
        System.out.println(user.getUsername());
        System.out.println(user.getPassword());
        if(userDao.add(user)){
            response.sendRedirect(request.getContextPath()+"/success.jsp");
            System.out.println("用户注册成功");
        }else{
            response.sendRedirect(request.getContextPath()+"/error.jsp");
            System.out.println("用户注册失败");
        }
    }
}


四、登录

login.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>登录</title>
</head>
<body>

<%--<link rel="stylesheet" type="text/css" href="./homepage.css">--%>
<div style="text-align: center">
    <form action="LoginServlet" method="post" id="loginform">
        账号:<input type="text" placeholder="手机号或邮箱" name="username"/><br>
        密码:<input type="password" placeholder="密码" name="password"/><br>
        <input type="submit" class="inputButton" value="登录" />
        <a href="register.jsp">没有账号,点击注册</a>
    </form>
</div>


</body>

</html>
LoginServlet.java
package cn.tedu.servlet;

import cn.tedu.dao.UserDao;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet(name = "LoginServlet", value = "/LoginServlet")
public class LoginServlet extends HttpServlet {
    UserDao userDao = new UserDao();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        System.out.println(password);
        System.out.println(username);
        if(userDao.findbone(username,password)){
            response.sendRedirect(request.getContextPath()+"/success.jsp");

        }else{
           response.sendRedirect(request.getContextPath()+"/error.jsp");
        }
    }
}


你可能感兴趣的:(JAVAWEB应用开发,servlet)