Search code examples
servletsjstlvs-web-application-project

Setting Sql datasource using JSTL Tag in JSP


Weeks before I developed a simple web application using JSP servlets. After reading through various sites, came to know that the Scriptlets should be completely avoided in jsp [view].

Hence, I am trying to convert to JSTL. While setting the SQL data source whose context are available in the web.xml. Things not worked. Also, how can I avoid mentioning the db user credentials explictly in the JSTL code. If any best way, please share. Thanks in Advance

JSTL connecting MySQL

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%>    

<sql:setDataSource 
    var="datasource"
    driver="com.mysql.jdbc.Driver"
    url=${initParam['dbURL']
    user=${initParam['dbUser']} 
    pass=${initParam['dbPass']}/>

Web.xml

<context-param>
    <param-name>dbUser</param-name>
    <param-value>root</param-value>
</context-param>
<context-param>
    <param-name>dbPassword</param-name>
    <param-value>root</param-value>
</context-param>
<context-param>
    <param-name>dbURL</param-name>
    <param-value>jdbc:mysql://xxx.xxx.xxx:3306/client_db</param-value>
</context-param>
<context-param>
    <param-name>log4j-config</param-name>
    <param-value>WEB-INF/log4j.xml</param-value>
</context-param>
<error-page>
    <error-code>404</error-code>
    <location>/AppErrorHandler</location>
</error-page>
<error-page>
    <exception-type>java.lang.Throwable</exception-type>
    <location>/AppErrorHandler</location>
</error-page>

<filter>
    <filter-name>AuthenticationFilter</filter-name>
    <filter-class>com.schoolmanager.servlet.filters.AuthenticationFilter</filter-class>
</filter>

<filter-mapping>
    <filter-name>AuthenticationFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

<session-config>
    <session-timeout>30</session-timeout>
</session-config>

Solution

  • You are right it is really not good idea to store db parameters in JSP page. Also official Java EE documentation approve it:

    The JSTL SQL tags for accessing databases listed in Table 7-7 are designed for quick prototyping and simple applications. For production applications, database operations are normally encapsulated in JavaBeans components.

    The general idea to store you connection parametrs in xml or Java files and execute all db specific operations in plain Java. To get this conception check example.