java--servlet get resources in several ways

Source: Internet
Author: User

 Public classJservletextendsHttpServlet { Public voiddoget (httpservletrequest request, httpservletresponse response)throwsservletexception, IOException {//Web-inf under theString path1 = Getservletcontext (). Getrealpath ("/web-inf/demo.xml"); //Lib under theString path2 = Getservletcontext (). Getrealpath ("/web-inf/lib/demo.xml"); //SRC under theString path3 = Getservletcontext (). Getrealpath ("/web-inf/classes/demo.xml"); //under the Cn.itcast.servlet.servlet_context bag.String Path4 = Getservletcontext (). Getrealpath ("/web-inf/classes/cn/itcast/servlet/servlet_context/demo.xml"); //in fact, in the above example, Path3 and Path4 have some trouble in both ways//introducing a way to get resources is the application of the. Class ==> class and ClassLoaderInputStream is = This. GetClass (). getResourceAsStream ("Demo.xml");//If you do not add "/" ==> is relative to the current (package) directory of the classInputStream Is2 = This. GetClass (). getResourceAsStream ("/demo.xml");//if Add "/" ==> "/" On behalf of Classes directory (SRC)//in the next classLoader there are methods ClassLoader is the loader of the class. ==> specifically to read the input stream of the class file//It also provides a way to read other files. (use ClassLoader not to read larger files)//This.getclass (). getClassLoader () ==> get ClassLoader for classInputStream Is3 = This. GetClass (). getClassLoader (). getResourceAsStream ("/demo.xml");//regardless of "/", relative to the classes directory, the same as the "/" in the class of the relative path is the same. //You can also get the absolute path of the file using class or ClassLoaderURL url = This. GetClass (). GetResource ("Demo.xml");                    System.out.println (Url.getpath ()); }}

java--servlet get resources in several ways

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.