从servlet检索值并存储在xml文件中

时间:2016-02-22 16:06:17

标签: java xml jsp servlets

我想将来自用户的信息存储到我的XML文件中。但是,我不知道我的代码有什么问题,它在java中运行得非常好,但是当涉及到JSP或Servlet时,它根本不起作用。真的需要帮助。

这是我的 form.jsp 代码

<%@ 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>

这是我的 xmlServlet.java 代码

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!");
    }
}

}

这是我的 user.java 代码

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

这是我的 xmlFile.xml 文件

<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
<root>
  <users>
    <user userId="user01">
      <name>Jane</name>
      <password>12345</password>
    </user>
  </users>
</root>

0 个答案:

没有答案