Below is my doGet
method
@WebServlet(
name = "IndexServlet",
urlPatterns={ "/", "/home" },
initParams = { @WebInitParam(name = "sortBy", value = Constants.POPULAR) }
)
public class IndexServlet extends HttpServlet {
private DataSource pool;
@Override
public void init() throws ServletException {
String datasource_name = "jdbc/bookhive_db";
try {
//A JNDI Initial context to be able to lookup the DataSource
InitialContext ctx = new InitialContext();
pool = (DataSource) ctx.lookup("java:comp/env/" + datasource_name);
if (pool == null)
throw new ServletException("Unknown DataSource '" + datasource_name + "'");
} catch (NamingException ex) {
ex.printStackTrace();
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int page;
try {
page = Integer.parseInt(request.getParameter("page"));
} catch (NumberFormatException e) {
page = 1;
}
String sortBy = request.getParameter("sortBy");
if (sortBy == null || sortBy.isEmpty())
sortBy = this.getInitParameter("sortBy");
String query = getQuery(sortBy);
Object[] params = {
(page - 1) * Constants.RESULTS_PER_PAGE,
Constants.RESULTS_PER_PAGE
};
JDBCService service = new JDBCService(pool);
service.setQuery(query);
service.setParams(params);
List<Book> books = service.getBookDetails();
System.out.println("HELLO");
RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/index.jsp");
dispatcher.forward(request, response);
}
}
When I start the server (Tomcat), it opens http://localhost:8080
in browser and the doGet
method gets called 3 times. It prints 'Hello' 3 times.
This only happen when I first start the server.
Any idea why this happens?