2

When I run my servlet I get this error in my Tomcat console. I guess I have to look at my SimpleDateformat, but can anyone see what is wrong here? My code is compiling fine, so I am a little in doubt what to look after:

Video of the error: https://www.youtube.com/watch?v=3hdmIkwuB6k&feature=youtu.be

Have a nice day/evening to everybody From Julie

My Servlet:

package WorkPackage;

import java.io.*;
import java.sql.*;
import java.text.SimpleDateFormat;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;

@WebServlet("/getHoursSQL")
public class getHoursSQL extends HttpServlet{

    private static final long serialVersionUID = 1L;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }

    public void doPost(HttpServletRequest req, HttpServletResponse res) 
        throws ServletException, IOException{

        String connectionURL = "jdbc:mysql://localhost/NekiWork";
        Connection connection=null;

        try {
            //Load database driver
            Class.forName("com.mysql.jdbc.Driver");
            //Connection to the database
            connection = DriverManager.getConnection(connectionURL, "root", ""); 
            //Getting the data from database

            String sql = "SELECT *, (Day_hours + (Day_minutes / 60)) AS Allday_hours FROM Workdata "
                    + "WHERE startdate = ? AND endDate = ? ";
            PreparedStatement pst = connection.prepareStatement(sql);

            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

            java.util.Date util_StartDate = format.parse( req.getParameter("startDate") );
            java.sql.Date sql_StartDate = new java.sql.Date( util_StartDate.getTime() );

            java.util.Date util_EndDate = format.parse( req.getParameter("endDate") );
            java.sql.Date sql_EndDate = new java.sql.Date( util_EndDate.getTime() );
                pst.setDate( 1, sql_StartDate );
                pst.setDate(2, sql_EndDate );

            //Show the result from database
                ResultSet rs = pst.executeQuery();

            float Allday_hours_sum = 0;
                while (rs.next()){                                      
                    Allday_hours_sum += rs.getFloat("Allday_hours"); 

                }   
                res.setContentType("text/html;charset=UTF-8");          
                res.getWriter().print(Allday_hours_sum); 

                pst.close();

        }
        catch(ClassNotFoundException e){

            System.out.println("Couldn't load database driver: " + e.getMessage());
        }
        catch(SQLException e){
            System.out.println("SQLException caught: " + e.getMessage());
        }
        catch (Exception e){
            e.printStackTrace();
        }
        finally {

            try {
                if (connection != null) connection.close();
            }
            catch (SQLException ignored){
                System.out.println(ignored);
            }
        }
    }
}

Javascript:

    <form id="myForm">
        <input type="text" id="startDate"/>                     
        <input type="text" id="endDate"/>
    </form>
    <div id="startresult"></div>
    <div id="endresult"></div>
    <script>

    $(function(){
        $("#startDate").datepicker({
            dateFormat: 'yy-mm-dd',
            onSelect: function(dateText,inst){
                $('.selected-date').html(dateText);
                 var JSON = $('#myForm').serializeArray(); //you forgot to create JSON data
                $.ajax({
                      url: "../getHoursSQL",
                      type: "post",
                      data: JSON,
                      success: function(data){
                          start: $("#startDate").val();
                          alert("success");
                          $("#startresult").html(data);

                      },
                      error:function(){
                          alert("failure");
                          $("#startresult").html('there is error while submit');
                      }  
                    });
            }
        });
    });

    $(function(){
        $("#endDate").datepicker({
            dateFormat: 'yy-mm-dd',
            onSelect: function(dateText,inst){
                $('.selected-date').html(dateText);
                 var JSON = $('#myForm').serializeArray(); //you forgot to create JSON data
                $.ajax({
                      url: "../getHoursSQL",
                      type: "post",
                      data: JSON,
                      success: function(data){
                          start: $("#endDate").val();
                          alert("success");
                          $("#startresult").html(data);

                      },
                      error:function(){
                          alert("failure");
                          $("#startresult").html('there is error while submit');
                      }  
                    });
            }
        });
    });

</script>

New console error with new javascript code:

java.lang.NullPointerException
at java.text.SimpleDateFormat.parse(SimpleDateFormat.java:1234)
at java.text.DateFormat.parse(DateFormat.java:335)
at WorkPackage.getHoursSQL.doPost(getHoursSQL.java:40)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:895)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:918)
at java.lang.Thread.run(Thread.java:695)
Julie24
  • 279
  • 4
  • 6
  • 19

2 Answers2

1

I think there is no parameter with 'startDate' (which makes req.getParameter("startDate") return null) there for causing SimpleDateFormat to throw a NullPointerException

geoand
  • 60,071
  • 24
  • 172
  • 190
0

Add id to html form like:

<form id="myForm">
        <input type="text" id="startDate"/>                     
        <input type="text" id="endDate"/>
</form>

then,

change your AJAX request like:

$(function(){
    $("#startDate").datepicker({
        dateFormat: 'yy-mm-dd',
        onSelect: function(dateText,inst){
            $('.selected-date').html(dateText);
             var jsonStr = $('#myForm').serializeArray(); //you forgot to create JSON data
            $.ajax({
                  url: "../getHoursSQL",
                  type: "post",
                  data: jsonStr,
                  success: function(data){
                      start: $("#startDate").val();                          
                      $("#startresult").html(data);
                      alert("success");
                  },
                  error:function(){
                      alert("failure");
                      $("#startresult").html('there is error while submit');
                  }  
                });
        }
    });
});


Tested app look here
Abhishek Nayak
  • 3,732
  • 3
  • 33
  • 64
  • @Julie24 you have not given form id to serializeArray("#endDate") endDate is not form id.. check my updated answer there is html form with id – Abhishek Nayak Mar 13 '14 at 07:39
  • @Julie24 you mean still `NullPointerException` getting in Console? – Abhishek Nayak Mar 13 '14 at 07:42
  • I have just made a short video of what happenes when I run the code, if that helps anything in my question. Yes I will try to find out to do that. I will write in 5 minutes again here – Julie24 Mar 13 '14 at 07:48
  • Shouldn't it go here:onSelect: function(dateText,inst){ $('.selected-date').html(dateText); var JSON = $('#myForm').serializeArray(); Console.log(JSON); $.ajax({ – Julie24 Mar 13 '14 at 07:54
  • @Julie24 k, the problem is when you select `startDate` AJAX request is triggered, that time `endDate` is null because you have not selected the `endDate`, So do one thing trigger the AJAX request when `endDate` is selected.. – Abhishek Nayak Mar 13 '14 at 07:55
  • In my javascript I have 2 functions. One with startDate and one with endDate. The endDate should be triggered when I choose the second form as I see it? – Julie24 Mar 13 '14 at 07:57
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/49633/discussion-between-rembo-and-julie24) – Abhishek Nayak Mar 13 '14 at 07:58
  • @Julie24 if any answer solved your problem mark it as answer. – Abhishek Nayak Mar 30 '14 at 08:50