Can't access static file from Spring Boot application running in Tomcat servlet - spring-boot

All I want to do is access a specific file in a Java class. I am using Spring Boot 2.0.0.M7. When I run from my development machine using mvn spring-boot:run then everything works well. In that case I am using:
File jFile = new File("src/main/resources/static/folder/fileName.txt");
When I deploy this to a Tomcat server (8.5) as a war, the file is put into:
WEB-INF/classes/static/folder/fileName.txt
I've tried everything I could find or think of, but always get an error of some sort, usually a file not found exception.
My most recent attempt was:
URL url = this.getClass().getClassLoader().getResource("fileName.txt");
File jFile = new File(url.getPath());
That produces a null pointer exception with url.getPath().
I have read about needing to access the servlet config, but couldn't ever understand that well enough to get it to work. Does anyone have a clear example so that I can access the file both from the development context and the production context? Thanks!

Related

Web application throws NoClassDefFoundError in Unix server whereas locally in Eclipse it works properly

I'm newbee in web application deployment and stuff related to this. I have simple maven web application which works cool locally in my Eclipse & Tomcat9 server. Application has jsp file and main class, both try to call log4j2 classes like Logger or LogManager:
<% Logger.getLogger("bla").toString()%>
or in main:
private statis final Logger logger = LogManager.getLogger("blablabla");
Just in addition I call getPath() method on those classes and they show me my local maven repository.
After I deployed it on Unix server I get NoClassDefFoundError: Could not initialize class org.apache.logging.log4j.status.StatusLogger in browser and if I try to call it again I always get a bit different: NoClassDefFoundError: Could not initialize class org.apache.log4j.LogManager
Trying to execute main class through the PuTTY I get the same however after setting up a export CLASSPATH=$CLASSPATH:./WEB-INF/lib/* to the path with the libraries the program exetutes in console showing me enviroment CLASSPATH exactly as i've set before but continuing to not to work as web application through the browser.
I've tried to set CLASSPATH through the command above (startup.sh\setenv.sh etc...) but nothing. The command ...catalina.sh version shows me a CLASSPATH but app still doesn't work. I can only run a main class in PuTTY after manual setting up the CLASSPATH as I said above.
I've run out of ideas, probably you guys can give me some tips & hints about it? Maybe there is some script to set it each time starting the app. Unfortunatelly I'am not able to attache some code stuff.
The problem was related to the SecurityManager which was turned off on my local whereas it was turned on on a server. First I had simulated problem on my local, then I found out what permissions are missed debagging SecurityManager. I then added an VM argument -Djava.security.debug=access,failure to a run conf. Be carefull because of huge amount of output in console and better to log it in external txt file. After that I ran through the log.txt serching a word like "denied\failed\fail" and added necessary permission to a catalina.policy file.
Hope that will be helpfull for somebody.

On running spring boot war from cmd getting error resolving template exception in thymeleaf

On running the spring boot war file from the command line why I am getting the below error in thymeleaf :
Error resolving template, template might not exist or might not be accessible by any of the configured Template Resolvers.
I have changed the default thymeleaf template folder location using spring.thymeleaf.prefix property in application properties file. However, when I run the same code using IDEs it works perfectly fine.
Oh ok I got the issue, it was with the html file name which i was returning from my controller. I was using / with the file name (e.g. /index) because of which it was failing. But i am amazed that the IDEs are smart enough to detect that issue and somehow internally auto corrected it while running. That's why it was running via IDEs but failing while running the war from command line.

url after spring maven deployment

I have a basic question about deployment but I can't seem to find an answer on google...
I am working on a jakarta project and it's the first time I do the deployment.
Since I am using Spring-boot maven, I know there is an embedded tomcat that will launch with the jar.
My issue is, I don't know what url to use to check my project is working...
Before, I used the address http://localhost:9091/contextPath/endpoint, but now, I only get a whiteScreen...
So my question is, what url should I use ? Also, is there something else to do after packaging ?
Thank you for your answers.
EDIT:
Alright, so I tried actuator but that didn't help me...
With /actuator/mappings, I could see that my endpoints are correctly configured but when I use the executable jar, http://localhost:9091/contextPath/endpoint odes not work while it does if I compile with my IDE...
I don't know what url to connect to just to see the index... I'm using a very basic spring framework (boot and mvc) and my IDE is intellij community if this helps anyone
EDIT 2:
I tried to deploy the app on a local Tomcat9 to see if something would change but the connexion is reinitialized everytime I try to deploy a war using the manager, and there was no trace of error in the logs.
I tried using ./mvnw and it did work, endpoint and all, but it implies working with IDE environment
I tried using java (openjdk 13) and it compiled, but i couldn"t acces my own endpoint. I could still access the actuator endpoints so i don't know what to make of it.
Should the url be different depending on whether we are using IDE environment or just the jar?
EDIT 3:
Ok, I think have a lead but I have no idea how to resolve this:
when I began the web part of the application, I created a WEB-INF folder where I put all my jsp. My js and css files were in the resources/static folder. I tried once to put the jsp in the resources folder but it didn't work so I didn't push too hard.
Now, when I unzip the jar, i find my css and js files, but not my jsp.
When I unzip my war file, I have everything, but when I try to deploy it on a separate tomcat server, the connexion resets and I don't know why because nothing is written in the logs.
The issue then becomes:
Right now, I have
└──src
└──main
├──java
├──resources
| ├──static
| | ├──css
| | └──js
| └──template
└──webapp
└──WEB-INF
└──classes
└──jsp
What is the standard tree in intellij with jsp ?
By default Spring Boot apps are on port 8080.
Can you try http://localhost:8080?
Port can be changed in application.properties (or application.yml, application-profile.properties etc.) via server.port property (e.g. server.port=8888).
Ok, I managed to make it work.
I'm going to describe here everything of note that I encountered.
First, when I called my app to the usual url, there was no response (whiteLabel).
I added test logs and i found that I indeed called m controller.
I unzipped the jar and war i produced and came to the conclusion that the issue was architectural. I couldn't use jar, I had to use the war file.
I tried to deploy on a local tomcat server using the manager, but it always resetted the connection, so I took the manual approach - copy pasting the war file in the webapp directory.
Finally, the web pages were accessible in the browser.
Thank you for all the tips given during my research!
`http://endpoint:{PORT}/actuator/health` or `http://endpoint:{PORT}/actuator/status`
it should help but it must require spring-boot-actuator as a dependency in your pom/gradle file.

Tomcat Context Root - Tiles Exception when deploy a Spring app to Tomcat

I have a Spring MVC 4 application deployed in tomcat. It works fine. I have to clone this app to have several applications with same behaviour but different configurations: database instance and folders for file management. Each for different customers. When I deploy de original application to Linux Tomcat it works fine (https://hostname:8443/app1).
Then I change the db connection settings (database name, username, and folders to manage some generated files) and change the name of the artefact to customername. But when I get into the application, it shows the login page right, but when login into the app, I'm getting the following error:
Status HTTP 500 - Request processing failed; nested exception is org.apache.tiles.request.render.CannotRenderException: java.io.IOException: JSPException including path '/WEB-INF/layout/header.jsp'
javax.servlet.ServletException: File [/WEB-INF/layout/header.jsp] not found
when accessing to https://hostname:8443/customername, which it's part of tiles template. Files exist in the deployed application, It's able to reach the login page, so it seems to be resolved the tiles config, but I don't know why is not able to reach the jsp files. It's working fine in local windows without secure Tomcat (port 8080).
EDITED
If I change the name of customername.war to app1.war it's working fine. Anybody knows where the war file keep a reference to the base application app1? It seems that there a reference to app1 in somewhere that makes that If I change the application name (artifact id) it does not reference to customername path.
Seems that it's a context root issue. I have changed it in STS (Project > Properties > Web Project Settings > Context root), deployed on Tomcat but still not working. It's supposed that only with changing the war file name, the context root of the application should be updated, but it's not working.
Upgrading Tomcat from 8.0 to 8.5.5 solves the issue. I don't know why, but there's an issue in 8.0 because no way to force context root for an application, not context.xml application file neither other configuration.
Just upgrade to 8.5.5 and deploy applications without context issue.
BR

WAS Liberty not serving images, css, js

I have an application which is working fine on Websphere server (as war and Eclipse Project).
Direct deploy on Liberty through WAR is also working fine.
I was trying to deploy it on WAS Liberty through Eclipse project. There are no console errors but once the application loads, none of the following files are getting loaded in the web page: js, gif, css
Because of this the page is looking distorted and most of the functionality is lost.
Surprisingly there are some JSPs in the js folder and these are getting loaded, so looks like the folders are published properly. But for all the mentioned files (js etc), I get following error in the browser console: 500 (Internal Server Error) .
There are no errors and the server log is also clean.
My setup: WAS Liberty 8.5, RHEL 6.5. Eclipse Luna, WDT 8.5.5.2. Project having Eclipse structure, not maven.
I have tried both loose config and 'from workspace' settings
Edit1: I noticed that Spring beans are not getting initialized properly. Getting null pointer on applicationContext.getBean.
OK, found the problem.
As I guessed this was related to spring initialization, though the problem was more code related.
Due to wrong implementation of REST implementation, where the base path was set as root application path (“/”), rest API classes were getting instantiated on application load and were then making calls to code which was instantiating few Spring beans.
But at this point the Spring listeners had not fired, hence the appcontext was empty. Some of the base application object were getting initialized with empty beans and hence spring security context and related classes were failing to serve the application content properly. (Problem is spring related code is created by another team and we just get the jar, hence I am not even able to debug it properly, so I don't know where it was failing exactly)
The thing that makes it Liberty specific is: The same problematic code is working fine on Websphere full profile and Weblogic and even on Liberty if we deploy as WAR. Not sure what classloading difference is causing difference in behaviour.
Thanks to all who took time and efforts for replying.
I am facing the same issue using open liberty and Eclipse Krazo when the base path is
application path (“/”)
so i have changed the path as shown below
package io.openliberty.sample;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;
#ApplicationPath("")
public class ConfigApplication extends Application {
}
Now the CSS and imgs are loading with no issues.

Resources