1. 程式人生 > >資料庫專案案例之---登入註冊和增刪改查

資料庫專案案例之---登入註冊和增刪改查

登入註冊和增刪改查

(一)功能

1.使用了普通的jdbc和資料庫連線池c3p0兩種技術

2.使用了三層架構dao層(資料訪問層),service層(業務邏輯層)和servlet層(請求控制層)

3.實現了增刪改查和登入註冊技術

(二)頁面展示

1.登入頁面

 

2.註冊頁面

 

3.登入成功頁面

 

4.登入失敗頁面

 

5.修改頁面

 

6.修改成功頁面

 

7.刪除成功頁面

 

(三)程式碼展示

 

 

(1)entity

1.User.java

package entity;

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

    public int getId() {
        return id;
    }

    public void setId(int 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 + '\'' +
                '}';
    }
}

 

(2)util

1.JDBCUtils.java   普通jdbc

package util;



import com.mchange.v2.c3p0.ComboPooledDataSource;



import java.io.IOException;

import java.io.InputStream;

import java.sql.*;

import java.util.Properties;



public class JDBCUtils {

    private static final String driverClass;

    private static final String url;

    private static final String username;

    private static final String password;



    static{



        driverClass ="com.mysql.jdbc.Driver";

        url ="jdbc:mysql://localhost:3306/zml";

        username ="root";

        password = "root";

    }



    /**

     * 註冊驅動的方法

     * @throws ClassNotFoundException

     */

    public static void loadDriver() throws ClassNotFoundException{

        Class.forName(driverClass);

    }



    /**

     * 獲得連線的方法:

     * @throws SQLException

     */

    public static Connection getConnection() throws Exception{

        loadDriver();

        Connection conn = DriverManager.getConnection(url, username, password);

        return conn;

    }



    /**

     * 資源釋放

     */

    public static void release(Statement stmt,Connection conn){

        if(stmt != null){

            try {

                stmt.close();

            } catch (SQLException e) {

                e.printStackTrace();

            }

            stmt = null;

        }

        if(conn != null){

            try {

                conn.close();

            } catch (SQLException e) {

                e.printStackTrace();

            }

            conn = null;

        }

    }



    public static void release(ResultSet rs,Statement stmt,Connection conn){

        if(rs!= null){

            try {

                rs.close();

            } catch (SQLException e) {

                e.printStackTrace();

            }

            rs = null;

        }

        if(stmt != null){

            try {

                stmt.close();

            } catch (SQLException e) {

                e.printStackTrace();

            }

            stmt = null;

        }

        if(conn != null){

            try {

                conn.close();

            } catch (SQLException e) {

                e.printStackTrace();

            }

            conn = null;

        }

    }

}

 

2.JDBCUtils2.java     資料連線池c3p0

package util;



import com.mchange.v2.c3p0.ComboPooledDataSource;



import javax.sql.DataSource;

import java.beans.PropertyVetoException;

import java.sql.Connection;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Statement;



/**

 * 資料連線池c3p0

 */

public class JDBCUtils2 {

    private static final ComboPooledDataSource dataSource = new ComboPooledDataSource();

    static{

        try {

            dataSource.setDriverClass("com.mysql.jdbc.Driver");

            dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/zml");

            dataSource.setUser("root");

            dataSource.setPassword("root");

        } catch (PropertyVetoException e) {

            e.printStackTrace();

        }

    }





    /**

     * 獲得連線的方法:

     * @throws SQLException

     */

    public static Connection getConnection() throws Exception{

        Connection conn = dataSource.getConnection();

        return conn;

    }



    /**

     * 資源釋放

     */

    public static void release(Statement stmt, Connection conn){

        if(stmt != null){

            try {

                stmt.close();

            } catch (SQLException e) {

                e.printStackTrace();

            }

            stmt = null;

        }

        if(conn != null){

            try {

                conn.close();

            } catch (SQLException e) {

                e.printStackTrace();

            }

            conn = null;

        }

    }



    public static void release(ResultSet rs, Statement stmt, Connection conn){

        if(rs!= null){

            try {

                rs.close();

            } catch (SQLException e) {

                e.printStackTrace();

            }

            rs = null;

        }

        if(stmt != null){

            try {

                stmt.close();

            } catch (SQLException e) {

                e.printStackTrace();

            }

            stmt = null;

        }

        if(conn != null){

            try {

                conn.close();

            } catch (SQLException e) {

                e.printStackTrace();

            }

            conn = null;

        }

    }

}

 

(3)dao

1.LoginDao.java

package dao;

import util.JDBCUtils;
import util.JDBCUtils2;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class LoginDao {
    public boolean getLogin(String username,String password){
        Connection conn=null;
        PreparedStatement pstmt=null;
        ResultSet rs=null;
        boolean flag=false;
        try{
            //獲得連線
           
conn = JDBCUtils2.getConnection();
            //編寫sql
           
String sql="select password from user where username=? and password=?";
            //預編譯sql
           
pstmt=conn.prepareCall(sql);
            pstmt.setString(1,username);
            pstmt.setString(2,password);
            //設定引數
           
//執行sql
           
rs=pstmt.executeQuery();
            if(rs.next()){
                flag=true;
            }else{
                flag=false;
            }

        }catch (Exception e){

        }finally {
            JDBCUtils2.release(rs,pstmt,conn);
        }
       return flag;
    }
}
package util;



import com.mchange.v2.c3p0.ComboPooledDataSource;



import javax.sql.DataSource;

import java.beans.PropertyVetoException;

import java.sql.Connection;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Statement;



/**

 * 資料連線池c3p0

 */

public class JDBCUtils2 {

    private static final ComboPooledDataSource dataSource = new ComboPooledDataSource();

    static{

        try {

            dataSource.setDriverClass("com.mysql.jdbc.Driver");

            dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/zml");

            dataSource.setUser("root");

            dataSource.setPassword("root");

        } catch (PropertyVetoException e) {

            e.printStackTrace();

        }

    }





    /**

     * 獲得連線的方法:

     * @throws SQLException

     */

    public static Connection getConnection() throws Exception{

        Connection conn = dataSource.getConnection();

        return conn;

    }



    /**

     * 資源釋放

     */

    public static void release(Statement stmt, Connection conn){

        if(stmt != null){

            try {

                stmt.close();

            } catch (SQLException e) {

                e.printStackTrace();

            }

            stmt = null;

        }

        if(conn != null){

            try {

                conn.close();

            } catch (SQLException e) {

                e.printStackTrace();

            }

            conn = null;

        }

    }



    public static void release(ResultSet rs, Statement stmt, Connection conn){

        if(rs!= null){

            try {

                rs.close();

            } catch (SQLException e) {

                e.printStackTrace();

            }

            rs = null;

        }

        if(stmt != null){

            try {

                stmt.close();

            } catch (SQLException e) {

                e.printStackTrace();

            }

            stmt = null;

        }

        if(conn != null){

            try {

                conn.close();

            } catch (SQLException e) {

                e.printStackTrace();

            }

            conn = null;

        }

    }

}

 

2.RegisterDao.java

package dao;



import entity.User;

import util.JDBCUtils;

import util.JDBCUtils2;



import java.sql.Connection;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.util.ArrayList;

import java.util.List;



public class RegisterDao {

    public int getinsert(String username,String password){

        Connection conn=null;

        PreparedStatement pstmt=null;

        int num=0;

        try {



            //獲得連線

            conn = JDBCUtils2.getConnection();

            //編寫sql

            String sql="insert into user values(null,?,?)";

            //預編譯sql

            pstmt=conn.prepareCall(sql);

            pstmt.setString(1,username);

            pstmt.setString(2,password);

            //設定引數

            //執行sql

             num=pstmt.executeUpdate();



        } catch (Exception e) {

            e.printStackTrace();



        }finally {

            JDBCUtils2.release(pstmt,conn);

        }

       return num;

    }

}

 

3.UserDao.java

package dao;



import com.mchange.v2.c3p0.ComboPooledDataSource;

import entity.User;

import util.JDBCUtils;

import util.JDBCUtils2;



import java.sql.Connection;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.util.ArrayList;

import java.util.List;



public class UserDao {

    public List<User> getSelect(){

        Connection conn=null;

        PreparedStatement pstmt=null;

        ResultSet rs=null;

        List<User> user=new ArrayList<User>();

        User a=null;

        try {



            //獲得連線

            conn = JDBCUtils2.getConnection();

            //編寫sql

            String sql="select * from user";

            //預編譯sql

            pstmt=conn.prepareCall(sql);

            //設定引數

            //執行sql

            rs=pstmt.executeQuery();



            while(rs.next()){

                a=new User();

                a.setId(rs.getInt(1));

                a.setUsername(rs.getString(2));

                a.setPassword(rs.getString(3));

                user.add(a);



            }

        } catch (Exception e) {

            e.printStackTrace();



        }finally {

            JDBCUtils.release(rs,pstmt,conn);

        }

        return user;

    }

}

 

4.UpdateDao.java

package dao;



import entity.User;

import util.JDBCUtils2;



import java.sql.Connection;

import java.sql.PreparedStatement;



public class UpdateDao {

    public int getUpdate(User user){

        Connection conn=null;

        PreparedStatement pstmt=null;

        int num=0;

        try {



            //獲得連線

            conn = JDBCUtils2.getConnection();

            //編寫sql

            String sql="update user set username=?,password=? where id=?";

            //預編譯sql

            pstmt=conn.prepareCall(sql);

            pstmt.setString(1,user.getUsername());

            pstmt.setString(2,user.getPassword());

            pstmt.setInt(3,user.getId());

            //設定引數

            //執行sql

            num=pstmt.executeUpdate();



        } catch (Exception e) {

            e.printStackTrace();



        }finally {

            JDBCUtils2.release(pstmt,conn);

        }

        return num;

    }

}

 

5.DeleteDao.java

package dao;



import util.JDBCUtils2;



import java.sql.Connection;

import java.sql.PreparedStatement;



public class DeleteDao {

    public int getDelete(int id){

        Connection conn=null;

        PreparedStatement pstmt=null;

        int num=0;

        try {



            //獲得連線

            conn = JDBCUtils2.getConnection();

            //編寫sql

            String sql="delete from user where id=?";

            //預編譯sql

            pstmt=conn.prepareCall(sql);

            pstmt.setInt(1,id);

            //設定引數

            //執行sql

            num=pstmt.executeUpdate();



        } catch (Exception e) {

            e.printStackTrace();



        }finally {

            JDBCUtils2.release(pstmt,conn);

        }

        return num;

    }

}

 

(4)service

1.UserService.java

package service;



import dao.*;

import entity.User;



import java.util.List;



public class UserService {

    public List<User> getServlet(){

        return new UserDao().getSelect();

    }

    public boolean getLogin(String username,String password){

        return new LoginDao().getLogin(username,password);

    }

    public int getinsert(String username,String password){

        return new RegisterDao().getinsert(username,password);

    }

    public int getUpdate(User user){

        return new UpdateDao().getUpdate(user);

    }

    public int getDelete(int id){

        return new DeleteDao().getDelete(id);

    }

}

 

(5)servlet

1.LoginServlet.java

package servlet;



import service.UserService;



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;



@WebServlet("/LoginServlet")

public class LoginServlet extends HttpServlet {

    @Override

    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        req.setCharacterEncoding("UTF-8");



        String username=req.getParameter("username");

        String password=req.getParameter("password");

        UserService log=new UserService();

        boolean pwd=log.getLogin(username,password);

        System.out.println(password+"   "+pwd);

        if(pwd==true){

            req.getRequestDispatcher("UserServlet").forward(req,resp);

        }else{

            req.getRequestDispatcher("error.jsp").forward(req,resp);

        }

    }



    @Override

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

        doPost(req, resp);

    }

}

 

2.RegisterServlet.java

package servlet;



import service.UserService;



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;



@WebServlet("/RegisterServlet")

public class RegisterServlet extends HttpServlet {

    @Override

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

        doPost(req, resp);

    }



    @Override

    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        req.setCharacterEncoding("UTF-8");

        String username=req.getParameter("username");

        String password=req.getParameter("password");

        UserService u=new UserService();

        int num=u.getinsert(username,password);

        if(num>0){

           req.getRequestDispatcher("index.jsp").forward(req,resp);

        }else{

            req.getRequestDispatcher("register.jsp").forward(req,resp);

        }

    }

}

 

3.UserServlet.java

package servlet;



import entity.User;

import service.UserService;



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.util.List;



@WebServlet("/UserServlet")

public class UserServlet extends HttpServlet {

    @Override

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

        doPost(req, resp);

    }



    @Override

    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        UserService u=new UserService();

        List<User> user=u.getServlet();



        System.out.println("udrt"+user);

        for(User uu:user){

            System.out.println(uu.getId()+" "+uu.getUsername()+" "+uu.getPassword());

        }



        req.setAttribute("User",user);

        req.getRequestDispatcher("success.jsp").forward(req,resp);

    }

}

 

4.UpdateServlet.java

package servlet;



import dao.UserDao;

import entity.User;

import service.UserService;



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;



@WebServlet("/UpdateServlet")

public class UpdateServlet extends HttpServlet {

    @Override

    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        req.setCharacterEncoding("UTF-8");

         int id=Integer.decode(req.getParameter("id"));

         String username=req.getParameter("username");

         String password=req.getParameter("password");

         User user=new User();

         user.setId(id);

         user.setUsername(username);

         user.setPassword(password);

        UserService u=new UserService();

        int num=u.getUpdate(user);

        if(num>0){

            req.getRequestDispatcher("LoginServlet").forward(req,resp);

        }else{

            req.getRequestDispatcher("update.jsp").forward(req,resp);

        }



    }



    @Override

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

        doPost(req, resp);

    }

}

 

5.DeleteServlet.java

package servlet;



import service.UserService;



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;



@WebServlet("/DeleteServlet")

public class DeleteServlet extends HttpServlet {

    @Override

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

        doPost(req, resp);

    }



    @Override

    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        int id=Integer.decode(req.getParameter("id"));

        UserService u=new UserService();

        int num=u.getDelete(id);

        req.getRequestDispatcher("UserServlet").forward(req,resp);





    }

}

 

(6)webapp

1.index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<html>

<head>

    <title>Title</title>

</head>

<body>

<h2>登入</h2><a href="register.jsp">註冊</a>

<form action="LoginServlet" method="post">

    使用者名稱:<input type="text" name="username">

    密碼:<input type="text" name="password">

    <input type="submit" value="確定"/>

</form>

</body>

</html>

 

2.register.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<html>

<head>

    <title>Title</title>

</head>

<body>

<h2>註冊</h2><a href="index.jsp"></a>

<form action="RegisterServlet" method="post">

    使用者名稱:<input type="text" name="username">

    密碼: <input type="text" name="password">

    <input type="submit" >

</form>



</body>

</html>

 

3.success.jsp

<%@ page import="entity.User" %>

<%@ page import="java.util.List" %>

<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<html>

<head>

    <title>Title</title>

</head>

<body>

<table>

    <tr>

        <td>id</td>

        <td>使用者名稱</td>

        <td>密碼</td>

        <td>修改</td>

        <td>刪除</td>

    </tr>

    <%

        List<User> us=(List<User>)request.getAttribute("User");

        for(User u:us){%>

            <tr>

                <td><%=u.getId()%></td>

                <td><%=u.getUsername()%></td>

                <td><%=u.getPassword()%></td>

                <td><a href="update.jsp?id=<%=u.getId()%>&&username=<%=u.getUsername()%>&&password=<%=u.getPassword()%>">修改</a></td>

                <td><a href="DeleteServlet?id=<%=u.getId()%>">刪除</a> </td>

            </tr>

        <%}%>

</table>

</body>

</html>

 

4.error.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<html>

<head>

    <title>Title</title>

</head>

<body>

賬戶名或密碼錯誤!

</body>

</html>

 

5.update.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<html>

<head>

    <title>Title</title>

</head>

<body>

<form action="UpdateServlet" method="post">

    <table>

        <tr>

            <td>id</td>

            <td><input type="text" name="id" value="<%=request.getParameter("id")%>"></td>

        </tr>

        <tr>

            <td>使用者名稱</td>

            <td><input type="text" name="username" value="<%=request.getParameter("username")%>"></td>

        </tr>

        <tr>

            <td>密碼</td>

            <td><input type="text" name="password" value="<%=request.getParameter("password")%>"></td>

        </tr>

    </table>

    <input type="submit">

</form>

</body>

</html>

 

(7)pom.xml
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->

<dependency>

  <groupId>javax.servlet</groupId>

  <artifactId>javax.servlet-api</artifactId>

  <version>3.1.0</version>

  <scope>provided</scope>

</dependency>

<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->

<dependency>

  <groupId>org.springframework</groupId>

  <artifactId>spring-jdbc</artifactId>

  <version>5.1.5.RELEASE</version>

</dependency>

<!-- https://mvnrepository.com/artifact/com.mchange/c3p0 -->

<dependency>

  <groupId>com.mchange</groupId>

  <artifactId>c3p0</artifactId>

  <version>0.9.5.2</version>

</dependency>

<!-- https://mvnrepository.com/artifact/org.apache.tomcat/tomcat-jdbc -->

<dependency>



  <groupId>mysql</groupId>



  <artifactId>mysql-connector-java</artifactId>



  <version>5.1.25</version>



</dependency>

&n