Core Java| JSP| Servlets| XML| EJB| JEE5| Web Services| J2ME| Glossary| Questions?

 

 

 

 

 

 

 

 

 

 

 

 

 

Search Tutorials

Latest Questions
Comments
 
Stored Data in XML File using Servlet 
 

In this section, you will learn how to stored data in xml file using Servlet We have created file login.jsp,XmlServlet.java.

 

Stored Data in XML File using Servlet

                         

In this section, you will learn how to stored data in xml file using Servlet  We have created  file login.jsp,XmlServlet.java. User details in the "login.jsp" are to be stored in xml file. It creates XML file with its version and encoding and display a message 'Xml File Created Successfully'.  

JAXP (Java API for XML Processing) is a Java interface that provides a standard approach to Parsing XML documents. With JAXP, we will use the Document BuilderFactory to create DocumentBuilder class. The class DocumentBuilderFactory is responsible for creating new DOM . 

 DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
 DocumentBuilder docBuilder = builderFactory .newDocumentBuilder();


DocumentBuilderFactory is used to find the class to load.

The instance of the class DocumentBuilder is used to create a blank document. 

Document doc = docBuilder.newDocument();

Step 1: Create a web page  "login.jsp"

<html>
<head>
</head>
<body>
<br>
<br>
<form name="loginform" method="post" action="xmlServlet">
<table align="center" style="border:1px solid #000000;" bgcolor="#efefef">
<tr>
<td colspan=2 align="center" style="font-weight:bold;">UserLogin</td>

</tr>
<tr>
<td>User Name</td>
<td><input type="text" name="username" value=""></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="password" value=""></td>
</tr>

<tr>
<td></td>
<td><input type="submit" name="Submit" value="Save"></td>
</tr>
</table>
</form>
</body>
</html>

 

Step 2:Create a  Servlet "XmlServlet.java". 

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

import java.io.*;
import org.w3c.dom.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;  

public class XmlServlet extends HttpServlet
  public void doPost(HttpServletRequest request, HttpServletResponse response)
                                   throws ServletException,IOException{
    response.setContentType("text/html");
    PrintWriter pw = response.getWriter();
  String username="";
  String password="";

  if(request.getParameter("username")!=null && request.getParameter("password")!=null)
    {
           username = request.getParameter("username").toString();
       password = request.getParameter("password").toString();
    }
  try
  {
    DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = builderFactory.newDocumentBuilder();
        //creating a new instance of a DOM to build a DOM tree.
        Document doc = docBuilder.newDocument();
        new XmlServlet().createXmlTree(doc,username,password);
    
    pw.println("<b>Xml File Created Successfully</b>");
  }
  catch(Exception e)
  {
    System.out.println(e);
  }
     
  }

  public void createXmlTree(Document doc,String userid,String passwordthrows Exception {
        //This method creates an element node
        Element root = doc.createElement("User");
        //adding a node after the last child node of the specified node.
        doc.appendChild(root);

       

        Element child1 = doc.createElement("UserId");
        root.appendChild(child1);

        Text text = doc.createTextNode(userid);
        child1.appendChild(text);

       

        Element element = doc.createElement("Password");
        root.appendChild(element);

        Text text1 = doc.createTextNode(password);
        element.appendChild(text1);

       
       
     //TransformerFactory instance is used to create Transformer objects. 
        TransformerFactory factory = TransformerFactory.newInstance();
        Transformer transformer = factory.newTransformer();
       
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");

        // create string from xml tree
        StringWriter sw = new StringWriter();
        StreamResult result = new StreamResult(sw);
        DOMSource source = new DOMSource(doc);
        transformer.transform(source, result);
        String xmlString = sw.toString();

        File file = new File("c:/loginXml.xml");
        BufferedWriter bw = new BufferedWriter
                      (new OutputStreamWriter(new FileOutputStream(file)));
        bw.write(xmlString);
        bw.flush();
        bw.close();
      
    }
}

 Step 3:Create a  web.xml for mapping Servlet "XmlServlet.java". 

<?xml version="1.0" encoding="ISO-8859-1"?>

<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">

<display-name>Welcome to Tomcat</display-name>
<description>
Welcome to Tomcat
</description>
<servlet>
<servlet-name>xmlservlet</servlet-name>
<servlet-class>XmlServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>xmlservlet</servlet-name>
<url-pattern>/xmlServlet</url-pattern>
</servlet-mapping>

</web-app>


Output :

"login.jsp"

 

After creating "loginXml.xml" successful message display.


 

"loginXml.xml" 

Download the full source code

 

                         

» View all related tutorials
Related Tags: c ide orm table data form io make type column field name columns change this id nsis war tab row

Leave your comment:

Name:

Email:

URL:

Title:

Comments:


Enter Code:

Audio Version
Reload Image
 

Note: Emails will not be visible or used in any way, and are not required. Please keep comments relevant. Any content deemed inappropriate or offensive may be edited and/or deleted.

No HTML code is allowed. Line breaks will be converted automatically. URLs will be auto-linked. Please use BBCode to format your text.

Add This Tutorial To:
  Del.icio.us   Digg   Google   Spurl   Blink   Furl   Simpy   Y! MyWeb 
Training Courses
Tell A Friend
Your Friend Name
Software Solutions
Least Viewed
Most Rated
Recently Viewed
Search Tutorials

 

 
 

Home | JSP | EJB | JDBC | Java Servlets | WAP  | Free JSP Hosting  | Search Engine | News Archive | Jboss 3.0 tutorial | Free Linux CD's | Forum | Blogs

About Us | Advertising On RoseIndia.net  | Site Map

India News

Indian Software Development Company | iPhone Development Company in India | Flex Development Company in India | Java Training Delhi | Java Training at Noida |

Send your comments, Suggestions or Queries regarding this site at roseindia_net@yahoo.com.

Copyright © 2008. All rights reserved.