servlet 中的 java.lang.NullPointerException
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22371631/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
java.lang.NullPointerException in servlet
提问by Julie24
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:
当我运行我的 servlet 时,我在 Tomcat 控制台中收到此错误。我想我必须看看我的 SimpleDateformat,但有人能看出这里有什么问题吗?我的代码编译得很好,所以我有点怀疑要注意什么:
Video of the error: https://www.youtube.com/watch?v=3hdmIkwuB6k&feature=youtu.be
错误视频: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:
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:
新的 javascript 代码的新控制台错误:
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)
采纳答案by geoand
I think there is no parameter with 'startDate' (which makes req.getParameter("startDate") return null) there for causing SimpleDateFormat to throw a NullPointerException
我认为没有带有 'startDate' 的参数(这使得 req.getParameter("startDate") 返回 null)导致 SimpleDateFormat 抛出 NullPointerException
回答by Abhishek Nayak
Add id to html form like:
将 id 添加到 html 表单,如:
<form id="myForm">
<input type="text" id="startDate"/>
<input type="text" id="endDate"/>
</form>
then,
然后,
change your AJAX request like:
更改您的 AJAX 请求,例如:
$(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');
}
});
}
});
});
测试应用外观 here这里