java.lang.NullPointerException in servlet

17,753

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

Share:
17,753
Julie24
Author by

Julie24

Hello out there. I am a 24 years old girl from Denmark. I am quite new at programming, and hope you guys can help me in here ;-) Have a nice day From Julie

Updated on June 04, 2022

Comments

  • Julie24
    Julie24 almost 2 years

    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
    Julie24 about 10 years
    Hello. Thanks a lot for your answer. the startDate and endDate should be in my: <form> <input id="startDate"/> <input id="endDate"/> </form> and in the javascript?
  • geoand
    geoand about 10 years
    It should definitely be the form whose input is sent to the Servlet. I don't know what how you are handling your UI, but Javascript is needed just to submit values for in a form to a Servlet.
  • Abhishek Nayak
    Abhishek Nayak about 10 years
    @Julie24 check updated answer
  • Julie24
    Julie24 about 10 years
    I am handling my javascript as a calendar like this: postimg.org/image/spe7u93nh
  • Abhishek Nayak
    Abhishek Nayak about 10 years
    @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
  • geoand
    geoand about 10 years
    Are you sure that input elements for the dates are inside the form?
  • Abhishek Nayak
    Abhishek Nayak about 10 years
    @Julie24 you mean still NullPointerException getting in Console?
  • Julie24
    Julie24 about 10 years
    They should be: <form id="myForm"> <input type="text" id="startDate"/> <input type="text" id="endDate"/> </form> <div id="startresult"></div> <div id="endresult"></div>
  • Julie24
    Julie24 about 10 years
    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
    Julie24 about 10 years
    Shouldn't it go here:onSelect: function(dateText,inst){ $('.selected-date').html(dateText); var JSON = $('#myForm').serializeArray(); Console.log(JSON); $.ajax({
  • Abhishek Nayak
    Abhishek Nayak about 10 years
    @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..
  • Julie24
    Julie24 about 10 years
    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?
  • Abhishek Nayak
    Abhishek Nayak about 10 years
  • Abhishek Nayak
    Abhishek Nayak about 10 years
    @Julie24 if any answer solved your problem mark it as answer.