i am developing a project using jsp & servlet.
i want create a xml from result set using document builder but when the servlet is executed it displays the Http Status 500 error

tell me what to do . where to place that xml file

is there other for writing result set data as xml
below is the code that does not work

protectedvoid doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException
    {
        // TODO Auto-generated method stub
        Document mapDoc;
        Document dataDoc = null;
        String XmlFileName = request.getParameter("filename");
        DocumentBuilder db;
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        System.out.println(XmlFileName);
        try
        {
            db = dbf.newDocumentBuilder();
            mapDoc = db.parse(XmlFileName);
            dataDoc = db.newDocument();
        }
        catch (ParserConfigurationException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        catch (SAXException e)
        {
            // TODO Auto-generated catch block
            System.out.println("sax");
            e.printStackTrace();
        }
        catch (IOException e)
        {
            // TODO Auto-generated catch block
            System.out.println("IO ->");
            e.printStackTrace();
        }
        Connection con;
        Statement st;
        ResultSet rs;
        ResultSetMetaData rsd = null;
        Element DocRoot = null;
        String query = "select * from StationarRequest";
        try
        {
            Class.forName(DbConnect.getDriverName());
            con = DriverManager.getConnection(DbConnect.getDsnName(), DbConnect
                    .getUid(), DbConnect.getPwd());
            st = con.createStatement();
            rs = st.executeQuery(query);
            rsd = rs.getMetaData();
            DocRoot = dataDoc.createElement("StationaryDb");
            while (rs.next())
            {
                Element row = dataDoc.createElement("Stationary");
                for (int i = 0; i < rsd.getColumnCount(); i++)
                {
                    String colName = rsd.getColumnName(i);
                    String colType = rsd.getColumnTypeName(i);
                    System.out.println(colType);
                    String colValue = "";
                    if (colType.equals("String"))
                    {
                        colValue = rs.getString(i);
                    }
                    else if (colType.equals("int"))
                    {
                        colValue = rs.getInt(i) + "";
                    }
                    else if (colType.equals("float"))
                    {
                        colValue = rs.getFloat(i) + "";
                    }
                    else if (colType.equals("double"))
                    {
                        colValue = rs.getDouble(i) + "";
                    }
                    Element DataCol = dataDoc.createElement(colName);
                    DataCol.appendChild(dataDoc.createTextNode(colValue));
                    row.appendChild(DataCol);
                }
                DocRoot.appendChild(row);
            }
        }
        catch (ClassNotFoundException e)
        {
            // TODO Auto-generated catch block
            System.out.println("class");
            e.printStackTrace();
        }
        catch (SQLException e)
        {
            // TODO Auto-generated catch block
            System.out.println("sql");
            e.printStackTrace();
        }
        dataDoc.appendChild(DocRoot);
        System.out.println("The Result Set is written into XML File");
    }

Hey 500 means internal server error. please check the logs and then send the exact error/exceptions. 500 can occur due to n reasons.

The jsp passes a filename and the servlet reads data from the Database
and stores the result set data in the xml file (the file name is passed from the jsp page)

The servlet cannot find my xml file
and displays the following error while trying to execute the servlet

type Exception report
message
description The server encountered an internal error () that prevented it from fulfilling this request.

exception java.lang.NullPointerException aspire.controller.WriteXml.doPost(WriteXml.java:125) javax.servlet.http.HttpServlet.service(HttpServlet.java:709) javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
note The full stack trace of the root cause is available in the Apache Tomcat/5.5.20 logs.
Apache Tomcat/5.5.20

The below output appers in the console when the servlet is executed

java.io.FileNotFoundException: D:\Eclipse3.2\eclipse wtp\Sample.xml (The system cannot find the file specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
at sun.net.www.protocol.file.FileURLConnection.connect(Unknown Source)
at sun.net.www.protocol.file.FileURLConnection.getInputStream(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLEntityManager.setupCurrentEntity(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLVersionDetector.determineDocVersion(Unknown Source)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source)
at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(Unknown Source)
at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(Unknown Source)
at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(Unknown Source)
at javax.xml.parsers.DocumentBuilder.parse(Unknown Source)
at aspire.controller.WriteXml.doPost(WriteXml.java:49)
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:869)
at org.apache.coyote.http11.Http11BaseProtocol$Http11ConnectionHandler.processConnection(Http11BaseProtocol.java:664)
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)
sql
java.sql.SQLException: [Microsoft][ODBC SQL Server Driver][SQL Server]Invalid object name 'StationarRequest'.
at sun.jdbc.odbc.JdbcOdbc.createSQLException(Unknown Source)
at sun.jdbc.odbc.JdbcOdbc.standardError(Unknown Source)
at sun.jdbc.odbc.JdbcOdbc.SQLExecDirect(Unknown Source)
at sun.jdbc.odbc.JdbcOdbcStatement.execute(Unknown Source)
at sun.jdbc.odbc.JdbcOdbcStatement.executeQuery(Unknown Source)
at aspire.controller.WriteXml.doPost(WriteXml.java:74)
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:869)
at org.apache.coyote.http11.Http11BaseProtocol$Http11ConnectionHandler.processConnection(Http11BaseProtocol.java:664)
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)
Sep 24, 2007 9:14:32 AM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet WriteXml threw exception
java.lang.NullPointerException
at aspire.controller.WriteXml.doPost(WriteXml.java:125)
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:869)
at org.apache.coyote.http11.Http11BaseProtocol$Http11ConnectionHandler.processConnection(Http11BaseProtocol.java:664)
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)

i need to know where the xml file is to be placed so the servlet will be able to access it and write the data into it.

i have used FileOutputStream and PrintWriter to create a xml file

i am using eclipse and the file gets stored in the eclipse's bin directory

the jsp page passes a file name to a servlet

and the servlet uses the FileOutputStream and PrintWriter to write the data from
Result Set using the below code


protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//Document mapDoc;
//Document dataDoc=null;
String XmlFileName=request.getParameter("filename");
System.out.println(XmlFileName);
FileOutputStream fout;
PrintWriter pw;
response.setContentType("text/html");
PrintWriter out=response.getWriter();


fout=new FileOutputStream(XmlFileName);

pw=new PrintWriter(fout);

Connection con;
Statement st;
ResultSet rs;
ResultSetMetaData rsd=null;
//Element DocRoot=null;
String query="select * from StationaryRequest";
try {
Class.forName(DbConnect.getDriverName());
con=DriverManager.getConnection(DbConnect.getDsnName(),DbConnect.getUid(),DbConnect.getPwd());
st=con.createStatement();
rs=st.executeQuery(query);
rsd=rs.getMetaData();
// DocRoot=dataDoc.createElement("StationaryDb");// add a docu root
pw.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
out.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
pw.println("<StationaryDb>");
out.println("<StationaryDb>");
while(rs.next())
{
//Element row=dataDoc.createElement("Stationary");
pw.println("<Stationary>");
out.println("<Stationary>");
for(int i=1;i<=rsd.getColumnCount();i++)
{
String colName=rsd.getColumnName(i);
String colType=rsd.getColumnTypeName(i);
System.out.println(colType);

String colValue="";
if(colType.equals("varchar"))
{
colValue=rs.getString(i);
}
else if(colType.equals("int") ||colType.equals("statLogId"))
//here statLogId is a userdefined data type created in sql server
{
colValue=rs.getInt(i)+"";
}
else if(colType.equals("float"))
{
colValue=rs.getFloat(i)+"";
}
else if(colType.equals("double"))
{
colValue=rs.getDouble(i)+"";
}

//Element DataCol=dataDoc.createElement(colName);//write a columnname
pw.println("<"+colName+">");
out.println("<"+colName+">");

//DataCol.appendChild(dataDoc.createTextNode(colValue));//write a value to the column
pw.println(""+colValue+"");
out.println(""+colValue+"");

pw.println("</"+colName+">");
out.println("</"+colName+">");

//row.appendChild(DataCol); //adding the column to a row
}

//DocRoot.appendChild(row); // adding a row to a xml parent root
pw.println("</Stationary>");
out.println("</Stationary>");
}


} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
System.out.println("class");
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
System.out.println("sql");
e.printStackTrace();
}


//dataDoc.appendChild(DocRoot);
pw.println("</StationaryDb>");
out.println("</StationaryDb>");
pw.close();
fout.flush();
fout.close();
System.out.println("The Result Set is written into XML File");
}

r u using JDBC ODBC bridge for establishing Connection with MS SQL Server. If that's the case, then you need to modify ur web.xml file in WEB-INF folder. The Context tag should be something like the one given below:

<<Context docBase="Wims" path="/Wims" reloadable="true" source="org.eclipse.jst.j2ee.server:Wims">
      	<Resource name="jdbc/WimsDs" auth="Container" type="javax.sql.DataSource"
      		   factory="org.apache.tomcat.dbcp.dbcp.BasicDataSourceFactory"
               maxActive="100" maxIdle="30" maxWait="10000"
               username="" password="" driverClassName="sun.jdbc.odbc.JdbcOdbcDriver"
               url="jdbc:odbc:WimsDs"
               removeAbandoned="true"
               removeAbandonedTimeout="60"
               logAbandoned="true"/>
      </Context>

You'll have to replace the Wims with your Specific requirements. And you'll have to figure it out what you need to change. I was using javax.sql.DataSource here to connect to MS Access. If you're using DriverManager then probably you've to research more....

Also, you will require resource ref tags. Please put them in proper order otherwise some exception might occur.

<resource-ref>
		<res-ref-name>jdbc/WimsDs</res-ref-name>
		<res-type>javax.sql.DataSource</res-type>
		<res-auth>Container</res-auth>
		<res-sharing-scope>Unshareable</res-sharing-scope>
	</resource-ref>
This article has been dead for over six months. Start a new discussion instead.