Get the unsafe relative path-get the classpath of the current class

Source: Internet
Author: User

This is an old topic. I have written an article to discuss this topic.

Http://blog.csdn.net/sunyujia/archive/2008/01/05/2027087.aspx

There are many methods to obtain relative paths, but there are not many security methods. What should I say?

Let me first describe the security of some popular methods.

Reprinted please indicate the source http://blog.csdn.net/sunyujia/

1. New file (./xx.txt); or new file(xx.txt );

This method is actually related to the window operating system. If you have research on batch processing and Win32 programming, you will know that running a program requires the operating system to know two points, 1 is the location where the file is stored, 2 is the start position of the file, this start position is very important, the file can be placed in C:/, and the start position can be D :/

If you are interested, try creating a new batch of test. bat.

  1. Dir
  2. Pause

Run it on drive C to list the directory of drive C.

Create a shortcut equation on the batch file, right-click it, and choose Properties> modify its starting position as disk D.

Click this quick equation to view the results. How can this problem be solved? List the directory of the d disk.

Therefore, using new file(xx.txt) in Java is very insecure, because where the path is depends on where the start position of the Java command is defined.

Catalina. bat calls Java, so in the Tomcat environment ". "The location is tomcat/bin, but the start position of the eclipse startup program is under the Eclipse project path. not to mention, we can see that this is not a good method. because a path cannot be determined by the location of the program.

Of course, this is not the case. The fully qualified hacker will want to upload % Cd % to JVM when java.exe is started. This is a method, but it is not too troublesome.

2. Class. Class. getclassloader (). getresource ("");

This is also a popular method, but it is unclear to use it to obtain the relative path, because in most cases we want the relative path to be fixed for our class. If we use this method, this gives the decision to the Class Loader. For example, Tomcat class loading is a non-commissioned mechanism, while WebLogic class loading is a delegated mechanism. This is the only reason for this decision, this method cannot guarantee that the relative path is actually relative to the class file in any environment. it is not safe, but in most cases it is safe. I thought it was safe for quite a while, and later I found it insecure in a complicated class loader environment in weblogic.

3. Class. Class. getresource ("")

It seems that this is indeed a good method, but its limitation is that if the class is in jar, you need to input the folder together when creating the jar package; otherwise, null is returned, jar files are actually ZIP files. In a zip file, the files are files and folders are not associated, many open-source jar packages do not include directories and only type the classes file. Although you can see the directory hierarchy of the file, you can call the class. class. getresource ("") returns NULL. because the directory structure of the file and the folder itself are two different. this question can be traced back to my previous post http://topic.csdn.net/u/20080520/21/1dc25316-8316-46f8-904b-ded9c4b7587a.html

As for the method for obtaining relative paths in Web applications, I will not mention it because of its limitations. Here I am talking about all the methods that can be used in any environment.

What is the safest way to get relative paths? The answer is to take the location of the file stored by the class itself in the system, and then find the classpath Based on the package hierarchy. The implementation is very simple. Well, let's not talk about the Code:

  1. Package com. syj. util;
  2. Import java. Io. file;
  3. Import java. Io. unsupportedencodingexception;
  4. Import java.net. url;
  5. /**
  6. * <P>
  7. * Title: URL auxiliary tool class
  8. * </P>
  9. *
  10. * <P>
  11. * Copyright: Reprinted please indicate the source http://blog.csdn.net/sunyujia/
  12. * </P>
  13. *
  14. * @ Author Sun Xiaojia
  15. * @ Main sunyujia@yahoo.cn
  16. * @ Date Sep 21,200 8 12:31:23 pm
  17. */
  18. Public class urlutil {
  19. /**
  20. *
  21. * Description: gets the file of the current class.
  22. *
  23. * @ Param clazz
  24. * @ Return
  25. * @ Mail sunyujia@yahoo.cn
  26. * @ Since: SEP 21,200 8 12:32:10
  27. */
  28. Public static file getclassfile (class clazz ){
  29. URL path = clazz. getresource (clazz. getname (). substring (
  30. Clazz. getname (). lastindexof (".") + 1)
  31. + ". Class ");
  32. If (Path = NULL ){
  33. String name = clazz. getname (). replaceall ("[.]", "/");
  34. Path = clazz. getresource ("/" + name + ". Class ");
  35. }
  36. Return new file (path. GetFile ());
  37. }
  38. /**
  39. *
  40. * Description: solves Chinese Encoding Problems with getclassfile.
  41. *
  42. * @ Param clazz
  43. * @ Return
  44. * @ Mail sunyujia@yahoo.cn
  45. * @ Since: SEP 21,200 8 1:10:12
  46. */
  47. Public static string getclassfilepath (class clazz ){
  48. Try {
  49. Return java.net. urldecoder. Decode (getclassfile (clazz)
  50. . Getabsolutepath (), "UTF-8 ");
  51. } Catch (unsupportedencodingexception e ){
  52. E. printstacktrace ();
  53. Return "";
  54. }
  55. }
  56. /**
  57. *
  58. * Description: gets the classpath directory of the current class.
  59. *
  60. * @ Param clazz
  61. * @ Return
  62. * @ Mail sunyujia@yahoo.cn
  63. * @ Since: SEP 21,200 8 12:32:27
  64. */
  65. Public static file getclasspathfile (class clazz ){
  66. File file = getclassfile (clazz );
  67. For (INT I = 0, Count = clazz. getname (). Split ("[.]"). length; I <count; I ++)
  68. File = file. getparentfile ();
  69. If (file. getname (). touppercase (). endswith (". Jar! ")){
  70. File = file. getparentfile ();
  71. }
  72. Return file;
  73. }
  74. /**
  75. *
  76. * Description: Same as getclasspathfile to solve Chinese Encoding Problems
  77. *
  78. * @ Param clazz
  79. * @ Return
  80. * @ Mail sunyujia@yahoo.cn
  81. * @ Since: SEP 21,200 8 1:10:37
  82. */
  83. Public static string getclasspath (class clazz ){
  84. Try {
  85. Return java.net. urldecoder. Decode (getclasspathfile (clazz)
  86. . Getabsolutepath (), "UTF-8 ");
  87. } Catch (unsupportedencodingexception e ){
  88. E. printstacktrace ();
  89. Return "";
  90. }
  91. }
  92. Public static void main (string [] ARGs) throws unsupportedencodingexception {
  93. System. Out. println (getclassfilepath (urlutil. Class ));
  94. System. Out. println (getclasspath (urlutil. Class ));
  95. }
  96. }

 

Run

The output is

D:/syj. Work/syj. workspace/WS1/util/classes/COM/syj/util/urlutil. Class
D:/syj. Work/syj. workspace/WS1/util/classes
Compress the package into a jar package and run it on the desktop.

The output is
File:/C:/Documents ents and settings/Administrator/desktop/util. Jar! /COM/syj/util/urlutil. Class
File:/C:/Documents ents and settings/Administrator/desktop

The obtained path is always the classpath directory of the class file.

You can perform tests in any class loading environment.

 

 

 

 

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.