1

I want to store information gets from user into my XML file. But, I don't know what's wrong with my code, it works perfectly well in java but when it comes to JSP or Servlet it doesn't work at all. Really need help.

Here is my form.jsp code

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
  <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  <html>

  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Insert title here</title>
  </head>

  <body>
    <form action="xmlServlet" method="POST">
      name :
      <input type="text" name="name">password :
      <input type="password" name="pword">
      <button type="submit">Create</button>
    </form>
  </body>

  </html>

Here is my xmlServlet.java code

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/xmlServlet")
public class xmlServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

public xmlServlet() {
    super();
}

protected void doPost(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {

    PrintWriter prt = response.getWriter();
    String name = request.getParameter("name");
    String password = request.getParameter("pword");
    if (user.create(name, password)) {
        prt.println("well done!");
    } else {
        prt.println("error!");
    }
}

}

Here is my user.java code

import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class user {
public static boolean create(String name, String pword) {
    try {
        String filepath = "WebContent\\xmlFile.xml";
        DocumentBuilderFactory docFactory = DocumentBuilderFactory
                .newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
        Document doc = docBuilder.parse(filepath);

        // get users element
        Node users = doc.getElementsByTagName("users").item(0);

        // append a new node to users
        Element user = doc.createElement("user");
        user.setAttribute("userId", "user11");
        users.appendChild(user);

        // loop the users child node
        int counter = 0;
        NodeList list = users.getChildNodes();
        for (int i = 0; i < list.getLength(); i++) {
            Node node = list.item(i);
            if ("user".equals(node.getNodeName())) {
                counter++;
            }
        }
        System.out.println("users node: " + list.getLength());
        System.out.println("user last index: " + counter);
        // get user element
        Node userEle = doc.getElementsByTagName("user").item(counter - 1);

        // append a new node to user
        Element nameEle = doc.createElement("name");
        nameEle.appendChild(doc.createTextNode(name));
        userEle.appendChild(nameEle);

        // append a new node to user
        Element password = doc.createElement("pword");
        password.appendChild(doc.createTextNode(pword));
        userEle.appendChild(password);

        // write the content into xml file
        TransformerFactory transformerFactory = TransformerFactory
                .newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        DOMSource source = new DOMSource(doc);
        StreamResult result = new StreamResult(new File(filepath));
        transformer.transform(source, result);

        System.out.println("Done");
        // user has been created
        return true;

    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}
// I test using this and it works
public static void main(String[] args){
 System.out.println(user.create("A", "x"));
}
}

Here is my xmlFile.xml File

<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
<root>
  <users>
    <user userId="user01">
      <name>Jane</name>
      <password>12345</password>
    </user>
  </users>
</root>
soulivong
  • 139
  • 1
  • 3
  • 10
  • what is failing that you do not anticipate failing? Also, I am pretty sure you are missing a return statement outside of the try / catch block – angryip Feb 22 '16 at 16:14
  • Note, I ran your param getting from the servlet, and it is working just fine on my machine, with the same jsp code you use. – angryip Feb 22 '16 at 16:14
  • @angryip you are right I don't have a return statement outside the try / catch, so what should it return true or false – soulivong Feb 22 '16 at 16:35
  • what you can do is place a variable in the first line of the create method: `boolean created = false`, remove `return false from the cath block`, and set the `return true` to `created = true`; last line, of the method, `return created` – angryip Feb 22 '16 at 16:38
  • added code to show you what i meant – angryip Feb 22 '16 at 16:41
  • it's still display "error from xmlServlet and haven't inserted the value to xml File.xml – soulivong Feb 22 '16 at 16:43
  • where is that error triggered from? what is generating that message? I do not see in the code where it can be geenrated – angryip Feb 22 '16 at 16:45
  • yes, it's just my code to see the output hereif (user.create(name, password)) { prt.println("well done!"); } else { prt.println("error!"); } – soulivong Feb 22 '16 at 16:48

0 Answers0