开发者

How to get application context path in spring-ws?

I am using Spring-WS to create a webservice. In my project, I have created a Helper class to reads sample response and request xml file which are located in my /src/main/resource folder.

When I am unit-testing my webservice application 'locally', I use the System.getProperty("user.dir") to get the application context folder. The following is a method that I created in the Helper class to help me retrieve the file that I am interested in my resource folder.

 public static File getFileFromResources(String filename) {
  System.out.println("Getting file from resource folder");
  File request = null;
  String curDir = Syste开发者_运维问答m.getProperty("user.dir");
  String contextpath = "C:\\src\\main\\resources\\";
  request = new File(curDir + contextpath + filename);
  return request;
 }

However, after 'publishing' the compiled WAR file to the ../webapps folder to the Apache Tomcat directory, I realise that System.getProperty("user.dir") no longer returns my application context path. Instead, it is returning the Apache Tomcat root directory as shown

C:\Program Files\Apache Software Foundation\Tomcat 6.0\src\main\resources\SampleClientFile

I cant seem to find any information about getting the root folder of my webservice. I have seen examples on Spring web application where I can retrieve the context path by using the following :

request.getSession().getServletContext().getContextPath()

But in this case, I am using a Spring web application where there is a servlet context in the request. But the Spring-WS, my entry point is an endpoint. How can I get the context path of my webservice application.

I am expecting a context path of something like

C:\Program Files\Apache Software Foundation\Tomcat 6.0\webapps\clientWebService\WEB-INF\classes

Could someone suggest a way to achieve this?


You can get the current request from RequestContextHolder:

HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();

A bit clunky, but probably your best option here.


I don't think there are any guarantees that your application will actually be in a folder, or that your code will be permitted to explore arbitrary parts of the file system. Some application servers may not explode the war file, and the location of your application will actually be inside of the archive file itself.

You can, however, load any resource within the application itself, regardless where it is. ServletContext allows you to do that through javax.servlet.ServletContext#getResourceAsStream, for example. You can also find out the context path of the application there (as in the request path).

You can gain access to the servlet context by implementing org.springframework.web.context.ServletContextAware in your bean.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜