Manesh
Manesh

Reputation: 596

Other Statergies to implemment <sql:query>

I have been using JSTL to fetch values from my database and display it in my jsp page using a similar code as shown below.

<sql:setDataSource
var="myDS"
driver="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/mydb"
user="root" password="secret"
/>

<sql:query var="list_users" dataSource="${myDS}">
SELECT * FROM users;
</sql:query>

<c:forEach var="user" items="${listUsers.rows}">

<c:out value="${user.name}" />

<c:out value="${user.email}" />

<c:out value="${user.profession}" />

</c:forEach>

My team leader advised me that it is not a good practice to put queries in the jsp page directly. Since there is a database name and username and password in this code I'm not sure if this code implements proper security. I would like to know your thoughts on the matter, and if there is any alternative to do this using JSTL itself.

Upvotes: 1

Views: 170

Answers (2)

Jonatan Cloutier
Jonatan Cloutier

Reputation: 929

You should really do your query in your java class, not in the jsp, like your team leader advised.

On the security side it doesn't really matter, all the code is available on the server, jsp or java. The sql tag shouldn't output that information in the generated page.

But really the question is more about the right use of the technologies:

jsp is used as a template, it should take data and show them to the end user. Some basic operation can be done life looping on data list or formating data, but this should be only specific to the view you want to make

java controler is used to recuperate data and configure the view as needed like which jsp to use and which data to send in that jsp

Upvotes: 1

Luiggi Mendoza
Luiggi Mendoza

Reputation: 85779

Since JSTL is executed on server side, there's no security hole because the query cannot be seen by clients of the application. There are other problems with this approach:

  • The query is not reusable. If you need it in other pages, you will need to repeat the query. When you have simple queries like this one you cannot check the problem, but this arises with more complex statements that needs parameters as well.
  • You're creating a connection manually per page! This will slow your application. Use a proper datasource for a database connection pool configured as a resource or programatically (C3PO or BoneCP, for example)

Move all your database code into proper Data Access Layer classes. And use <sql> for JSTL for learning purposes only, not for real world applications.

More info:

Upvotes: 4

Related Questions