Re: Accessing context parameters from web.xml in java class
On Sep 29, 5:39 pm, Lew <l...@lewscanon.com> wrote:
Sameer wrote:
public class DBUtils {
But then i [sic] have to depend on the external parameters from JSP.
Can i [sic] access the context parameters in the java [sic] class?
As i [sic] checked ServletContext is not getting resolved in the java [sic] class
Any way to access the data from web.xml in java [sic] class?
Please revert.
Interesting use of the term "revert". I'm guessing it's a regional variant usage.
You cannot access the context parameters directly from any class; you need to
inject something that references them. Servlets do it by injecting
ServletRequest and ServletResponse objects into the service() method. You can
do it by injecting the parameters into your custom-class method invocations,
either individually, as a parameter map of some sort, or via the request
object entire.
protected void doPost(
HttpServletRequest request, HttpServletResponse response )
throws ServletException, IOException
{
NonServlet handler = new NonServlet();
handler.processRequest(request, response);
}
or
protected void doPost(
HttpServletRequest request, HttpServletResponse response )
throws ServletException, IOException
{
ServletContext ctx = getServletContext();
String dbDriver = ctx.getInitParameter( DBDRIVER );
logger.debug( "dbDriver "+ dbDriver );
Dao.loadDriver( dbDriver ); // give Dao class access to dbDriver parm
}
--
Lew
Thanks I modified the procedure as:
import java.sql.*;
import javax.servlet.*;
public class DBUtils {
public static Connection getDBConnection(ServletContext context)
throws Exception {
String driver = context.getInitParameter("db_driver");
String server = context.getInitParameter("db_server");
String port = context.getInitParameter("db_port");
String sid = context.getInitParameter("db_sid");
String conn_url = "jdbc:oracle:thin:@" + server + ":" + port + ":"
+ sid;
String db_username = context.getInitParameter("db_username");
String db_password = context.getInitParameter("db_password");
Class.forName(driver).newInstance();
Connection con = DriverManager.getConnection(conn_url, db_username,
db_password);
return con;
}
}