Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / October 2007

Tip: Looking for answers? Try searching our database.

Accessing context parameters from web.xml in java class

Thread view: 
Sameer - 29 Sep 2007 13:07 GMT
Dear All,
My web.xml is as follows:

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID">
    <display-name>Reports</display-name>
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
        <welcome-file>index.jsp</welcome-file>
        <welcome-file>default.htm</welcome-file>
        <welcome-file>default.jsp</welcome-file>
    </welcome-file-list>
    <context-param>
        <param-name>db_driver</param-name>
        <param-value>oracle.jdbc.driver.OracleDriver</param-value>
    </context-param>
    <context-param>
        <param-name>db_server</param-name>
        <param-value>192.168.31.41</param-value>
    </context-param>
</web-app>

I able to acess it in the JSP using
ServletContext context = getServletContext();
String driver = context.getInitParameter("db_driver");
String server = context.getInitParameter("db_server");

I have also written a Java class in the Web App as:

import java.sql.*;
public class DBUtils {
    public DBUtils() {
    }
    public static Connection getDBConnection(String driver, String
conn_url,
            String db_username, String db_password) throws Exception {
        Class.forName(driver).newInstance();
        Connection con = DriverManager.getConnection(conn_url, db_username,
                db_password);
        return con;
    }
}

I can get DB connection for the JSP using this:
con = DBUtils.getDBConnection(driver, conn_url, username,
db_password);

But then i have to depend on the external parameters from JSP.

Can i access the context parameters in the java class?
As i checked ServletContext is not getting resolved in the java class
Any way to access the data from web.xml in java class?

Please revert.

-Sameer
Lew - 29 Sep 2007 13:39 GMT
> public class DBUtils {
>
[quoted text clipped - 5 lines]
>
> 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
 }

Signature

Lew

Sameer - 29 Sep 2007 14:22 GMT
> > public class DBUtils {
>
[quoted text clipped - 37 lines]
> --
> 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;
    }

}
Lew - 29 Sep 2007 15:38 GMT
> import java.sql.*;
> import javax.servlet.*;
[quoted text clipped - 17 lines]
>
> }

The happy-path part of this is more or less correct there, but for a few
points of note.

You don't need the throwaway instance of the DB driver, so Class.forName()
alone is enough, and you only ever need to load the driver once, not with
every connection.  Consider using the generic version of Class.

You absolutely must not omit exception handling in production code.  Never
declare a method simply "throws Exception"; use a custom exception.  Always
handle and log exceptions.  Log them at the point of occurrence.  It even sets
a bad example to post Usenet code that violates these precepts unless you
include a disclaimer.

Use spaces, not TABs, to indent Usenet posts.

Signature

Lew

Sameer - 03 Oct 2007 11:15 GMT
> > import java.sql.*;
> > import javax.servlet.*;
[quoted text clipped - 37 lines]
>
> - Show quoted text -

Thanks for the suggestions.
What do you mean by Generic version of class? Accepting data types as
parameters?
Please clarify.
Lew - 03 Oct 2007 14:58 GMT
> What do you mean by Generic [sic] version of class [sic]? Accepting data types as
> parameters?

<http://java.sun.com/docs/books/tutorial/java/generics/index.html>

It's a major feature of the Java language, arguably among the most major.

And I said "the generic version of Class", not "the Generic version of class".
 It matters; I was speaking of the class Class specifically.

How about you read the Javadocs for Class?  That will explain what I meant.

Signature

Lew



Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.