1. First, if it is in a controller method, it is very simple, use the following statement directly.
1@RequestMapping ("Categoryhome")2 PublicModelandview categoryhome (Parammodel pm,httpservletrequest req) {3String path=Req.getservletcontext (). Getcontextpath ();4 System.out.println (path);5String Realpath=req.getservletcontext (). Getrealpath ("/uploadfile");6 System.out.println (realpath);7Modelandview mv =NewModelandview ("Back/category/categoryhome");8Mv.addobject ("PM", PM);9 returnMV;Ten}
Lines 2nd and 5th get the Absolute directory of the project's root directory and/uploadfile, respectively, and print as follows.
2. Another way is to configure the following code in Web. xml
< Context-param > < Param-name >webapprootkey</param-name> < Param-value>www.qgranite.com</param-value>< /context-param>
Then in the Java code we can get the absolute path.
String BasePath = System.getproperty ("www.qgranite.com");
System.out.println ("BasePath:" +basepath);
The printing results are as follows:
3. When we are not in the Controller method, want to get the absolute path, in fact, is also possible, referring to the first method, we just have to obtain the SERVLETCONTEXTJ can be, can use the following method curve save the nation.
Webapplicationcontext webapplicationcontext = contextloader . Getcurrentwebapplicationcontext (); = Webapplicationcontext . Getservletcontext (); // get the file absolute path String Realpath = Servletcontext.getrealpath ("/uploadfile"); System.out.println ("Realpath:" +realpath);
Print out the results
Several ways to get absolute paths from spring MVC