How to display .png file from static/image folder?

Viewed 211

I have the logo.png file in the static/image folder and I appended the path as you can see on my code but it is not displaying the image. Any help is appreciated.

Here is my controller class:

@RestController
public class ShoppingController {

    
    @GetMapping("/shopping/logo")
    public String getShoppingLogo() {
        System.out.println("Inside the the logo method.........");
        StringBuffer sb = new StringBuffer();
        sb.append("<tr>");
        sb.append("<p> <h1>Semhal Online Shopping!!</h1></p>");
        sb.append("<img src=").append("/shoppingLogo.PNG").append("alt='No logo to view.'>");
        sb.append("</tr>");
        return sb.toString();
    }

Here is the Config class :

@Configuration
public class WebConfiguration extends WebMvcConfigurationSupport {
    
    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**")
        .addResourceLocations("classpath:/static/", "classpath:/image/")
        .setCachePeriod(0);
    }
1 Answers

You'd need to escape the quotes with \" for the image src value. Just to be sure, the same for the alt field:

sb.append("<img src=\"/shoppingLogo.PNG\" ")
  .append("alt=\"No logo to view.\">");

So the result becomes something like:

<img src="/shoppingLogo.PNG" alt="No logo to view.">

Your code creates an invalid tag, as doesn't include the double quotes:

<img src=/shoppingLogo.PNG ... >.

Related