在netbeans 8示例DB中的jsp servlet中自动生成ID

时间:2014-10-03 04:10:22

标签: jsp servlets netbeans-8

AdminDao.java

package com.ydp.dao;

import com.ydp.encapsulation.Admin;
import java.sql.SQLException;
import java.util.List;

 public interface AdminDao {

    public void createAdmin(Admin admin) throws SQLException;

    public List<Admin> getAllAdmin()throws SQLException;

    public Admin getAdmin(int adminID)throws SQLException;

    public void updateAdmin(Admin admin)throws SQLException;

    public void deleteAdmin (int adminID)throws SQLException;
}

AdminDaoImpl.java

package com.ydp.dao;

import com.ydp.encapsulation.Admin;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

public class AdminDaoImpl implements AdminDao {

    private Connection con;
    private PreparedStatement psm;
    private ResultSet rs;
    private List<Admin> admins = new ArrayList<>();

    public AdminDaoImpl() {
    }

    @Override
    public void createAdmin(Admin admin) throws SQLException {

        try {
            con = getAdminDS().getConnection();
        } catch (NamingException ex) {
            Logger.getLogger(AdminDaoImpl.class.getName()).log(Level.SEVERE, null, ex);
        }


        String insert = "INSERT INTO ADMIN(NAME,PASSWORD,GMAIL)VALUES(?,?,?)";
        psm = con.prepareStatement(insert);
        psm.setString(2, admin.getName());
        psm.setString(3, admin.getPassword());
        psm.setString(4, admin.getGmail());
        psm.executeUpdate();
        con.close();
    }

    @Override
    public List<Admin> getAllAdmin() throws SQLException {
        String findAll = "SELECT * FROM ADMIN";
        psm = con.prepareStatement(findAll);
        rs = psm.executeQuery();
        while (rs.next()) {
            Admin admin = new Admin();
            admin.setAdminID(rs.getInt("ADMIN_ID"));
            admin.setName(rs.getString("NAME"));
            admin.setPassword(rs.getString("PASSWROD"));
            admin.setGmail(rs.getString("GMAIL"));
            admins.add(admin);
        }
        return admins;
    }

    @Override
    public Admin getAdmin(int adminID) throws SQLException {
        String findByID = "SELECT * FROM ADMIN WHERE ADMIN_ID=?";
        psm = con.prepareStatement(findByID);
        rs = psm.executeQuery();
        Admin admin = new Admin();
        while (rs.next()) {
            admin.setAdminID(rs.getInt("ADMIN_ID"));
            admin.setName(rs.getString("NAME"));
            admin.setPassword(rs.getString("PASSWROD"));
            admin.setGmail(rs.getString("GMAIL"));
        }
        return admin;
    }

    @Override
    public void updateAdmin(Admin admin) throws SQLException {
        String update = "UPDATE ADMIN SET NAME=? WHERE ADMIN_ID=?";
        psm = con.prepareStatement(update);
        psm.setString(1, admin.getName());
        psm.setInt(2, admin.getAdminID());
        psm.executeUpdate();
        con.close();
    }

    @Override
    public void deleteAdmin(int adminID) throws SQLException {
        String delete = "DELETE FROM ADMIN WHERE ADMIN_ID=?";
        psm = con.prepareStatement(delete);
        psm.setInt(1, adminID);
        psm.executeUpdate();
        con.close();
    }

    private DataSource getAdminDS() throws NamingException {
        Context c = new InitialContext();
        return (DataSource) c.lookup("java:comp/env/adminDS");
    }

}

AdminRegister.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title> Admin | Register </title>
        <link href="css/bootstrap-responsive.css" rel="stylesheet" type="text/css"/>
        <link href="css/bootstrap.css" rel="stylesheet" type="text/css"/>
        <script language="javascript">
            function validateForm()
            {

                var n = document.forms["formregister"]["txtname"].value;
                if (n == null || n == "")
                {
                    alert("please Enter Admin Name ");
                    return false;
                }
                var pa = document.forms["formregister"]["txtpassword"].value;
                if (pa == null || pa == "")
                {
                    alert("please Enter Password");
                    return false;
                }
                var e = document.forms["formregister"]["txtgmail"].value;
                if (e == null || e == "")
                {
                    alert("please Enter Gmail");
                    return false;
                } else {
                    var mailformat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
                    if (e.match(mailformat))
                    {
                        document.RForm.Email.focus();
                        //return true;
                    }
                    else
                    {
                        alert("please Enter Correct Gmail");
                        document.RForm.Email.focus();
                        return false;
                    }
                }

            }
        </script>
    </head>
    <body>  
        <br/>
        <div class="container">
            <div class="row">
                <div class="span5 offset3 well">
                    <legend>Admin Register လုပ္ရန္</legend>

                    <form name="formregister" method="POST" action="AdminRegisterServlet" accept-charset="UTF-8" onSubmit="return validateForm();">
                        <table>
                            <tr>
                                <td width="35%"><label>Admin Name:</label></td>
                                <td><input type="text" name="txtname"/></td>
                            </tr>

                            <tr>
                                <td width="35%"><label>Password:</label></td>
                                <td><input type="password" name="txtpassword" ></td>
                            </tr>

                            <tr>
                                <td width="35%"><label>Gmail:</label></td>
                                <td><input type="text" name="txtgmail" /></td>
                            </tr>

                            <tr>
                                <td width="35%"></td>
                                <td><button type="submit" class="btn btn-success " name="btnsubmit" value="Submit" >Register !</button></td>
                            </tr>
                        </table>
                    </form>

                </div>
            </div>
        </div>

    </body>  
</html>

AdminRegisterServlet.java

package com.ydp.servlet;

import com.ydp.dao.AdminDao;
import com.ydp.dao.AdminDaoImpl;
import com.ydp.encapsulation.Admin;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Resource;
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 javax.sql.DataSource;

@WebServlet(name = "AdminRegisterServlet", urlPatterns = {"/AdminRegisterServlet"})
public class AdminRegisterServlet extends HttpServlet {

    @Resource(name = "adminRegisterDS")
    private DataSource adminRegisterDS;
    private Connection conn;
    private PreparedStatement psm;
    private ResultSet rs;

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");

        Integer id = Integer.parseInt(request.getParameter("txtid"));
        String n = request.getParameter("txtname");
        String p = request.getParameter("txtpassword");
        String g = request.getParameter("txtgmail");

        Admin ad = new Admin(1, n, p, g);
        AdminDao adm = new AdminDaoImpl();
        try {
            adm.createAdmin(ad);
        } catch (SQLException ex) {
            Logger.getLogger(AdminRegisterServlet.class.getName()).log(Level.SEVERE, null, ex);
        }

    }


}

Admin.java

package com.ydp.encapsulation;

import java.io.Serializable; import java.util.Objects;

public class Admin implements Serializable{ private Integer adminID; private String name; private String password; private String gmail;

public Admin() {
}

public Admin(Integer adminID, String name, String password, String gmail) {
    this.adminID = adminID;
    this.name = name;
    this.password = password;
    this.gmail = gmail;
}

public Integer getAdminID() {
    return adminID;
}

public String getName() {
    return name;
}

public String getPassword() {
    return password;
}

public String getGmail() {
    return gmail;
}

public void setAdminID(Integer adminID) {
    this.adminID = adminID;
}

public void setName(String name) {
    this.name = name;
}

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

public void setGmail(String gmail) {
    this.gmail = gmail;
}

@Override
public int hashCode() {
    int hash = 3;
    hash = 29 * hash + Objects.hashCode(this.adminID);
    hash = 29 * hash + Objects.hashCode(this.name);
    hash = 29 * hash + Objects.hashCode(this.password);
    hash = 29 * hash + Objects.hashCode(this.gmail);
    return hash;
}

@Override
public boolean equals(Object obj) {
    if (obj == null) {
        return false;
    }
    if (getClass() != obj.getClass()) {
        return false;
    }
    final Admin other = (Admin) obj;
    if (!Objects.equals(this.adminID, other.adminID)) {
        return false;
    }
    if (!Objects.equals(this.name, other.name)) {
        return false;
    }
    if (!Objects.equals(this.password, other.password)) {
        return false;
    }
    if (!Objects.equals(this.gmail, other.gmail)) {
        return false;
    }
    return true;
}

@Override
public String toString() {
    return "Admin{" + "adminID=" + adminID + ", name=" + name + ", password=" + password + ", gmail=" + gmail + '}';
}

在这种情况下,如何在netbeans示例数据库中自动生成ID?我正在使用java servlet,jsp页面,dao。请帮帮我!

1 个答案:

答案 0 :(得分:0)

假设您使用Oracle数据库。

oracle中无法使用自动增量功能。但如果你需要自动完成,你可以通过Sequence and trigger来实现它。

否则,如果您需要手动插入自动递增的ID,请创建Sequence并使用nextval

例如,

String insert = "INSERT INTO ADMIN(ID,NAME,PASSWORD,GMAIL)VALUES(seqName.nextval,?,?,?)";

如果是jdbc。

相反,如果您尝试使用mysql,请轻松实现this.

另请阅读此Why oracle does not have autoincrement feature for primary keys?

希望这有帮助!!