为了账号安全,请及时绑定邮箱和手机立即绑定

用Jdom向web.xml添加节点出错

用Jdom向web.xml添加节点出错

Smart猫小萌 2019-03-15 14:15:41
想通过Jdom向web.xml文件添加servlet的配置信息。如:xxxcom.sdt.action.xxxxxx/xxx但是总是报这样的错误:Exception in thread "main" org.jdom.IllegalAddException: The Content already has an existing parent "servlet"我的代码如下:[code="java"]import java.io.File;import java.io.FileOutputStream;import org.jdom.Document;import org.jdom.Element;import org.jdom.Parent;import org.jdom.input.SAXBuilder;import org.jdom.output.XMLOutputter;/**向web.xml中增加Servlet配置*@author liujia*/public class DomUtil {public static void add(String tableName) throws Exception {String className = "PersonServlet" ;String servletPackage = "com.sdt.servlet" ;String fileName = "d:/netbeans/workday01/src/test/javaeye/web.xml" ; File f = new File(fileName) ; SAXBuilder builder = new SAXBuilder() ; Document doc = builder.build(f) ; Element root = doc.getRootElement() ; System.out.println("root: " + root.getName()); Element servlet = new Element("servlet") ; Element servletMapping = new Element("servlet-mapping") ; Element servletName = new Element("servletName") ; Element servletClass = new Element("servletClass") ; Element urlPattern = new Element("urlPattern") ; servletClass.setText(servletPackage + "." + className) ; servletName.setText("className") ; urlPattern.setText("/" + className) ; servlet.addContent(servletName) ; servlet.addContent(servletClass) ; servletMapping.addContent(servletName) ; servletMapping.addContent(urlPattern) ; Parent p = root.getParent(); p.removeContent(root); root.addContent(servlet) ; root.addContent(servletMapping) ; XMLOutputter out = new XMLOutputter() ; out.setFormat(out.getFormat().setEncoding("GBK")) ; out.output(doc, new FileOutputStream(new File(fileName),true)) ;}public static void main(String[] args) throws Exception {add("t_person") ;}}希望大家能帮帮我,实在是解决不了了。
查看完整描述

2 回答

?
守候你守候我

TA贡献1802条经验 获得超10个赞

第26行代码 Element servlet = new Element("servlet") ;

servlet节点不能共享,只能是一个节点的子节点,不能即是a节点的子节点又是b节点的子节点
也就是说解决你的问题在于
第38行代码
servletMapping.addContent(servletName) ;

处修改为
servletMapping.addContent( new Element("servletName")) ;

另外42行处
p.removeContent(root);

干什么吧根节点给删除了?
如果跟节点删除了,没有根节点
那么document就不完整了,你后面也没有显示的增加,所以,是你的思路的问题;再好好的整理一下!


查看完整回答
反对 回复 2019-04-26
?
慕标琳琳

TA贡献1830条经验 获得超9个赞

楼主竟然运行时改web.xml?
我out了 还是楼主碉堡了 :oops:

查看完整回答
反对 回复 2019-04-26
  • 2 回答
  • 0 关注
  • 604 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信