0

Hello am developing a web-app using mvc architecture am trying to insert data from form to database through service layer but it throwing a null pointer exception:

Below is my Servlet :

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    Affiliate af= new Affiliate();

    af.setFisrtName(request.getParameter("txtFname"));
    af.setLastName(request.getParameter("txtLname"));
    af.setGender(request.getParameter("txtGender"));
    af.setCategory(request.getParameter("txtCategory"));
    String dob=(request.getParameter("txtDob"));
    SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");  
    Date date;
    try {
        date = (Date)formatter.parse(dob);
        af.setDate(date);
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    af.setAge(Integer.parseInt(request.getParameter("txtAge")));
    af.setAddress(request.getParameter("txtAddr"));
    af.setCountry("India");
    af.setState(request.getParameter("txtState"));
    af.setCity(request.getParameter("txtCity"));
    af.setPinCode(Integer.parseInt(request.getParameter("txtPin")));
    af.setEmailId(request.getParameter("txtEmail"));
    af.setStd(Integer.parseInt(request.getParameter("txtStd")));
    af.setContactNo(Integer.parseInt(request.getParameter("txtPhone")));
    af.setMobileNo(Long.parseLong(request.getParameter("txtMobile"),10));

AffiliateService afs=new AffiliateService();
**afs.createAffiliate(af);**
}

}

and my service code is:

public class AffiliateService {
    Affiliate affiliate=null;


    public Affiliate createAffiliate( Affiliate affiliate) {
         **validateAffiliate(affiliate);**
        return affiliate;
            }


    private Affiliate validateAffiliate(Affiliate affiliate) {
        this.affiliate=affiliate;
         if(affiliate!=null){
       AffiliateDAO afd=new AffiliateDAO();
        **afd.insertAffiliate(affiliate);**
    }
    return affiliate;

}


}

and my DAO code is as below:

public class AffiliateDAO {

    private DataSource dataSource;
    public void setDataSource(DataSource dataSource) {
    this.dataSource = dataSource;
    }

    public List<Affiliate> addAffiliate(){
    ArrayList<Affiliate> affiliates = new ArrayList<Affiliate>();
    return affiliates;
          }



public void updateAffiliate(Affiliate affiliate){


}

public void delteAffiliate(Affiliate affiliate){

}

public void selectAffiliate(Affiliate affiliate){

}

public void insertAffiliate(Affiliate affiliate){
    String sql="INSERT INTO REGISTER " +"(id,FisrtName,LastName,Gender,Category,DateOfBirth,Age,Address,Country,State,City,PinCode,EmailId,Std,ContactNo,MobileNo)VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
    Connection conn = null;

    try {
        **conn = dataSource.createConnection();**
        PreparedStatement ps = conn.prepareStatement(sql);
        ps.setInt(1, affiliate.getId());
        ps.setString(2, affiliate.getFisrtName());
        ps.setString(3, affiliate.getLastName());
        ps.setString(4,affiliate.getGender());
        ps.setString(5, affiliate.getCategory());
        ps.setDate(6, (Date) affiliate.getDate());
        ps.setInt(7, affiliate.getAge());
        ps.setString(8, affiliate.getAddress());
        ps.setString(9,affiliate.getCountry());
        ps.setString(10,affiliate.getState());
        ps.setString(11, affiliate.getCity());
        ps.setInt(12, affiliate.getPinCode());
        ps.setString(13, affiliate.getEmailId());
        ps.setInt(14,affiliate.getStd());
        ps.setInt(15, affiliate.getContactNo());
        ps.setLong(16, affiliate.getMobileNo());

        ps.executeUpdate();
        ps.close();

    } catch (SQLException e) {
        throw new RuntimeException(e);

    } finally {
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {}
        }
    }
}


public Affiliate searchById(int id){
    String sql = "SELECT * FROM REGISTER WHERE id = ?";

    Connection conn = null;

    try {
        conn = dataSource.createConnection();
        PreparedStatement ps = conn.prepareStatement(sql);
        ps.setInt(1, id);
        Affiliate affiliate = null;
        ResultSet rs = ps.executeQuery();
        if (rs.next()) {

                rs.getInt("id");
                rs.getString("FisrtName");
                rs.getString("LastName");
                rs.getString("Gender");
                rs.getString("Category");
                rs.getDate("DateOfBirth");
                rs.getString("Age");
                rs.getString("Address");
                rs.getString("Country");
                rs.getString("State");
                rs.getString("City");
                rs.getInt("PinCode");
                rs.getString("EmailId");
                rs.getInt("Std+ContactNo");
                rs.getString("MobileNo");
            }
        rs.close();
        ps.close();
        return affiliate;
    } catch (SQLException e) {
        throw new RuntimeException(e);
    } finally {
        if (conn != null) {
            try {
            conn.close();
            } catch (SQLException e) {}
        }

    }
}
}

and this is my dataSource class:

public class DataSource {

    Connection connection=null;
    BasicDataSource bdsource=new BasicDataSource();

    public DataSource(){

        bdsource.setUrl("dbUrl");
        bdsource.setUsername("dbuserName");
        bdsource.setPassword("dbPassword");
        bdsource.setDriverClassName("com.mysql.jdbc.Driver");
    }
    public Connection createConnection(){

        Connection con=null;


        try{

            if(connection !=null){
              System.out.println("Can't create a new connection");
            }
            else{
                con=bdsource.getConnection();
            }
        }
            catch(Exception e){
                e.printStackTrace();

        }
        return con;
    }
}

and my stack trace is as below:

    java.lang.NullPointerException
com.affiliate.DAO.AffiliateDAO.insertAffiliate(AffiliateDAO.java:43)
com.affiliate.service.AffiliateService.validateAffiliate(AffiliateService.java:21)
com.affiliate.service.AffiliateService.createAffiliate(AffiliateService.java:12)
com.affiliate.servlet.AffiliateServlet.doPost(AffiliateServlet.java:71)
javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)
com.affiliate.servlet.RegisterServlet.doPost(RegisterServlet.java:42)
javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)

All the bolded lines in the codes are correspoding to the stack trace. Please help me fix this..I doubt my validate method...

5
  • 1
    You need to call setDataSource Commented Feb 5, 2014 at 9:29
  • ya i ve called its there in my AffiliateDAO Commented Feb 5, 2014 at 9:31
  • only send me 43 numbder lines of AffiliateDAO class Commented Feb 5, 2014 at 9:32
  • There isn't an inkling of evidence in your code that you have dealt with the concern of acquiring a dataSource by any mechanism. Advice: learn to use Spring. Commented Feb 5, 2014 at 9:35
  • Initialize dataSource before call to conn = dataSource.createConnection(); Commented Feb 5, 2014 at 9:56

3 Answers 3

3

Looks like dataSource is null because setDataSource is never called.

Sign up to request clarification or add additional context in comments.

Comments

2

You need to modify you validateAffiliate(Affiliate affiliate) method of the AffiliateService class. You have never initialized the Data Source which is causing NPE to occur.

Check this:

private Affiliate validateAffiliate(Affiliate affiliate) {
   this.affiliate=affiliate;
   if(affiliate!=null){
   AffiliateDAO afd=new AffiliateDAO();

   // This was causing NPE. Data source must be set before using it.
   afd.setDataSource(passDataSourceInstance);

   afd.insertAffiliate(affiliate);
}

4 Comments

DataSource dataSource=new DataSource(); afd.setDataSource(dataSource); afd.insertAffiliate(affiliate); is this how i need to change??
@user3222718: DataSource is an interface. You need to create instance of one the implementing classes of DataSource interface and use it.
please have a look at my DataSource class. I ve updated my question
so i can do it as 'DataSource dataSource=new DataSource(); afd.setDataSource(dataSource); afd.insertAffiliate(affiliate);'???
0

Initialize dataSource before call to conn = dataSource.createConnection(); can be in AffiliateDAO constructor.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.