gpt4 book ai didi

抛出 servlet 和堆栈跟踪的 Java 问题

转载 作者:行者123 更新时间:2023-11-30 06:35:42 29 4
gpt4 key购买 nike

我有以下内容,我必须在其中编写一个 servlet,该 servlet 需要年龄、婚姻状况、家庭收入和 child 数量,输出到数据库,然后将更新后的平均值返回给用户。但是,我遇到了这个堆栈跟踪:

java.lang.NullPointerException
at HouseSurvey$SurveyResults.access$200(HouseSurvey.java:86)
at HouseSurvey.doPost(HouseSurvey.java:43)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:709)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
at org.apache.catalina.servlets.InvokerServlet.serveRequest(InvokerServlet.java:419)
at org.apache.catalina.servlets.InvokerServlet.doPost(InvokerServlet.java:169)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:709)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:252)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:213)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:178)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:126)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:105)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:107)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:148)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:868)
at org.apache.coyote.http11.Http11BaseProtocol$Http11ConnectionHandler.processConnection(Http11BaseProtocol.java:663)
at org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:527)
at org.apache.tomcat.util.net.LeaderFollowerWorkerThread.runIt(LeaderFollowerWorkerThread.java:80)
at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:684)
at java.lang.Thread.run(Unknown Source)

这到底是什么意思?我想我得到了一个 NullPointerException,但我看不到在哪里。这是我的程序:

import java.text.DecimalFormat;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class HouseSurvey extends HttpServlet
{
private final static String SURVEY_FILE = "HouseSurvey.dat";
SurveyResults results;
Household h;
DecimalFormat form = new DecimalFormat("#,###,#00.00");

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
PrintWriter out = response.getWriter(); //make a printwriter to print the page
File survey = new File(SURVEY_FILE);
if(!survey.exists()) //check to see if the file exists
results = new SurveyResults();
else
{ //If the file exists, read it the latest survey tallies
try
{
ObjectInputStream ips = new ObjectInputStream(new FileInputStream(survey));
results = (SurveyResults)ips.readObject(); //read the file into 'results'
ips.close(); //close the input stream
}
catch(ClassNotFoundException e) {e.printStackTrace();}
catch(FileNotFoundException f) {f.printStackTrace();}
catch(IOException ioe) {ioe.printStackTrace();}
}
int ageValue = Integer.parseInt(request.getParameter("age")),
childValue = Integer.parseInt(request.getParameter("children"));
double incomeValue = Double.parseDouble(request.getParameter("income"));
Boolean marriedValue = true;
if (request.getParameter("status").equals("married"))
marriedValue = true;
else
if(request.getParameter("status").equals("single"))
marriedValue = false;
Household h = new Household(ageValue,childValue,incomeValue,marriedValue);
results.totalResults(h);
//Write results to disk.
try
{
ObjectOutputStream ops = new ObjectOutputStream(new FileOutputStream(survey));
ops.writeObject(results); ops.flush(); ops.close();
}
catch(IOException ioe) {ioe.printStackTrace();}
response.setContentType("text/html"); //contnent type for the responding webpage
out.println("<html>\n"+
"<head><title>Thanks!</title></head>"+
"<body style='background:cyan;'>"+
" <h1 style='text-align:center'>RRC BIT Department - Household Survey</h1>"+
" <hr><br/>"+
" <h2 style='text-align:center'>Up to Date Survey Results</h2>"+
" <h4 style='margin-left:200px'>Average Age: "+form.format(results.getAvgAge())+"</h4>"+
" <h4 style='margin-left:200px'>Average Number of Children: "+form.format(results.getAvgKids())+"</h4>"+
" <h4 style='margin-left:200px'>Average Number of Married Respondents: "+form.format(results.getTotalMarried())+"</h4>"+
" <h4 style='margin-left:200px'>Average Number of Single Respondents: "+form.format(results.getTotalSingle())+"</h4>"+
" <h4 style='margin-left:200px'>Average Income: "+form.format(results.getAvgIncome())+"</h4></body>");
}
private class Household
{
private int age, children;
private double income;
private boolean married=false;
/**Method: Household
* Constructor
* @ param age - age of person surveyed:int
* @ param children - number of children person surveyed has:int
* @ param married - true or false, used to determine married or single:boolean
* @ param income - the family income of the person surveyed:double
*/
private Household(int age, int children, double income, boolean married)
{
this.age=age; this.children=children; this.income=income; this.married=married;
}
//Getters
private int getAge() {return age;}
private int getChildren() {return children;}
private double getIncome() {return income;}
private boolean getMarried() {return married;}
}
private class SurveyResults implements Serializable
{
private double totalAge, totalChildren, totalMarried, totalSingle, totalIncome;
/**Method: SurveyResults
* Used for totals
* @ param h - Household object created above:Household
*/
private void totalResults(Household h)
{
totalAge += h.getAge(); totalChildren += h.getChildren(); totalIncome += h.getIncome();
if(h.getMarried()) totalMarried += 1;
else
totalSingle += 1;
}
private double getTotalHouseholds() {return totalSingle + totalMarried;}
private double getAvgAge() {return totalAge/getTotalHouseholds();}
private double getAvgKids() {return totalChildren/getTotalHouseholds();}
private double getTotalMarried() {return totalMarried;}
private double getTotalSingle() {return totalSingle;}
private double getAvgIncome() {return totalIncome/getTotalHouseholds();}
}
}

最初在我的 HTML 输出中,我不小心有一行

"Average Number of Married Respondents: "+form.format(results.getTotalMarried())+"</h4>" 

作为

"Average Number of Married Respondents: "+form.format(results.getAvgKids())+"</h4>"

而且效果很好。然后我将它切换到前者以获得 totalMarried,现在它给了我异常(exception)。问题出在哪里?

提前致谢。

最佳答案

我将其添加为单独的答案,因为这是完全不同的思路。如果编辑更好,请告诉我,我会删除重复的。

看起来您将在读取结果对象时抛出 IOException。原因是,您尝试序列化的类不可序列化。由于 SurveyResults 是一个内部类,要序列化它也必须序列化包含类(在本例中为您的 Servlet)。我建议将您的类更改为静态嵌套类,或者可能是默认作用域的顶级类。 (根据需要更改方法访问级别。)

您可能还需要删除您的调查结果数据文件并重新开始。在我的测试中,它引用了不可序列化的类,在删除它之前我无法让代码运行。

关于抛出 servlet 和堆栈跟踪的 Java 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5710099/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com