A JSP should not open JDBC connections or execute SQL. Database work belongs in a repository called by a service or controller; the JSP receives only the rows or view model needed to render the response. This keeps credentials, transactions, and failure handling out of the presentation layer.
JSP files become fragile when they mix HTML, SQL, connection code, and error handling. Move SQL into DAO classes and call them from servlets or services.
Prepared statements protect SQL structure from user input. Connection pools avoid creating a new physical connection for every request.
Database values can still contain unsafe text. Escape output in JSP and paginate large result sets.
The controller obtains validated parameters, invokes a repository that uses a pooled DataSource and prepared statements, maps results to plain view data, then forwards. Every JDBC resource closes before rendering begins, so a slow client does not hold a database connection.
For writes, complete the transaction and redirect before rendering the next page. Use JSTL c:forEach and EL for rows, escape text, and paginate large results. A database failure should produce a controlled error view with a correlation ID rather than SQL text.
1. User submits search form.
2. Servlet validates filters.
3. DAO runs a prepared SELECT query.
4. Servlet stores results in request scope.
5. JSP renders escaped values in a table.
The servlet coordinates the request, while the DAO owns JDBC resources and the JSP only renders the result.
protected void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
String status = req.getParameter("status");
List<Order> orders = orderDao.findByStatus(status);
req.setAttribute("orders", orders);
req.getRequestDispatcher("/WEB-INF/orders.jsp").forward(req, res);
}
The JSP receives a List<Order>; it never opens a database connection.
Not in maintainable applications. Use a servlet/service/DAO flow and let JSP render results.
Practice, interview questions, and compiler links for JSP With Database.
Finish the concept here, then reinforce it with hands-on coding, interview prep, or a tool that matches the topic.
Explore 500+ free tutorials across 20+ languages and frameworks.
Fresh tutorials, interview guides, and coding practice in your inbox.