Java 实例 - 获取web.xml文件中的信息

XMLUtil运行文件
public class XMLUtil {
    public static void main(String[] args) {
        String IP = XMLUtil.getIpName(); //读取配置文件中的参数
        System.out.println(IP);
        String url = "http://" + IP + "/cc/json/mobile_tel_segment.htm?tel=13026194071";
        System.out.println(url);
    }
    public static String getIpName() {
        try {
            //创建文档对象
            DocumentBuilderFactory dFactory =  DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = dFactory.newDocumentBuilder();
            Document doc;
            String cName=null;
       //文件web.xml的绝对路径
            doc = builder.parse(new File("web.xml文件的绝对路径"));
            //获取包含类名的文本节点
            //获取包含图表类型的文本节点
            NodeList nl = doc.getElementsByTagName("IpName");
            //通过设置不同的参数即可得到不同类型的图表
            Node classNode = nl.item(0).getFirstChild();
            String chartType = classNode.getNodeValue().trim();
            return chartType;
        }
        catch(Exception e) {
            e.printStackTrace();
            System.out.println("执行失败,请检查web.xml中是否有对应参数名称");
            return null;
        }
    }
}

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<config>
    <IpName>192.168.24.123</IpName>
</config>

 

posted @ 2021-11-01 14:43  岁月记忆  阅读(288)  评论(0)    收藏  举报