CS4025 Final Exam
public
class BookInfoHandlerBean implements SessionBean{
Connection dbcon = null;
public void ejbCreate() throws
EJBException {
DataSource ds = null;
String dbname =
"java:comp/env/jdbc/yourid";
try {
InitialContext ic = new InitialContext();
ds = (DataSource) ic.lookup(dbname);
} catch (Exception ex) {
throw new EJBException("Cannot get
Data Source:" + ex);
}
openDB(ds);
}
public Vector computeCategories()
throws EJBException {
String sql = "select distinct category
from books";
Vector categories = new Vector();
try {
if (dbcon != null) {
PreparedStatement pstmt =
dbcon.prepareStatement(sql);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
String category = rs.getString(1);
categories.addElement(category);
}
rs.close();
pstmt.close();
}
} catch (Exception ex) {
throw new EJBException("Cannot
execute SQL statement:" + ex);
}
return categories;
}
public void ejbRemove() {}
public void ejbActivate() {}
public void ejbPassivate() {}
public void setSessionContext(SessionContext
sc) {}
void closeDB() throws EJBException {
try {
dbcon.close();
dbcon
= null;
} catch (Exception ex) {
throw new EJBException("Cannot close
the database connection.");
}
}
void openDB(DataSource ds) throws
EJBException {
try {
dbcon = ds.getConnection();
} catch (Exception ex) {
throw new EJBException("Cannot
connect to database: " + ex);
}
}
}
public
class AccessCount extends HttpServlet {
HttpServletRequest request;
HttpServletResponse response;
public void doPost(HttpServletRequest
request,
HttpServletResponse response) throws
ServletException, IOException {
this.request = request; this.response =
response;
controller();
}
public void doGet(HttpServletRequest request,
HttpServletResponse response)throws
ServletException, IOException {
this.request = request; this.response =
response;
controller();
}
private void controller(){
//add your code here
generateCountPage(count, case);
}
private void generateCountPage(int
count, String case) {
response.setContentType("text/html");
try {
writer = response.getWriter();
} catch (Exception ex) {}
writer.println("<html><head>");
writer.println("<title>Access
Count</title></head> \n");
writer.println("<body>");
writer.println("This page has been
accessed" + count + " times ");
writer.println("in case: " + case
+ " <br />");
writer.println("<form><input
type=submit value=’Submit Again’>");
writer.println("</form></body></html>");
}
}