Thymeleaf +Spring Boot can't find files (FileNotFoundException) - spring-boot

This is a bit of a silly and frustrating one:
The #Configuration is taken from a tutorial website or forum and in it a
ServletContextTemplateResolver thymeleafTemplateResolver
is created using the ServletContext provided by spring boot.
When requested, a FileNotFoundException is thrown, despite the file being in the configured resources folder.
How do I get it to find the file / load it from the resources?

For thymeleaf to resolve the classpath resources, you need to configure a ClassLoaderTemplateResolver. (You were using a ServletContextTemplateResolver)
Also check that setPrefix is set to the correct folder, eg. "/thymeleaf/" if your documents are in resources/thymeleaf/ and that setSuffix is set to ".html" (or whatever your preferred file suffix is)
To also serve static content, you can extend WebMvcConfigurer and override addResourceHandlers, to then do e.g.
registry.addResourceHandler("/**").addResourceLocations("classpath:/static/");
assuming a static folder in your resources.
(Spring controllers take precedence here)

Related

spring boot app cannot load bundle properties files

I am building an app that mostly provide REST services, nothing fancy. since my data consumed by the app can have multiple languages I thought about using the bundle files.
I created 3 files, one with the default file name and another two with specific languages. The files created using intellij IDE I am using.
I followed this guide https://www.baeldung.com/java-resourcebundle however on each run I am getting:
MissingResourceException: Can't find bundle for base name tp_app_strings, locale en_US
I tried numerous articles but none of them seems to resolve the issue.
One fun fact is that if I am using the #Value("classpath:tp_app_strings.properties") on a 'Resource' field I am able to get a reference to that file, so it spring is able to find it.
Additional thing that I tried was to create a WEB-INF directory and place the files there (read it in some article) but still no positive affect
The project structure is quite straight forward:
Spring boot version 2.2 running tomcat.
Any suggeestions would be highly appriciated
You can load the .properties file to the application context using #PropertySource annotation instead using #Value to load the .properties file to a org.springframework.core.io.Resource instance.
The usage;
#Configuration
#PropertySource("classpath:tp_app_strings.properties")
public class DefaultProperties {
#Value("${property1.name}") // Access properties in the above file here using SpringEL.
private String prop1;
#Value("${property2.name}")
private String prop2;
}
You wouldn't need java.util.ResourceBundle access properties this way. Use different or same class to load other .properties files as well.
Update 1:
In order to have the functionality of java.util.ResourceBundle, you can't just use org.springframework.core.io.Resource class. This class or non of it sub-classes don't provide functions to access properties by its name java.util.ResourceBundle whatsoever.
However, if you want a functionality like java.util.ResourceBundle, you could implement something custom like this using org.springframework.core.io.Resource;
#Configuration
public class PropertyConfig {
#Value("classpath:tp_app_strings.properties")
private Resource defaultProperties;
#Bean("default-lang")
public java.util.Properties getDefaultProperties() throws IOException {
Properties props = new Properties();
props.load(defaultProperties.getInputStream());
return props;
}
}
Make sure to follow correct naming convention when define the property file as java.util.Properties#load(InputStream) expect that.
Now you can #Autowire and use this java.util.Properties bean wherever you want just like with java.util.ResourceBundle using java.util.Properties#getProperty(String) or its overloaded counterpart.
I think it's problem of you properties file naming convention. use underline "_" for specifying locale of file like
filename_[languageCode]_[regionCode]
[languageCode] and [regionCode] are two letters standard code that [regionCode] section is optional
about code abbrivation standard take a look on this question
in your case change file name to tp_app_strings_en_US.properties

How to integrate Sitemap.xml and Robot.txt files generated from free online source to Spring Boot Application

"I have Sitemap.xml and Robot.txt files generated from free online sources, and I want to integrate those with my Spring Boot Application" and want to access that as http://localhost:8080/Sitemap.xml.
Previously I work with Struts 2.x. where I usually drop those files in JSPs folder and I able to access that as http://localhost:8080/Sitemap.xml.
But here in Spring Boot Application, I am totally confused in adding them to Application. (My Doubts are listed Below).
In which folder I need to add these files?
2.Does it need any controller to access Sitemap.xml as http://localhost:8080/Sitemap.xml.
Help me in Sorting out this.
Thanks in Advance.
Added Sitemap.xml and Robot.txt under static folder, but no use of that.
you can add these files under public folder in src/main/resources.
For more info refer this.
Also, if you have security configuration then you need to modify as below:
#Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/Sitemap.xml");
}

How to push external xml file into spring boot embedded tomcat continer

i have created springboot project which gives fat-jar. i want to push external xml file in runtime into it.i want to place that xml file into spring-boot-tomcat container. tried many ways to do it (#import, --spring.config.location,etc) those ways didn't work out for me.
That xml file is ApplicationInsight.xml, which is used to post telemetry from our application to Azure portal.
Highly appreciate any help.
Based on the GitHJub issue, I think part of the problem is how you are passing JVM parameters, and how you are using "spring.config.location".
I am not familiar with Azure Insights really, but if I understand correctly, it is trying to load the ApplicationInsights.xml file to configure itself, and it's doing this automatically. So you really can't set it up in the WebConfigurerAdapter as I previously suggested because it has already initialized itself before that, correct? I left that part in anyways, but I get that it needs to be loaded sooner so I provided a few additional ways to add the file to the classpath ASAP.
New Stuff
First take a look at this line you had originally posted ala GitHub:
java -jar build/libs/file-gateway.jar --spring.config.location=classpath:/apps/conf/ApplicationInsight.xml
Instead the value should be just a folder path, without "classpath" of "file" prefix. Also, try using '-D' instead of '--'.
java -jar build/libs/file-gateway.jar -Dspring.config.location=/apps/conf/
The property is supposed to either refer to a directory containing auto configuration property files for Spring Boot. It can also work for referring to a specific "application.properties|yml" file.
With that, my previous suggestion may work for you.
Old Suggestion
If you require a unique way for loading resources, you can add a resource handler to your application.
#Configuration
#EnableWebMvc
public class MvcConfig extends WebMvcConfigurerAdapter {
#Value("${telemetry.folder}")
private String telemetryFolder;
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry
.addResourceLocations(telemetryFolder);
}
}
And/or you could load it with apache IO:
#Value("${telemetry.file}")
private String telemetryFile;
#Autowired
private ResourceLoader resourceLoader;
public String telemtryXml(){
return org.apache.commons.io.IOUtils.toString(resourceLoader.getResource(telemtryFile).getInputStream());
}
But this will only work if the api you are using doesn't need to be initialized much earlier.
More New Stuff
In your last post on the GitHub issue, you tried this:
java -jar build/libs/file-gateway.jar -applicationinsights.configurationDirectory="/apps/conf/"
Instead, try adding the property as a jvm parameter like this:
java -jar build/libs/file-gateway.jar -Dapplicationinsights.configurationDirectory=/apps/conf/
Notice that I added a capital 'D' character after the, and I removed the quotes from the path.
Other ways to add the file to classpath are.
Add the directory to the JVM classpath.
java -cp "build/libs/file-gateway.jar:/apps/conf/*" your.package.MainSpringBootApplication
This requires that you specify the main class which is (commonly) annotated with '#SpringBootApplication' and contains the main method. You do not execute the jar like before, but you do still add it to the classpath.
Forget about SpringBoot, and go back to your roots as a JEE developer. Add a "context.xml" for your app under the "src/main/resources/META-INF" folder, or "src/main/webapp/META-INF". I prefer the later if I'm building an executable war file, and the former for jars.
Example context.xml:
<?xml version='1.0' encoding='utf-8'?>
<!-- path should be the context-path of you application.
<Context path="/">
<Resources className="org.apache.catalina.webresources.StandardRoot">
<PreResources base="/apps/conf"
className="org.apache.catalina.webresources.DirResourceSet"
internalPath="/"
webAppMount="/WEB-INF/classes"/>
</Resources>
</Context>
You can also use JVM parameters with EL.
So if you execute the jar with this:
java -jar build/libs/file-gateway.jar -Dapplicationinsights.configurationDirectory=/apps/conf/
You could set the resources base with this:
<!--snip -->
<PreResources base="${applicationinsights.configurationDirectory}"
<!--snip -->
Hope that helps:)

Thymeleaf: can't load js and css when direct access the page

Updated: to describe the question more clearly
I create a web applicaiton with spring boot and thymeleaf, everything works fine if I open the login page, then login, then head for the management module or reports module sequently.
The proleam occurs when I type the url locahost:8080/send/kf/index(needs to authenticate, but I have open access to all in customized filter) in the browser, the page loads without js and css. In debug mode, I saw /send/kf was unexpectly put into the path like the following. I can get the resource if I access localhost:8080/assets/avatars/avatar.png.
The following is the folder structure I put my static resources. How could /send/kf automatically added into the url, please help me solve this problem. Thanks!
you can use spring.resources.static-locations in your application.properties file
spring.resources.static-locations=classpath:/resources/css/
spring.mvc.static-path-pattern=/resources/**
this is taken form documentation
Note:Static resources, like JavaScript or CSS, can easily be served from your Spring Boot application just be dropping them into the right place in the source code. By default Spring Boot serves static content from resources in the classpath at "/static" (or "/public")
Using /assets/ instead of assets/ fixes the issue, as otherwise it's a relative url that's supposed to get added to the end of existing url.
I find a solution for this question. I don't know how /send/kf is put into the url for the static resources, but I think if I put the controller mapping under the root path, this problem should avoid. As I think, the url is correct and resources can load successfully.
#Controller
public class ManualMessageController {
#Autowired
private MsgTemplateRepository msgTemplateRepository;
#RequestMapping("/manualMsg")
public String manualMsg(Model model){
model.addAttribute("msgTemplateList", msgTemplateRepository.findByStatus(1));
return "manualMessage";
}
}
updated:
The right solution is to use absolute path rather than relative path in the project. So change assets/css to /assets/css works.

How to change the way Spring Boot serves static files?

After using JHipster on a couple of new projects recently (Highly recommended ! Amazing work !), I am trying to back-port some of the concepts into an older webapp, essentially migrating it to Spring Boot and Angular.
In Spring Boot, the default location for static web resources (HTML, JS, CSS, etc.) is in a directory called public, static or resources located at the root of the classpath. Any of these directories will be picked up by spring boot and files in them will be accessible via HTTP.
In JHipster the web files are in the src/main/webapp directory. Which is the directory used by default in a classic Maven WAR project.
I like this better because :
it more clearly separates the static web stuff from the classpath resources used by the Java code
the nesting is less deep (we already have enough levels of directories nesting with Maven as it is!).
But if I just create webapp directory in my project and put my HTML files in it, they are not available via HTTP, and the build process creates the WEB-INF directory structure in it. I don't want that, and in JHipster this is not the case.
How can I configure Spring Boot to behave like it does in JHipster ?
For those not familiar with JHipster : How can I instruct Spring Boot to serve static files from a different folder, no included in the classpath ?
You can try following configuration. The idea should be pretty straight forward. It does register artifacts in assets directory.
public class AppMvcConfiguration extends WebMvcConfigurerAdapter {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
// Including all static resources.
registry.addResourceHandler("/assets/**",
"/css/**",
"/img/**",
"/js/**"
).addResourceLocations("/assets/",
"/css/",
"/img/",
"/js/"
).resourceChain(true)
.addResolver(new PathResourceResolver());
super.addResourceHandlers(registry);
}
}
you can add following code in application.propertise:
spring.resources.static-locations=classpath:/webapp/
and following code in application.yaml:
resources:
static-locations: classpath:/webapp/
I recently had the same issue and simply did a text search for "robots.txt" within my jHipster generated files.
I added my new file to the assets array in angular.json and put my new file in the same location as robots.txt, which as stated earlier is webapps.

Resources