2

I am trying to create a rest webservice to add an element to data base. This is my connection class

@Path(value="/user")
public class classeConnection {
    Connection cn=null;
    Statement st=null;
    public classeConnection()  {
      try  {
        Class.forName("com.mysql.jdbc.Driver");
      } catch (ClassNotFoundException e ){};
    }
    public void connecter ()throws SQLException  {
      cn= DriverManager.getConnection("jdbc:mysql://localhost:3306/codezone4", "root","");
      st=cn.createStatement();
      System.out.print("Ping!!");
    }
    public ResultSet execSelect(String req)throws SQLException {
        return(st.executeQuery(req));
    }
    @GET
    @Path (value="/add/{nom}/{prenom}/{email}/{login}/{psw}")
    @Produces(MediaType.APPLICATION_JSON)
    public String execMAJ(@PathParam(value="nom")String nom,
                              @PathParam(value="prenom")String prenom,
            @PathParam(value="email")String email ,@PathParam(value="login")String login,
            @PathParam(value="psw")String psw) throws SQLException  {
      String req;
          req="INSERT INTO user (nom,prenom,email,login,psw) values(
            '"+nom+"','"+prenom+"','"+email+"','"+login+"','"+psw+"')";
          int r=0;
          System.out.println(st);
          r=st.executeUpdate(req);
          System.out.println(st);
      return "succee d'ajout";
    }
    public void fermeture()throws SQLException {
          st.close(); // line 57
      cn.close();
    }
    public static void main(String[] args) throws SQLException {
        classeConnection c=new classeConnection();
        c.connecter();
    }
}

And this is my web.xml

<?xml version="1.0" encoding="ASCII"?>
<web-app 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns="http://java.sun.com/xml/ns/javaee" 
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee       http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" 
version="3.0">
<display-name>rest</display-name>
<servlet>
<description>JAX-RS Tools Generated - Do not modify</description>
<servlet-name>JAX-RS Servlet</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.server.provider.packages</param-name>
<param-value>com.example</param-value>
</init-param><load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>JAX-RS Servlet</servlet-name>
<url-pattern>/myrest/*</url-pattern>
</servlet-mapping>
</web-app>

When I run my webservice using the url : /AddToDataBase/myrest/user/add/test/test/[email protected]/test/test, I get this error :

java.lang.NullPointerException
com.example.classeConnection.execMAJ(classeConnection.java:57)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
java.lang.reflect.Method.invoke(Unknown Source)
com.sun.jersey.spi.container.JavaMethodInvokerFactory$1.invoke(JavaMethodInvokerFactory.java:60)
com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$TypeOutInvoker._dispatch(AbstractResourceMethodDispatchProvider.java:185)
com.sun.jersey.server.impl.model.method.dispatch.ResourceJavaMethodDispatcher.dispatch(ResourceJavaMethodDispatcher.java:75)
com.sun.jersey.server.impl.uri.rules.HttpMethodRule.accept(HttpMethodRule.java:302)
com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
com.sun.jersey.server.impl.uri.rules.ResourceClassRule.accept(ResourceClassRule.java:108)
com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
com.sun.jersey.server.impl.uri.rules.RootResourceClassesRule.accept(RootResourceClassesRule.java:84)
com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1542)
com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1473)
com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1419)
com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1409)
com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:409)
com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:540)
com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:715)
javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)

Are there any suggestions to this issue? Please help!

3
  • Could you point out line 57 of classeConnection?
    – Tejas Kale
    Commented May 26, 2014 at 9:49
  • I edited my post so you can see line 57
    – Marya
    Commented May 26, 2014 at 9:52
  • From the error it is clear that it is getting null pointer exception at line 57 in execMAJ method. But you pointed out line 57 in fermeture() method. Kindly confirm.
    – Vicky
    Commented May 26, 2014 at 10:16

2 Answers 2

1

The method void connecter() never gets called so the Statement objects are not getting initialized and they remain null. You should probably change the Statement object to a local variable and initialize it right before using it, then close the statement right after using it. You can do the same with the database connection:

cn= DriverManager.getConnection("jdbc:mysql://localhost:3306/codezone4", "root","");

If you need faster performance, then the database connection could be opened when your application starts up (not by this class) and then closed when it shuts down. Or you can use a ConnectionPool.

Another issue to consider:

We are not allowed to pass special characters in a URL parameter without encoding them. For a list of what characters are allowed, see this question.

Your test URL should be /AddToDataBase/myrest/user/add/test/test/test%40test.com/test/test

5
  • I get the same error even when I change my url to /AddToDataBase/myrest/user/add/test/test/test/test/test
    – Marya
    Commented May 26, 2014 at 10:23
  • You do need the URL encoding but that shouldn't cause the null pointer exception. Since you know the exception happens on the st.close() line, try moving this to where the statement is being used. Make Statement a local variable rather than a class field. You are printing before and after the database case call: System.out.println(st); r=st.executeUpdate(req); Sytem.out.println(st); What output do you get from this?
    – Thorn
    Commented May 26, 2014 at 10:28
  • null , null this value does not change!!
    – Marya
    Commented May 26, 2014 at 10:30
  • The method public void connecter () never gets called. Move whatever initialization code you need to the constructor.
    – Thorn
    Commented May 26, 2014 at 10:31
  • Let us continue this discussion in chat.
    – Thorn
    Commented May 26, 2014 at 10:40
0

Do not ask for a new connection in each endpoint this is not a good use of a database connection. You should use a central connection pool and inject it , or if you do not want to mess with DI just make a connection pool with a singleton class using a library such as http://www.mchange.com/projects/c3p0/ .

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.