Java – how to access the webcontent folder from the web service method

I want to reach the file in the webcontent folder from the method in the web service in the same project For example:

@WebMethod
public String test() {
     File configFile = new File("config.xml");
     return configFile.getAbsolutePath();
}

It returns "/ usr / share / glassfish3 / GlassFish / domains / domain1 / config / config. XML" I think of the files in the directory "/ usr / share / glassfish3 / GlassFish / domains / domain1 / applications / my_project_name /" How can I do that?

Solution

Add the following parameters to the web service class:

@Context
ServletContext context;

Then, suppose your config The XML file is located in the webcontent folder, and you can call the method context Getrealpath (string) to get its absolute path Using your sample code would be:

@WebMethod
public String test() {
     File configFile = new File(context.getRealPath("config.xml"));
     return configFile.getAbsolutePath();
}

Or directly, without passing through the file object:

@WebMethod
public String test() {
     return context.getRealPath("config.xml");
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>