Several ways to get absolute paths from spring MVC

Source: Internet
Author: User

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

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.