3

Am working on spring boot applicaiton. I want to write a jsp files dynamically into the web content. So i took the real path from the ServletContext and write into it. It is working fine in eclipse.

@autowired
ServletContext context 

or

ServletContext context = request.getSession().getServletContext();
String targetPath = context.getRealPath("/default/pages");

But I try to deploy a war file on linux machine, the path is empty. Please help me to fix this or let me know if it possible to do ?

spring boot embedded tomcat
Shankar
  • 143
  • 2
  • 10
  • Correct me if I am wrong, but the "/" sign means root directory of the whole system. String is trying to find "/default/pages" from the root. So may be try classpath: ? – RedCollarPanda Jul 02 '17 at 15:18
  • classpath will have java files only right. I want to write into the webcontents. getRealPath("/default/pages") @RedCollarPanda – Shankar Jul 02 '17 at 15:20
  • Any file access permissions? Can you check them? – RedCollarPanda Jul 02 '17 at 15:22
  • using as root user only. having all permission @RedCollarPanda – Shankar Jul 02 '17 at 15:34
  • There are many similar questions on situations when `getRealPath` does not work here on SO. Please check other questions and answers. Also you did not specify your application server / servlet container. AFAIK the real path does not work if your servlet container does not unpack the WAR (i.e. you can not get real path for files inside a WAR). – Pavel Horal Jul 02 '17 at 15:47
  • am using spring boot embedded tomcat @PavelHoral – Shankar Jul 02 '17 at 15:52
  • So you are packing everything inside JAR. No support for real path there. `getRealPath` should return file system path for the resource, but no path can represent file inside JAR archive. Maybe ask a different question with your actual goal (what are you trying to achieve). – Pavel Horal Jul 02 '17 at 15:53
  • I want to dynamically add HTML, CSS and JS inside the WAR on run time and access it on run time itself. @PavelHoral – Shankar Jul 02 '17 at 16:13
  • Then you probably need to have a separate folder for that. I don't think it is possible (at least not easily achievable) to modify JAR on the fly. – Pavel Horal Jul 02 '17 at 17:55

1 Answers1

1

There are lots of reasons not to rely on getRealPath() in real-world deployments. There are several better approaches, depending on your use-case; but the one that worked best for me was to use a file path from the application.properties file using @Value

Black
  • 5,023
  • 6
  • 63
  • 92