简体   繁体   中英

Cannot connect to SQL Server via Servlet however can connect to it locally

I am trying to connect to SQL Server via JDBC - for that I have created a class called Sahoodblib which does the work of connecting to database and retrieving the data. I have created another client, which is called Sahooclient - this provides a front end for displaying the data. The system so far works beautifully.

Now, I am trying to create a servlet, which instantiates Sahoodblib, and then I keep getting the ClassNotFoundException, I traced it back and I get the exception at Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver")

Now, this has perplexed me, because this is working perfectly fine when I invoke the method locally, but gives me problem when I do it via browser. I have already enabled TCP/IP and all other connections for SQL Server.

This is where I get error:

   /* Initialize the servlet. */
@Override
public void init(ServletConfig config) throws ServletException {
    super.init(config);
    sdb = new Sahoodblib("ism6236","ism6236bo");
}

EDIT:

This is how I connect to DB:

    public Sahoodblib(String uname, String pwd) {
    try {
        Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
        String url = "jdbc:sqlserver://localhost;" + 
            "databaseName=Travel;user=ism6236;password=ism6236bo;";
        cn = DriverManager.getConnection(url);
    } catch (ClassNotFoundException ex) {
        Logger.getLogger(Sahoodblib.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SQLException ex) {
        Logger.getLogger(Sahoodblib.class.getName()).log(Level.SEVERE, null, ex);
    }
    set_max_tid();
}

The class com.microsoft.sqlserver.jdbc.SQLServerDriver is in the classpath when you run stand-alone. It isn't when you run as a servlet.

You need to figure out how these classpaths differs. When you run the client, do you give a classpath containing the SQL Server classes in a jar file?

  • If you do, you need to look at the web server and figure out how to supply it with ther same jar file; usually you put it in the WEB-INF/lib directory for your web-app.
  • If you do not, it is included from one of the default places for the JVM. Are the client and the web server using the same JVM?

I have assumed here that you have all the SQL Server stuff in a JAR-file. If you have unpacked it somewhere, your classpath needs the directory where it is unpacked instead of the jar file itself.

You can find more information on where the class loader will look for classes in http://download.oracle.com/javase/6/docs/technotes/tools/findingclasses.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM