StupidBeauty
Read times:2724Posted at: - no title specified

转载 Why does getRealPath() return null when deployed with a .war file?

ServletRequest.getRealPath(String path) 这个方法已经被废弃。在Java代码中,要想载入WAR里自带的某个文件的话,可使用ServletContext.getResourceAsStream。

http://stackoverflow.com/a/536260

亮点


23
down vote

For a start,  ServletRequest.getRealPath(String path)  is deprecated. The appropriate replacement is:

ServletContext context = session.getServletContext();

String realContextPath = context.getRealPath(request.getContextPath());

However, the API docs for  ServletContext.getRealPath(String path)  state:

"This method returns  null  if the servlet container cannot translate the virtual path to a real path for any reason (such as when the content is being made available from a .war archive)."

So the API is fulfilling its contract! However, all is not lost, as you can load a resource from the WAR using the following method, as defined in  ServletContext :

ServletContext context = session.getServletContext();

InputStream is = context.getResourceAsStream( "generate.xml" );

Your opinions

Your name:Email:Website url:Opinion content:
- no title specified

HxLauncher: Launch Android applications by voice commands