在web project裡面如何讀取XML檔案

來源:互聯網
上載者:User

標籤:style   http   color   java   os   io   檔案   for   ar   

在web proect裡面,context.getRealPath("/")可能返回了null,你可以輸入來看看,對一個打包的應用來說,是沒有RealPath的概念的,調用getRealPath只會簡單地返回null。其實,也很好理解,一個檔案被打包入了.war檔案,就不存在目錄結構了(雖然包中仍然存在目錄結構,但這不等同於檔案系統中的目錄結構)。所以,對war包中的資源是無法得到RealPath的。這樣也就無從通過檔案IO進行讀取了。

方法:

1.XML放在web Resource: webContent --->Web-INF----下面


2.HttpServlet下的代碼:


package org.platform.servlet;import java.io.File;import java.io.IOException;import java.io.InputStream;import java.net.URL;import java.util.Iterator;import java.util.Set;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.platform.jason.util.JasonUtil;import org.platform.token.AccessToken;import org.platform.xml.ServerConfiguration;/** * Servlet implementation class MenuLoader */@WebServlet("/MenuLoader")public class MenuLoaderServlet extends HttpServlet{private static final long serialVersionUID = 1L;/** * @see HttpServlet#HttpServlet() */public MenuLoaderServlet(){super();// TODO Auto-generated constructor stub}/** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse *      response) */protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException{<span style="color:#990000;">ClassLoader classLoader = this.getServletContext().getClassLoader();java.net.URL url = classLoader.getResource("actionlist.xml");ServerConfiguration.parseXml(url)</span>;}/** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse *      response) */protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException{}}public class ServerConfiguration{    public static void parseXml(URL path)    {        ActionList action = new ActionList();        SAXReader reader = new SAXReader();        Document doc = null;        try        {            doc = reader.read(path);        } catch (DocumentException e)        {            e.printStackTrace();        }       //拿到根節點後,想怎麼做都可以了        Element root = doc.getRootElement();         }} 


在web project裡面如何讀取XML檔案

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.