1

Trying to do simple connection with a datebase in SSMS, and that's all working fine when I use ordinary Java project, but when i use web application/jsf it's not working. Connection is NULL all the time. This is the error i get:

Caused by: java.lang.NullPointerException
at controllers.FirstController.firstOne(FirstController.java:42)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at javax.el.ELUtil.invokeMethod(ELUtil.java:332)
at javax.el.BeanELResolver.invoke(BeanELResolver.java:537)
at javax.el.CompositeELResolver.invoke(CompositeELResolver.java:256)
at com.sun.el.parser.AstValue.invoke(AstValue.java:283)
at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:304)
at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:87)
... 36 more

This is simple xhtml file:

<h:head>
    <title>Facelet Title</title>
</h:head>
<h:body>
    <p>
    Hello from Facelets <br/><br/>
    <h:form>
    <b:commandButton action="#{firstController.firstOne()}" look="primary" value="First try" />
    </h:form>
    </p>
</h:body>

Connection with base:

public class DB {
    private static final String username="sa";
    private static final String password="123";
    private static final String database="KulturniDogadjaji";
    private static final int port=1434;
    private static final String serverName="localhost";

    //jdbc:sqlserver://[serverName[\instanceName][:portNumber]][;property=value[;property=value]]
    //link ka zvanicnom sajtu: https://learn.microsoft.com/en-us/sql/connect/jdbc/building-the-connection-url?view=sql-server-2017
    private static final String connectionString="jdbc:sqlserver://"+serverName+":"+port+";"+
            "database="+database+";user="+username+";password="+password;
 //   private static final String connectionString="jdbc:sqlserver://"+serverName+":"+port+";"+
 //         "database="+database+";integratedSecurity=true;

    private Connection connection;    
    private DB(){
        try {
            connection=DriverManager.getConnection(connectionString);
        } catch (SQLException ex) {
            Logger.getLogger(DB.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    private static DB db=null;
    public static DB getInstance()
    {
        if(db==null)
            db=new DB();
        return db;
    }
    public Connection getConnection() {
        return connection;
    }
}

And, controller:

@ManagedBean(name = "firstController")
public class FirstController {

public FirstController() {
}

public String firstOne() {
    FacesContext context = FacesContext.getCurrentInstance();
    Connection connection = DB.getInstance().getConnection();
    String insertQuery = "insert into admin values('onetwo', 'onetwo')";

    try {
        Statement st = connection.createStatement(); // this is where it's breaks
        int ret = st.executeUpdate(insertQuery);
        System.out.println("Number of changed rows:" + ret);
        context.addMessage(null, new FacesMessage("Successful"));

    } catch (SQLException ex) {
        Logger.getLogger(FirstController.class.getName()).log(Level.SEVERE, null, ex);
        context.addMessage(null, new FacesMessage("Unsuccessful"));
    }
    return null;
}

}

At the very end i must repeat that this is working correctly with ordinary Java project(assuming that DB class is ok) so i suppose somewhere else is problem.

p.s. my pc is using port 1434 for sqlserver

munchy a
  • 11
  • 2
  • Can you tell what the line _32_'s code is (from the stacktrace: `at head.Controller.firstOne(Controller.java:32)`)? – prasad_ Jul 19 '18 at 01:18
  • Statement st = connection.createStatement(); // this is where it's breaks – munchy a Jul 19 '18 at 01:21
  • because connection is null... – munchy a Jul 19 '18 at 01:22
  • Is the JDBC driver on the classpath? – prasad_ Jul 19 '18 at 01:25
  • i corrected Stack Trace, sorry – munchy a Jul 19 '18 at 01:25
  • how can i check classpath? sqljdbc.jar is in library – munchy a Jul 19 '18 at 01:27
  • Yes, in the web server's lib folder (for example, in Apache Tomcat). – prasad_ Jul 19 '18 at 01:28
  • i'am using GlassFish server; its not in GlassFish its in 'Libraries' folder – munchy a Jul 19 '18 at 01:32
  • Also, print the `connectionString` with a logger statement and see if its ok. – prasad_ Jul 19 '18 at 01:33
  • it works well with an ordinary Java project, i don't see why it would be different here – munchy a Jul 19 '18 at 01:37
  • In the `DB()` constructor change this in the `try-catch` from `SQLException` -to- `Exception`, and see anything? Also, check this [post](https://stackoverflow.com/questions/32558251/sqljdbc4-2-on-glassfish-server4-1). – prasad_ Jul 19 '18 at 01:47
  • it works now.. added Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); in DB constructor. I thought it's not necessary in latest versions. Thanks – munchy a Jul 19 '18 at 11:01
  • The correct way to connect to a database from a web application is to use a `javax.sql.DataSource`. The `DataSource` is configured on the web server as a _resource_. You may check your web server user guide to find the correct way to configure in the `WEB-INF/web.xml` or `META-INF/contect.xml`.The `DataSourse` object is accessed in the web app using JNDI's `Context` API to get the `Connection` object. Note the `DriverManager` is not used in this case. Also, see [Oracle's Java tutorial on JDBC](https://docs.oracle.com/javase/tutorial/jdbc/basics/sqldatasources.html). – prasad_ Jul 19 '18 at 12:13

0 Answers0