I tried out DAO Pattern after reading http://java.sun.com/blueprints/corej2eepatterns/Patterns/DataAccessObject.html but I get NullPointerException when I run the servlet
<>DAOFactory
package dao;
import java.sql.SQLException;
public abstract class DAOFactory {
// List of DAO types supported by the factory
public static final int MYSQL = 1;
public abstract UserDAO getUserDAO() throws SQLException;
public static DAOFactory getDAOFactory(int whichFactory) {
switch (whichFactory) {
case MYSQL:
return new MySQLDAOFactory();
default :
return null;
}
}
}
<><>MySQLDAOFactory
package dao;
import java.sql.*;
public class MySQLDAOFactory extends DAOFactory {
public MySQLDAOFactory() {
}
public static final String DRIVER="com.mysql.jdbc.Driver";
public static final String DBURL="jdbc:mysql://localhost:3306/musicompany";
public static Connection createConnection() {
Connection conn=null;
try{
Class.forName(DRIVER);
conn = DriverManager.getConnection(DBURL,"root","toor");
}catch(Exception e){}
return conn;
}
public UserDAO getUserDAO() throws SQLException{
return new MySQLUserDAO();
}
}
<<>MySQLUserDAO>
package dao;
import java.sql.*;
import java.util.ArrayList;
import model.User;
public class MySQLUserDAO implements UserDAO {
Connection conn=null;
Statement s=null;
public MySQLUserDAO() throws SQLException{
conn = MySQLDAOFactory.createConnection();
s = conn.createStatement();
}
public int insertUser(String fname, String lname)
{
try{
//code to insertUser
}catch(Exception e){}
return key;
}
public ArrayList<User> selectUsers() {
ResultSet rs=null;
ArrayList customerList=null;
try{
rs =s.executeQuery("select * from users");
customerList = new ArrayList<User>();
while(rs.next())
{
customerList.add(new User(rs.getString("name"), rs.getString("pass"), rs.getInt("type"), rs.getString("email")));
}
return customerList;
}catch(Exception e){}
return customerList;
}
}
UserDAO
package dao;
import java.util.ArrayList;
import model.User;
public interface UserDAO {
public int insertUser(String fname, String lname);
public ArrayList<User> selectUsers();
}
model.User.java
这一类有以下领域和相应的准入方法。
String name;
String pass;
short type;
String email;
http://www.ohchr.org。
public class AddRetrieve extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException{
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
// create the required DAO Factory
DAOFactory factoryObj = DAOFactory.getDAOFactory(DAOFactory.MYSQL);
// Create a DAO
UserDAO custDAO = factoryObj.getUserDAO();
// print existing users
ArrayList list = custDAO.selectUsers();
Iterator i = list.iterator();
while(i.hasNext())
{
User o = (User)i.next();
out.println(o.getName());
}
} catch(Exception e)
{
out.println(e);
}
finally {
out.close();
}
}