我的上一个java问题即使是我的教授也无法解决的问题

时间:2011-04-18 17:26:41

标签: java servlets

我正在写我的最后一个java作业(Yayy! - 感谢所有帮助我完成其他工作的人)。在这一个中,我必须编写一个servlet,它接受年龄,婚姻状况,房屋收入和孩子数量,转到数据库,然后将更新的平均值返回给用户。但是,我遇到了这个 stacktrace:

java.lang.NoClassDefFoundError: HouseSurvey$SurveyResults
    at HouseSurvey.doPost(HouseSurvey.java:23)
    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)
Caused by: java.lang.ClassNotFoundException: HouseSurvey$SurveyResults
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1338)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1187)
    ... 21 more

在过去,我已经犯了过多代码,没有足够的代码等等。我为我的新生事道歉。这是我写的课程:

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;
        if (request.getParameter("status") == "married") {
            marriedValue = true;
        } else {
            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!</tile></head>" +
                "<body>" +
                "   <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='left-margin:200px'>Average Age: " + results.getAvgAge() +
                "   <h4 style='left-margin:200px'>Average Number of Children: " + results.getAvgKids() +
                "   <h4 style='left-margin:200px'>Average Number of Married Respondents: " + results.getAvgKids() +
                "   <h4 style='left-margin:200px'>Average Number of Single Respondents: " + results.getTotalSingle() +
                "   <h4 style='left-margin:200px'>Average Income: " + results.getAvgIncome());
    }

    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) {
            if (h.getMarried()) totalMarried += 1;
            else totalSingle += 1;
            totalAge += h.getAge();
            totalChildren += h.getChildren();
            totalIncome += h.getIncome();
        }

        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();
        }
    }
}

我觉得它非常接近,所以我去问我的导师。他看了大约20分钟,他无法理解。

我知道你们这些人非常聪明(尤其是当涉及到东西时),所以如果你们中的任何一个人可以花一点时间帮助一个兄弟出去.......

3 个答案:

答案 0 :(得分:9)

看起来您没有上传所有已编译的.class文件。确保您不仅上传HouseSurvey.class,还要上传编译器生成的所有其他.class文件。在您的情况下,似乎缺少HouseSurvey$SurveyResults.class

答案 1 :(得分:2)

java.lang.NoClassDefFoundError: HouseSurvey$SurveyResults

我建议为您的Java类创建一个包。 Tomcat对默认包中的.class文件不太友好。

您应该创建一个WAR文件并将其部署到Tomcat / webapps目录。不要把你的东西放进ROOT。

我还建议您不要将所有这些代码都压缩到servlet类中。如果你这样做,你不能在没有Tomcat的情况下测试或调试它。 servlet应该做的很少:监听HTTP请求,验证和绑定输入参数,调用其他类的方法来完成工作,然后将响应打包成适当的输出格式。而已。其他课程应该是繁重的工作。 Servlet是HTTP侦听器。

将您的问题分解成更小,更小的部分,您可以单独测试。

例如,在servlet外部的类中进行数据库交互。彻底测试并放在一边。

答案 2 :(得分:0)

将SurveyResults类公开。 readObject()方法需要找到SurveyResult的定义。并且该类应该(很可能)是静态的。