如何获得WebRoot中的资源,避免普通java项目转tomcat运行空指针异常

下面就是运行tomcat之后在浏览器输入访问地址后,eclipse控制台报错示意图。
在这里插入图片描述
解决办法:
1.在你需要获得相对资源路径的.java文件中的某个类或者某个方法下添加如下方法:

ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
	if (classLoader == null) {
    
    
	classLoader = ClassLoader.getSystemClassLoader();
    }
	java.net.URL url = classLoader.getResource("");
	String ROOT_CLASS_PATH = url.getPath() + "/";
	File rootFile = new File(ROOT_CLASS_PATH);
	String WEB_INFO_DIRECTORY_PATH = rootFile.getParent() + "/";
	File webInfoDir = new File(WEB_INFO_DIRECTORY_PATH);
	String SERVLET_CONTEXT_PATH = webInfoDir.getParent() + "/";
	//这里 SERVLET_CONTEXT_PATH 就是WebRoot的路径
	String path = SERVLET_CONTEXT_PATH ;
	System.out.println(path);

这里就能通过控制台的输出,而得到你的资源路径,我们得到的放在项目文件下,WebRoot目录下的path是:(注意控制台输出的是你的项目资源绝对路径,不要复制我的,复制你的路径即可)。

file:///D:/workspace/1811/ssm/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/movie_graph/

2.但是注意一点不能直接用改代码代替绝对路径,前面的file:///去掉,换成下面的路径。

D:/workspace/1811/ssm/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/movie_graph/

本人代码示意:

public static String xuanze_qusetions_path = "D:/workspace/1811/ssm/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/movie_graph/questionFile/选择题";

本人博客跳转链接:http://zhenyunboy.icu/?p=343

猜你喜欢

转载自blog.csdn.net/qq_34134299/article/details/109480955