为什么我的Java JOX解析器servlet无法从bean转换为字符串?

时间:2010-10-24 13:44:50

标签: java xml jsp servlets netbeans

目前正在编写一本关于JOX的教程,其中包括 Sams在24小时内使用Apache Tomcat自学JavaServer Pages 2.0

com.wutka.jox已经改变或者作者遗漏了一个关键因素。

当我尝试执行时:

java "hu/flux/xml/XMLTestClient" "http://localhost:8080/SamsTeachYourselfJSP/joxparse" "d:\education\java\SamsTeachYourselfJSP\WebContent\test.xml"

我的CMD控制台显示:

Sending: d:\education\java\SamsTeachYourselfJSP\WebContent\test.xml
To: http://localhost:8080/SamsTeachYourselfJSP/joxparse

Received:


null

我的Eclipse控制台显示:

Can't convert bean to String: null
java.lang.NullPointerException
    at hu.flux.xml.TestBean.toString(TestBean.java:144)
    at hu.flux.xml.JOXParseServlet.doPost(JOXParseServlet.java:50)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at hu.flux.logging.SessionRecorder.doFilter(SessionRecorder.java:61)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:242)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at hu.flux.timing.TimingFilter.doFilter(TimingFilter.java:62)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:242)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:243)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:201)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:163)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:108)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:556)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:401)
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:242)
    at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:267)
    at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:245)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:260)
    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:619)
Returning String: null

这是servlet的当前代码:

package hu.flux.xml;

import java.io.*;

import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import com.wutka.jox.*;
import com.wutka.jox.test.*;


/**
 * Servlet implementation class JOXParseServlet
 */
@SuppressWarnings("unused")
@WebServlet("/JOXParseServlet")
public class JOXParseServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public JOXParseServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
    {
        com.wutka.jox.test.TestBean newBean = new com.wutka.jox.test.TestBean();
        BufferedReader requestReader = request.getReader();
        JOXBeanReader reader = new JOXBeanReader(requestReader);
        reader.readObject(newBean);

        // This servlet just sends a plain text response.
        response.setContentType("text/plain");
        PrintWriter out = response.getWriter();

        String beanString = null;
        try { beanString = newBean.toString(); }
        catch (Exception exc)
        {
            System.err.println("Can't convert bean to String: " + exc.getMessage());
            exc.printStackTrace();
        }

        System.out.println ("Returning String: " + beanString);
        out.println(beanString);
    }

}

XMLTestClient和test.xml都不是问题所在,因为它们都能成功地与Sax解析器和Dom解析器一起工作。

但是,如果看到它们有用或有趣,那么它们就是:

<!-- test.xml -->
<?xml version="1.0" encoding="UTF-8"?>
    <name>
        <first>Brian</first>
        <last>Kessler</last>
    </name>

////////////////////////////////////////////

/**
 *  XMLTestClient.java
 */
package hu.flux.xml;
import java.io.*;
import java.net.*;

/**
 * @author Brian Kessler
 *
 */
public class XMLTestClient {

    /**
     * 
     */
    public XMLTestClient() {
        // TODO Auto-generated constructor stub
    }

    /**
     * @param args
     */
    public static void main(String[] args) 
    {
        try
        {
            // args[1] is the name of the file to send.

            System.out.println("\n\nSending: " + args[1]);
            System.out.println("To: " + args[0]);
            System.out.println("\nReceived:\n\n");

            try
            {
                File f = new File(args[1]);
                int contentLength = (int) f.length();

                // args[0] is the URL to send the file to.
                URL url = new URL(args[0]);
                URLConnection conn = url.openConnection();

                // Tell the URLConnection that this is an XML file.
                conn.setDoOutput(true);
                conn.setRequestProperty("content-type", "text/xml");
                conn.setRequestProperty("content-length", ""+contentLength);

                FileInputStream in = new FileInputStream(f);

                byte[] buffer = new byte[4096];
                int len;

                OutputStream out = conn.getOutputStream();

                // Send the XML file to the servlet.
                while ((len = in.read(buffer)) > 0)
                    { out.write(buffer, 0, len); }

                InputStream resp = conn.getInputStream();

                // Read the response back from the servlet.
                while ((len = resp.read(buffer)) > 0)
                    { System.out.write(buffer, 0, len); }

            }
            catch (Exception exc) 
            {
                System.err.println("Missing file argument: " + exc);
                exc.printStackTrace();
            }
        }
        catch (Exception exc) { exc.printStackTrace(); }
    }

}

1 个答案:

答案 0 :(得分:0)

问题在于TestBean。

在本书的上下文中,似乎这可能是某种通用bean。

实际上,bean中的getter和setter需要匹配XML的内容。

toString()失败,因为bean没有填充数据。

一旦我创建了一个与XML匹配的bean并包含了一个自定义的toString(),我就能够使这个servlet工作。 : - )

这是一个工作bean:

/**
 * 
 */
package hu.flux.user;

/**
 * @author Brian Kessler
 *
 */
public class NamedPerson extends Person
{
    private String firstName = "";
    private String lastName = "";


    public String getFirst() { return this.firstName; }
    public void setFirst(String firstName) {this.firstName = firstName;}

    public String getLast() { return this.lastName; }
    public void setLast(String lastName) {this.lastName = lastName;}

    public String toString() {return (this.firstName + " " + this.lastName);}
}

此外,在servlet中,我需要更改:

com.wutka.jox.test.TestBean newBean = new com.wutka.jox.test.TestBean();

Person newBean new Person();

欢迎Teja Kantamneni让我走上正确的答案。 : - )