Fix location path to .css with Thymeleaf (Spring Boot) - java

I'm working on a project with Spring Boot. I have a main.css file under /src/main/resources/static/css/
I use this thymeleaf code to inject the .css file into a .html file from the /templates folder:
<link rel="stylesheet" th:href="#{/css/main.css}" href="../static/css/main.css" />
I can open it respectively via http://localhost:1126/css/main.css
I use this .html as a detailed error page. So if an URL doesn't exists, show this .html. If the URL is with "one depth" (for example localhost:1126/something) it works fine (.html is shown and .css is loaded).
But if I use URLs with at least "two depths", or even with an "/" at the end (for example localhost:1126/something/ or localhost:1126/something/anything) it doesn't work (.html is shown but .css IS NOT loaded).
The problem is that in the second case Spring try to find the .css file under localhost:1126/something/css/main.css
Things I've tried so far:
use th:href="#{/css/main.css}" instead of th:href="#{css/main.css}"
AND
#SpringBootApplication
#EnableWebMvc
public class SpringBootProjectApplication implements WebMvcConfigurer {
public static void main(String[] args) {
SpringApplication.run(SpringBootProjectApplication.class, args);
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/css/**").addResourceLocations("classpath:/css/");
}
}
I have found these threads with no answers for my problem:
Thymeleaf, IntelliJ and Spring Boot not loading CSS files
correctly
Spring Boot, Thymeleaf and CSS
CSS file cannot
be located thymeleaf Spring Boot

Spring boot default BasicErrorController would directly look at src/main/resources/templates/ folder if you add your error html page there as "error.html" you can show that whenever error occurs

I faced the same issue when my URL had multiple "/". But I did not make any special changes except for changing my css links as follows.
<link rel="stylesheet" th:href="#{~/css/main.css}">
And same with javascript files as well.
On a side note, I don't use #EnableWebMvc annotation. It kinda messes up with automatic SpringMVC configuration.

Related

CSS File Not Load In Maven Project

My Maven Project Structure is Like Below.I want To Load Css In mainMenu.jsp File.
<link rel="stylesheet" href="../Main.css">
Above Line Is Not Working.So How Can I Load Main.css in mainMenu?
Don't confuse your WEB-INF layout with what the browser sees. Move your Main.css to "webapp" (or, more commonly "webapp/style"), and then reference it as "Main.css" (if in webapp) or "style/Main.css" (if in webapp/style).
Under WEB-INF, you typically only want files which are processed server-side, eg. JSP (when using a ViewRenderer) or web.xml.
Spring Boot automatically adds static resources located within any of the following directories as mentioned here:
/META-INF/resources/
/resources/
/static/
/public/
Hence, the mistake you are making is by placing static content in wrong directory.
I Have Solved Issue By Adding Below Line OF Code In Web Configuraion And Add All Front End File In resources Folder.
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry
.addResourceHandler("/resources/**")
.addResourceLocations("/resources/");
}

How to externally add a javascript file to a JSP in a maven project?

I have a maven project with spring-mvc configurations with the hierarchy mentioned in below image. I've placed list.js file inside all the possible places in src folder and its sub folders but I couldn't access it from my list.jsp file. What am I doing wrong here? Can anyone help me to figure it out?
Static Resources like JS, CSS, Images,etc visible from webapp folder in a web application.
So, you can create js folder under webapp folder and place your list.js file inside it.
Also, you need to tell Spring to not process these static resources path.
Looks like you had defined your Spring Configuration in Java Classes i.e. WebConfig. You need to add below code
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/js/**").addResourceLocations("/js/");
}
Lastly, change your path in jsp file like this
<script
src="${pageContext.request.contextPath}/js/list.js"></script>
Hope it helps to solve your problem.

Spring boot not loading images from src/main/resources path into jsp

I have a image file inside
enter image description here
Here is my configuration inside Configuration class.
private static final String[] CLASSPATH_RESOURCE_LOCATIONS = {
"classpath:/META-INF/resources/", "classpath:/resources/**",
"classpath:/static/**", "classpath:/public/" };
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**").addResourceLocations(CLASSPATH_RESOURCE_LOCATIONS);
Inside Jsp I am not able to load the image under div tag
<div id="image">
<p>
<img src="/images/reviewCount.jpg" width="600" height="400" border="0" usemap="#chart">
</p>
I tried
1) To give absolute path like src/main/resources/static/images/reviewCount.jpg
2) src="{/images}/reviewCount.jpg"
Both the approaches went in a wine.
Any one who can some shed light would be appreciated.
TIA.
regards
Vinod
Spring Boot automatically maps static folder in the resources to serve static content. Just put images like this:
You have to place all the images, css, js files inside your webapp folder.. ie webapp/resources.
If you are packaging the application as a jar then dont use the src/main/webapp
this will only work with war packaging and it will be ignored by most build tools if you generate a jar.
In Spring boot by default, resources are mapped on /** but you can tune that via spring.mvc.static-path-pattern. For instance, relocating all resources to /resources/** can be achieved as follows:
spring.mvc.static-path-pattern=/resources/**
Read more from here
It is a typo. You have reviewCount.png in static/images folder and you are referring reviewCount.jpg from div tag.

Spring Boot does not load Bootstrap in jsp file

Today i have a problem with Bootstrap in my Spring Boot app.
Spefically, when i start the app and open the browser, i can see my page but with "classic" html; that is, i don't see the page formatted with the css of Bootstrap but with normal html5 (so, Bootstrap is nota loaded).
What i have done?
First, i've download Boostrap framework; then i try to put the 3 folder css, js and fonts under both this path:
src/main/webapp (first)
src/main/resource/static (then)
In the second case, i tried also to move from /static folder into resource, that is src/main/resource
When i've put this 3 folder in resource and resource/static, i tried 2 configuration:
add in application.properties file this line of code: spring.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/
Use a MvcConfiguration class that extends the WebMvcConfigurerAdapter class and override the method addResourceHandlers this way:
public void addResourceHandlers(ResourceHandlerRegistry registry)
{
registry.addResourceHandler("/resources/**")
.addResourceLocations("/resources/");
}
Of course, done this, in my jsp file (located under src/main/webapp/WEB-INF/jsp) i'v put the 2 line of code to tell the page where take the css and js file:
<link href="/resources/static/css/bootstrap.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="/resources/static/js/bootstrap.min.js"></script>
and of course, these line change from /resource/static/ with /webapp when i try to put under src/main/webapp the 3 Bootstrap folder. But, after this, i cannot see Bootstrap loaded. What i wrong?
Update: solved. The problem was based on a setting in my applications.properties:
server.port=8080
server.contextPath=/polaris
that is, the change of the context path. A usefull tread on this site is this: Spring 4 - addResourceHandlers not resolving the static resources
Using in JSP by link href and give path like static/css/somename.css
Do 4 Step:
1.maven-Clean
2.update project
3.maven install
4.Run As Spring Boot App
Hope it will help.
The Path Of Any CSS Should be Like This in Spring Boot
You can refer following link for spring boot with boostrap template on web application. example_link. You have to change following property values on application.properties file inside the above application for jsp page load. Make sure inside webapp folder having correct name.
spring.mvc.view.prefix=/html/
spring.mvc.view.suffix=.html

Spring boot WAR deployed to Tomcat and missing context for static resources

I'm having a problem when deploying a Spring Boot application as a WAR file to a standalone Tomcat 7 server. It builds and deploys fine but when the index.html page tries to load other static resources they are missing the context in the url so fail to load (404).
e.g. http://localhost:8080/app/images/springboot.png
should be: http://localhost:8080/spring-boot-war-context-issue/app/images/springboot.png
Image showing issue
It works fine when using the embedded Tomcat
Similar issues:
Seems to be a similar issue to:
Spring-Boot war external Tomcat context path
However the suggestions in that question did not seem to solve my issue. I wasn't sure about the Tomcat xml file.
Steps followed:
I created a simple sample application and followed the steps in the Spring Boot docs.
The sample code can be seen in this github repo along with steps to reproduce the problem: https://github.com/jgraham0325/spring-boot-war-context-issue
Things I've tried so far:
Set contextPath in application.properties but this only applies to embedded tomcat
Tried using a fresh install of Tomcat 7
Tried creating a config file in tomcat to force context:
apache-tomcat-7.0.72\conf\Catalina\localhost\spring-boot-war-context-issue.xml
Contents of spring-boot-war-context-issue.xml:
<Context
docBase="spring-boot-war-context-issue"
path="spring-boot-war-context-issue"
reloadable="true"
/>
Any advice would be much appreciated!
Thanks
Update 23/10/2016:
Alex's answer below about using relative URLs without the slash at the start was perfect solution!
Isn't it simply caused by the way you defined your url in index.html (the url does not include the context root):
<img src="/app/images/springboot.png" />
Use relative uri
You should be able to use a relative uri (without the leading forward slash):
<img src="app/images/springboot.png" />
get the context root
How do you get the contextPath from JavaScript, the right way?
How to set ContextPath for an image link
Browser can't access/find relative resources like CSS, images and links when calling a Servlet which forwards to a JSP
How to use relative paths without including the context root name?
With JSP/JSTL:
<img src="${pageContext.request.contextPath}/app/images/springboot.png" />
Or with Javascript:
function getContextPath() {
return window.location.pathname.substring(0, window.location.pathname.indexOf("/",2));
}
...
var img = new Image();
img.src = getContextPath() + "/app/images/springboot.png";
document.getElementById('div').appendChild(img);
If using Thymeleaf, another way is using Context-Relative URLs like below:
<link rel="icon" type="image" th:href="#{/img/favicon.ico}"/>
For more information please refer to: Thymeleaf Documentation

Categories

Resources