How to get the resources in WebRoot to avoid the null pointer exception when normal java project is transferred to tomcat

The following is a schematic diagram of the eclipse console reporting an error after entering the access address in the browser after running tomcat.
Insert picture description here
Solution:
1. Add the following method under a certain class or method in the .java file that you need to obtain the relative resource path:

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);

Here you can get your resource path through the output of the console. We put it under the project file. The path under the WebRoot directory is: (Note that the output of the console is the absolute path of your project resource. Don’t copy mine. , Just copy your path).

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

2. But note that you cannot directly replace the absolute path with the modified code. Remove the file:/// in front and replace it with the following path.

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

My code hint:

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

My blog jump link: http://zhenyunboy.icu/?p=343

Guess you like

Origin blog.csdn.net/qq_34134299/article/details/109480955