我將我的緯度和經度作爲url參數傳遞給我的java servlet。我想用hibernate將這些經度和緯度存儲到mySQL數據庫中。將String轉換爲Double我使用下面的代碼,但它給了我一個nullPointerException。如何將字符串轉換爲Java Servlet中的double?
FileWriter fstream = new FileWriter("out2.txt");
req.setCharacterEncoding("UTF-8");
resp.setCharacterEncoding("UTF-8");
String par1 = req.getParameter("param1");
String par2 = req.getParameter("param2");
BufferedWriter out = new BufferedWriter(fstream);
out.append(par1);
out.append(" ");
out.append(par2);
double lat=0.0;
double lon=0.0;
try
{
lat =Double.parseDouble(par1);
}
catch(NumberFormatException e)
{
//not a double
}
try
{
lon= Double.parseDouble(par2);
}
catch(NumberFormatException e)
{
//not a double
}
我得到我的控制檯以下錯誤:
SEVERE: Servlet.service() for servlet [org.spark.servlet.PostDataReceiverServlet] in context with path [/HelloServlet] threw exception
java.lang.NullPointerException
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:991)
at java.lang.Double.parseDouble(Double.java:510)
at org.spark.servlet.PostDataReceiverServlet.doGet(PostDataReceiverServlet.java:48)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:304)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:224)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:185)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:151)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:929)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:405)
at org.apache.coyote.http11.Http11AprProcessor.process(Http11AprProcessor.java:269)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:515)
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:1773)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:662)
代碼工作正常,如果我同時刪除parseDouble語句。 @所有我很確定par1或par2不是null。我只是檢查了一下,然後我在文件中輸出了以下內容。 28.500788 77.395829
。這些是我從我的Android應用程序發送的座標。
你確定'par1'不是null嗎? – nullpotent
我很肯定part1是空的,因爲當你嘗試解析它時你得到了NPE。有了這個說法,你的問題在於你的getParameter行 –
是的。之前,我將這兩個參數寫入文件,並且工作正常。 – rishiag