1. 程式人生 > >java建立簡單註冊登入網頁

java建立簡單註冊登入網頁

1.配置環境

做這次的小專案使用到的語言是java,當然eclipse是必不可少的,另外還需要用到的有Tomcat,MySQL,mysql-connector-java的bin包和Navicat。其實Navicat可以不裝,但是為了更方便看到我們的資料庫,還是建議裝一下。這裡介紹一下Tomcat和mysql-connector-java的bin包的配置。
  • Tomcat的配置
    這裡為了防止Tomcat出錯,安裝的是8.3版本的,先開啟Preferences,然後執行如下操作
    步驟1
    然後找到Tomcat的資料夾,最後Finish
    步驟2
  • mysql-connector-java的bin包的配置
    將mysql-connector-java的bin包拖到lib資料夾下,並右鍵build Path

2.大致框架的建立

我們首先建立了一個Dynamic Web Project,隨後在這個java專案中建立了兩個Source Folder,一個是預設的src,另一個是我們的測試程式碼。
在src中,我們建立四個包
- controller:放置控制servlet的class
- dao:放置控制資料庫的class,其中還包含了imp包,裡面放置dao的實現類
- entity:放置使用者的實體類
- utils:放置工具類
建立完成後,檢視應該是這樣的
檢視

然後我們需要在entity包中寫一個使用者的實體類
需要提供的屬性有id,userName,nickName,password,birth,imgs,gender,favorite,同時需要提供相應的get和set方法。無參的構造方法,全參的構造方法,無id的構造方法。


public class User {
    private int id;
    private String userName;
    private String nickName;
    private String password;
    private Date birth;
    private String imgs;
    private char gender;
    private String favorite;
    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 getNickName() { return nickName; } public void setNickName(String nickName) { this.nickName = nickName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Date getBirth() { return birth; } public void setBirth(Date birth) { this.birth = birth; } public String getImgs() { return imgs; } public void setImgs(String imgs) { this.imgs = imgs; } public char getGender() { return gender; } public void setGender(char gender) { this.gender = gender; } public String getFavorite() { return favorite; } public void setFavorite(String favorite) { this.favorite = favorite; } public User(int id, String userName, String nickName, String password, Date birth, String imgs, char gender, String favorite) { super(); this.id = id; this.userName = userName; this.nickName = nickName; this.password = password; this.birth = birth; this.imgs = imgs; this.gender = gender; this.favorite = favorite; } @Override public String toString() { return "User [id=" + id + ", userName=" + userName + ", nickName=" + nickName + ", password=" + password + ", birth=" + birth + ", imgs=" + imgs + ", gender=" + gender + ", favorite=" + favorite + "]"; } public User() { super(); } public User(String userName, String nickName, String password, Date birth, String imgs, char gender, String favorite) { super(); this.userName = userName; this.nickName = nickName; this.password = password; this.birth = birth; this.imgs = imgs; this.gender = gender; this.favorite = favorite; } }

隨後我們應該寫的是dao包中的介面,這些介面是整個專案的靈魂。
在這個介面中,我們需要實現的功能有

  • 往資料庫中新增使用者
  • 通過使用者名稱和密碼查詢使用者,並返回這個使用者
  • 返回一個包含所有使用者的List
  • 通過id查詢使用者,並返回這個使用者
public interface UserDao {
    public int insert(User user);
    public User select(int id);
    public User select(String userName, String password);
    public List<User> select();
}

3.Utils類的實現

Utils類中需要實現的方法有:

  • 實現連線資料庫
  • 獲取Connection
  • 釋放記憶體
  • 通過forName來載入Driver驅動

public class DBUtil {
    private static final String url = "jdbc:mysql:///test";
    private static final String user = "root";
    private static final String password = "root";

    static {
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public static Connection getConnection() {
        Connection conn = null;
        try {
            conn = DriverManager.getConnection(url, user, password);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }
    public static void free(Connection conn , Statement stmt, ResultSet rs){
        try {
            if(rs != null)
                rs.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally{
            try {
                if(stmt != null)
                    stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }finally{
                try {
                    if(conn != null)
                        conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}

4.Dao介面的實現

  1. 首先我們先實現插入功能

,步驟如下:
(1).通過Utils工具類建立連線
(2).通過Connection連線建立statement物件
(3).通過statement物件呼叫SQL語句
注意:呼叫SQL語句時,Date不能直接插入,需要用simpledateformat來格式化字串
程式碼如下:

@Override
    public int insert(User user) {
        Connection conn = DBUtils.getConnection();
        Statement stmt = null;
        SimpleDateFormat sim = new SimpleDateFormat("yyyy-MM-dd");
        try {
            stmt = conn.createStatement();
        } catch (SQLException e1) {
            e1.printStackTrace();
        }
        String sql = "insert into tb_user(id, username, nickname, password, birth, imgs, gender, favorite) "
                + "values("
                + user.getId()
                + ", '"
                + user.getUserName()
                + "', '"
                + user.getNickName()
                + "', '"
                + user.getPassword()
                + "', '"
                + sim.format(user.getBirth())
                + "', '"
                +user.getImgs()
                + "', '"
                + user.getGender()
                + "', '"
                + user.getFavorite() + "')";
        try {
            stmt.execute(sql);
        } catch (SQLException e) {
            e.printStackTrace();
        }

        DBUtils.free(conn, stmt, null);
        return 0;
    }

2 . 實現查詢所有使用者的介面,步驟如下:
(1).通過Utils工具類建立連線
(2).通過Connection連線建立statement物件
(3).建立List用於儲存查詢到的所有的使用者
(4).使用statemrnt物件中的executeQuery()呼叫SQL語句,並返回一個ResultSet物件用於遍歷所有使用者
(5).將遍歷到的所有的使用者儲存到list中,並返回這個List
程式碼如下

@Override
    public List<User> select() throws SQLException {
        Connection conn = DBUtil.getConnection();
        Statement state = conn.createStatement();
        ArrayList<User> list = new ArrayList<>();
        String sql = "select * from tb_user";
        ResultSet rs = state.executeQuery(sql);
        while(rs.next()){
            User user = new User();

            int id = rs.getInt("id");
            user.setId(id);

            String username = rs.getString("username");
            if (username != null)
                user.setUserName(username);

            String nickname = rs.getString("nickname");
            if (nickname != null)
                user.setNickName(nickname);

            String pwd = rs.getString("password");
            if (pwd != null)
                user.setPassword(pwd);

            Date birth = rs.getDate("birth");
            if (birth != null)
                user.setBirth(birth);

            String imgs = rs.getString("imgs");
            if (imgs != null)
                user.setImgs(imgs);

            String genderStr = rs.getString("gender");
            if (genderStr != null && genderStr.length() > 0) {
                char gender = genderStr.charAt(0);
                user.setGender(gender);
            }

            String favorite = rs.getString("favorite");
            if(favorite != null)
                user.setFavorite(favorite);

            list.add(user);
        }
        return list;
    }

3 . 實現通過id查詢使用者
(1).通過Utils工具類建立連線
(2).通過Connection連線建立statement物件
(3).使用statemrnt物件中的executeQuery()呼叫SQL語句,並返回一個符合條件的ResultSet物件
(4).利用這個ResultSet物件將查詢到的使用者返回
程式碼如下:

    @Override
    public User select(int id) throws SQLException {
        Connection conn = DBUtil.getConnection();
        Statement state = conn.createStatement();
        String sql = "select * from tb_user " + "where id='" + id +"' ";
        ResultSet rs = state.executeQuery(sql);
        User user = new User();

        if (rs.next()) {
            user = new User();

            int aid = rs.getInt("id");
            user.setId(aid);

            String username = rs.getString("username");
            if (username != null)
                user.setUserName(username);

            String nickname = rs.getString("nickname");
            if (nickname != null)
                user.setNickName(nickname);

            String pwd = rs.getString("password");
            if (pwd != null)
                user.setPassword(pwd);

            Date birth = rs.getDate("birth");
            if (birth != null)
                user.setBirth(birth);

            String imgs = rs.getString("imgs");
            if (imgs != null)
                user.setImgs(imgs);

            String genderStr = rs.getString("gender");
            if (genderStr != null && genderStr.length() > 0) {
                char gender = genderStr.charAt(0);
                user.setGender(gender);
            }

            String favorite = rs.getString("favorite");
            if(favorite != null)
                user.setFavorite(favorite);
        }

        return user;
    }

4.實現根據使用者名稱和密碼查詢使用者(其實和3差不多,只需要修改SQL語句就行了)
(1).通過Utils工具類建立連線
(2).通過Connection連線建立statement物件
(3).使用statemrnt物件中的executeQuery()呼叫SQL語句,並返回一個符合條件的ResultSet物件
(4).利用這個ResultSet物件將查詢到的使用者返回
程式碼如下:

@Override
    public User select(String userName, String password) throws SQLException {
        Connection conn = DBUtil.getConnection();
        Statement state = conn.createStatement();
        String sql = "select * from tb_user " + "where username='" + userName
                + "' and password='" + password + "'";
        ResultSet rs = state.executeQuery(sql);
        User user = null;

        if (rs.next()) {
            user = new User();

            int id = rs.getInt("id");
            user.setId(id);

            String username = rs.getString("username");
            if (username != null)
                user.setUserName(username);

            String nickname = rs.getString("nickname");
            if (nickname != null)
                user.setNickName(nickname);

            String pwd = rs.getString("password");
            if (pwd != null)
                user.setPassword(pwd);

            Date birth = rs.getDate("birth");
            if (birth != null)
                user.setBirth(birth);

            String imgs = rs.getString("imgs");
            if (imgs != null)
                user.setImgs(imgs);

            String genderStr = rs.getString("gender");
            if (genderStr != null && genderStr.length() > 0) {
                char gender = genderStr.charAt(0);
                user.setGender(gender);
            }

            String favorite = rs.getString("favorite");
            if(favorite != null)
                user.setFavorite(favorite);
        }

        return user;
    }

5.java和網頁的連線