日期:2014-05-18  浏览次数:20742 次

第一次发帖,一个关于servlet使用数据源的多线程安全性问题
public class UserDaoImpl implements UserDAO {
/** 日志实例 */
private Logger logger = Logger.getLogger("UserDaoImpl");
/** 数据源实例 */
private DataSource ds = null;

private static UserDaoImpl userDaoImpl = null;

public static UserDaoImpl getInstance() {

userDaoImpl = new UserDaoImpl();
return userDaoImpl;
}

private UserDaoImpl() {

initDataSource();
}

public void initDataSource() {

try {

Context initialContext = new InitialContext();
Context evoContext = (Context)initialContext.lookup("java:/comp/evo");
ds = (DataSource)evoContext.lookup("java/ums");
} catch (NamingException e) {

logger.log(Level.INFO, "数据源初始化失败!");
e.printStackTrace();
}
}

/////////////////////////////主要方法////////////////////////////////////////////

@Override
public boolean addUser(User user) {

Connection conn = null;
PreparedStatement preparedStatement = null;
ResultSet rs = null;
String sql = null;

int rowCount = -1; //数据库改变的行号,初始化为-1

try {
conn = ds.getConnection();

sql = "INSERT INTO userinfo VALUES(?, ?, ?, ?, ?)";

preparedStatement = conn.prepareStatement(sql);
preparedStatement.setString(1, user.getUserId());
preparedStatement.setString(2, user.getPassword());
preparedStatement.setString(3, user.getUserName());
preparedStatement.setString(4, user.getUserCode());
preparedStatement.setString(5, user.getEmail());

rowCount = preparedStatement.executeUpdate(sql);

preparedStatement.close();
preparedStatement = null;

conn.close();
conn = null;
} catch (SQLException e) {

logger.log(Level.INFO, "添加用户操作异常!");
e.printStackTrace();
} finally {

try {
if (rs != null) {

rs.close();
rs = null;
}
if (preparedStatement != null) {

preparedStatement.close();
preparedStatement = null;
}
if (conn != null) {

conn.close();
conn = null;
}
} catch (SQLException e) {

logger.log(Level.INFO, "数据库连接释放异常!");
e.printStackTrace();
}
}

if (rowCount == 0 || rowCount == -1) {

return false;
} else {

return true;
}
}

@Override
public List<User> findAll() {
.............(代码略,类似于adduser方法)


}

public boolean getUser(String userId) {

.............(代码略,类似于adduser方法)

}

servlet代码:

@SuppressWarnings("serial")
public class FrontController extends HttpServlet {

UserDAO userDao;

public void init() throws ServletException {

userDao = UserDaoImpl.getInstance();
}

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

System.out.println("get");

doPost(request, response); //将请求交由doPost()处理
}

public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

System.out.println("post");

String act