How to load corectly image in thymeleaf (spring boot project)? - image

I want to display the image after an error has occurred in my spring boot application. I read the documentation and tried several ways and it still doesn't work.
I read the documentation and tried several ways and it still doesn't work.
I try this:
<img th:src="#{/images/error_image.jpg}"/>
and this:
<img src="../static/images/error_image.jpg" th:width="1000" th:src="#{/images/error_image.jpg}"/>
This is my project structure:
project structure
Hovering over a photo with ctrl directs me to a photo, so the path is good.
link
but all the time I see this:
error

[EDIT]
The issue is with below controller method, you should provide mapping below.
#GetMapping // add mapping here
public String showSignUpForm()
{
return "register";
}
Make sure static resource is not configured to different path other static/ at your end.
If you have below configuration in application.properties, remove it.
spring.resources.static-locations=
Make sure you have below configurations in application.properties, spring boot's auto-configuration will set it to resource/static/
spring.thymeleaf.enabled=true
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
It's not an issue but still, change /images/ to images/
<img src="../static/images/error_image.jpg" th:width="1000" th:src="#{images/error_image.jpg}"/>

Related

Spring Boot - Image assets are not being loaded even if they are permitted on WebSecurityConfig file

I have recently wanted to add some image on a page within my Spring Boot application, templated with Thymeleaf.
Even other assets (js, css) are being loaded and served successfully, images inside permitted img folder is not being served, a broken image is shown on the designated page.
This is where the image resides:
src/main/resources/static/img/image.png
Excerpt from WebSecurityConfig:
.antMatchers("/css/**", "/js/**", "/img/**","/uploads/**","**/favicon.ico").permitAll()
from the HTML (tried 2 ways, one with Thymeleaf and one without using th prefix):
<img class="featurette-image pull-left" th:src="#{../static/img/image.png}" />
<img src="../static/img/image.png"/>
Please guide me on how to proceed?
Ps: I am using Java DSL, instead xml based configuration.
I've made the search and and seen a couple solutions did not fit my situation. (Checked answers on these before:
Spring Security Thymleaf static resources don't load
when spring security enabled, resouces(css or js) can't be loaded
HTML Image not displaying, while the src url works
)
You don't need "static" in your reference to the image, because Spring Boot by default adds those paths to the classpath (source):
/META-INF/resources/
/resources/
/static/
/public/
So your reference to the file should be directly:
th:src="#{/img/image.png}"

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.

Spring Web Flux cannot resolve path to static content

I am using Spring Boot 2.0.0 M1 with WebFlux to build my sample web application. After succeeding with REST endpoints I've decided to add some views to my application. I've decided to use Thymeleaf 3.x version. I know that Spring serves static content from 4 default location:
/META-INF/resources/
/resources/
/static/
/public/
I've decided to go with second example so my css file is in /resources/static/css/. However after loading my page .css file was not found.
This is a screenshot from my IDE:
I am not providing my own configuration for static directory I just want to use default one. What might be important is the fact that templates are loading just fine from the /resources/templates/ directory.
Css file is loaded like this:
<link data-th-href="#{css/bootstrap.min.css}" rel="stylesheet">
App is not using normal Controller class instead I've provided function as a Bean to define my router:
#Bean
RouterFunction<?> router(final GeneratorHandler generatorHandler) {
return route(GET("/generate"), handler::render);
}
Any ideas what's wrong here?
I've found the right solution. In your RouterFunction you need to use:
return resources("/**", new ClassPathResource("/static/"))
This will set your static directory to:
:classpath/static

Url Binding in SpringBoot

i have been strugling since 4 days but did not found the solution for how to bind the url in Spring Boot with gradle.
I have a url as, http://loalhost:8080/blog/post.html?pid=2&ptitle=abc
I want this url to be shown as below with html and (?),
http://localhost:8080/blog/post/2/abc
Is there any way to do that. I don't want to use tucky urlrewriter. All my html files are placed in webapp folder.
Thanks in Advance.
if your have a POST method in your #RestController to create a post blog:
#PostMapping("/blog/post/{pid}/{ptitle}")
public void create(#PathVariable("pid") String pid, #PathVariable("ptitle") String ptitle) {
// a repo save call
}
(I supposed that you use last spring boot version)

Why does Spring Boot replace all of my favicons with Spring's leaf icon?

(I examined similar questions, but none of them explain the odd behavior I illustrate at the end of this question.)
I have a Spring Boot 1.3.5 application that insists on replacing my favicon with Boot's default favicon (the green leaf). To resolve the problem, I have tried the following:
Install my own favicon at my application's static root.
The word on the street is that this is just supposed to work. Unfortunately, it does not.
Set property spring​.​mvc​.​favicon​.​enabled to false.
This is supposed to disable org​.​springframework​.​boot​.​autoconfigure​.​web​.​WebMvcAutoConfiguration​.​WebMvcAutoConfigurationAdapter​.​FaviconConfiguration, which appears to responsible for serving Boot's default favicon. By setting a breakpoint in that class, I was able to confirm that the beans defined in that class indeed do not get created when the property is set to false.
Unfortunately, this didn't solve the problem, either.
Implement my own favicon handler:
#Configuration
public class FaviconConfiguration {
#Bean
public SimpleUrlHandlerMapping faviconHandlerMapping() {
SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();
mapping.setOrder(Integer.MIN_VALUE);
mapping.setUrlMap(Collections.singletonMap("**/favicon.ico", faviconRequestHandler()));
return mapping;
}
#Bean
protected ResourceHttpRequestHandler faviconRequestHandler() {
ResourceHttpRequestHandler requestHandler = new ResourceHttpRequestHandler();
ClassPathResource classPathResource = new ClassPathResource("static/");
List<Resource> locations = Arrays.asList(classPathResource);
requestHandler.setLocations(locations);
return requestHandler;
}
}
Sadly, no luck here, too.
Rename my favicon from favicon.ico to logo.ico, and just point all my pages' favicon links to that, instead.
Now, with this potential fix, I discovered a surprising result. When I curled my newly named icon.ico resource, I was served Spring's leaf icon. However, when I deleted the resource, I got 404. But then, when I put it back, I got the leaf again! In other words, Spring Boot was happy to answer 404 when my static resource was missing, but when it was there, it would always answer with the leaf instead!
Incidentally, other static resources (PNGs, JPGs, etc.) in the same folder serve up just fine.
It was easy to imagine that there was some evil Spring Boot contributor laughing himself silly over this, as I pulled my hair out. :-)
I'm out of ideas. Anyone?
As a last resort, I may just abandon using an ICO file for my site icon, and use a PNG instead, but that comes at a cost (losing multi-resolution support), so I'd rather avoid that.
This is a spring boot feature:
Spring MVC auto-configuration
Spring Boot provides auto-configuration for Spring MVC that works well with most applications.
The auto-configuration adds the following features on top of Spring’s defaults:
Inclusion of ContentNegotiatingViewResolver and BeanNameViewResolver
beans.
Support for serving static resources, including support for
WebJars (see below).
Automatic registration of Converter,
GenericConverter, Formatter beans.
Support for HttpMessageConverters
(see below).
Automatic registration of MessageCodesResolver (see
below).
Static index.html support.
Custom Favicon support.
Automatic use of a ConfigurableWebBindingInitializer bean (see below).
You can find this document at: http://docs.spring.io/spring-boot/docs/1.4.1.RELEASE/reference/htmlsingle/#boot-features-spring-mvc-auto-configuration
And, If you want to disable spring boot favicon, you can add this config to you yml or perperties files
spring.mvc.favicon.enabled=true # Enable resolution of favicon.ico.
Or, If you want change favicon to you own. try this:
#Configuration
public static class FaviconConfiguration {
#Bean
public SimpleUrlHandlerMapping faviconHandlerMapping() {
SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();
mapping.setOrder(Integer.MIN_VALUE);
mapping.setUrlMap(Collections.singletonMap("mylocation/favicon.ico",
faviconRequestHandler()));
return mapping;
}
}
And you can find more detail at: Spring Boot: Overriding favicon
UPDATE:
put favicon.ico to resources folder.
And, try it:
Why choose the hard way, when u can get the easy one?
just create a new link into ur <head> with:
<link rel="icon" type="image/png" href="images/fav.png" />
Copy and paste ur icon in src/main/resources/static/images/
Rename the file to whatever you want, just remember to change the link in the html too.

Resources