首页 > 代码库 > 在web project里面如何读取XML文件

在web project里面如何读取XML文件

在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文件