JSTL vs Scriptlets in Database Operations
When working with databases in JSP, developers can either use Scriptlets (Java code
directly) or JSTL (JSP Standard Tag Library). Below is a comparison of both approaches.
1. Scriptlet Style (Traditional JDBC in JSP)
<%@ page import="[Link].*" %>
<html>
<body>
<%
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
[Link]("[Link]");
conn = [Link]("jdbc:mysql://localhost:3306/testdb","root","");
stmt = [Link]();
rs = [Link]("SELECT id, name FROM students");
while([Link]()){
[Link]("<p>ID: " + [Link]("id") + " - Name: " + [Link]("name") + "</p>");
}
} catch(Exception e){
[Link]("Error: " + [Link]());
} finally {
if(rs!=null) [Link]();
if(stmt!=null) [Link]();
if(conn!=null) [Link]();
}
%>
</body>
</html>
2. JSTL Style (Using <sql:query>)
<%@ taglib uri="[Link] prefix="sql" %>
<%@ taglib uri="[Link] prefix="c" %>
<html>
<body>
<sql:setDataSource var="db" driver="[Link]"
url="jdbc:mysql://localhost:3306/testdb"
user="root" password=""/>
<sql:query dataSource="${db}" var="result">
SELECT id, name FROM students;
</sql:query>
<table border="1">
<tr><th>ID</th><th>Name</th></tr>
<c:forEach var="row" items="${[Link]}">
<tr>
<td>${[Link]}</td>
<td>${[Link]}</td>
</tr>
</c:forEach>
</table>
</body>
</html>
3. Side-by-Side Comparison
Feature Scriptlet (JDBC in JSP) JSTL (sql tag)
Code Style Java code in JSP using JDBC XML-like tags
Complexity Long try-catch, manual Simple and clean
connection handling
Readability Hard for beginners Easy to understand
Best Use Case Good for learning raw JDBC Good for demos/teaching
Enterprise Practice ❌ Not recommended ✅ Cleaner, but still DAO
preferred
4. Teaching Tip for Students
- Start with Scriptlet JDBC to show how messy it looks.
- Then show JSTL sql:query to demonstrate cleaner code.
- Finally, explain that in real enterprise projects, database logic should go into Servlets/DAO
layer, not directly in JSP.