Spring Boot custom favicon.ico not showing - spring-mvc

I know this question has been asked over and over here and there are several solutions. I've tried several of those except the ones that suggests writing you own configuration bean for this. I don't want to do all that just to display a tiny icon it seams overkill. But I can not get it to work. These are the solutions I've tried so far.
just add favicon.ico under static resources and it should work....it doesn't.
spring.mvc.favicon.enabled=false in application.properties, no favicon showed at all (which I guess is the whole point of that).
Tried 2 examples of including the favicon as a link in the html pages. Like so:
<link rel="icon" type="image/png" href="favicon.png" />
<link rel="icon" type="image/x-icon" href="favicon.ico" />
Neither of those work.
Tried renaming my own favicon to something else and reference it as above. Does not work.
When inspecting the page in the browser I sometimes get no error at all printed out despite no icon showing, or I get an error saying GET http://localhost:8080/myapp/favicon.png 404 () Where it is refering the type as JSON (which I find strange).
I'm running out of ideas here so if anyone can tell me why this is not working please let me know. Did I perhaps forget one of those magic spring annotations?
This is what my main class looks like.
#SpringBootApplication
#ComponentScan
#Configuration
#EnableWebMvc
public class JobengineMonitorApplication implements CommandLineRunner {
public static void main(String[] args) {
SpringApplication.run(JobengineMonitorApplication.class, args);
}
}
I am using thymeleaf as the template engine

I solved this problem by putting favicon.ico in main/resource/static and adding this lines to my security config
httpSecurity
.authorizeRequests()
.antMatchers( "/favicon.ico").permitAll()

I have this with SpringBoot configuration too and is working
<link rel="shortcut icon" type="image/png" th:href="#{/img/favicon.png}"/>
And the favicon.png under resources/public/img

If anyone faces the same problem using newer version of Spring (in my case spring boot 2.4.4), here's the scenario that worked fine for me:
Put the favicon.ico in the /resources/static folder. I also tried to put it just in the /resourses/ folder and it worked fine as well, so do not worry about the folder that much.
Create a FaviconConfiguration in your configurations folder with the following content:
#Configuration
public class FaviconConfiguration {
#Bean
public SimpleUrlHandlerMapping customFaviconHandlerMapping() {
SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();
mapping.setOrder(Integer.MIN_VALUE);
mapping.setUrlMap(Collections.singletonMap(
"/static/favicon.ico", faviconRequestHandler()));
return mapping;
}
#Bean
protected ResourceHttpRequestHandler faviconRequestHandler() {
ResourceHttpRequestHandler requestHandler
= new ResourceHttpRequestHandler();
requestHandler.setLocations(Collections.singletonList(new ClassPathResource("/")));
return requestHandler;
}
}
In case you use Spring Security don't forget to add antMatcher for your favicon resource by adding the following code to your SpringSecurityConfiguration (as JaneXQ already mentioned above):
.antMatchers("/static/favicon.ico").permitAll()
Use link to your custom favicon explicitly in your html. To do that just put the following link in the <head> section of each of your html pages in the following way (I used thymeleaf in here):
<head>
...
<link rel="icon" type="image/ico" th:href="#{../static/favicon.ico}">
...
</head>

Put your favicon.png under src/main/resources/public and add this to your *.html page exactly in the header section
<link rel="shortcut icon" type="image/png" th:href="#{favicon.png}"/>

I found I had to put my favicon.ico file in:
src/main/resources/public

I saved my favicon which was a simple .png download as src/main/resources/static/favicon.ico
I couldn't get it to display until I tried another browser and it worked fine - so try clearing the browser cache, or try testing on another browser

Ok so this appears to be working now. Of course I managed to get it working just after ranting about it :).
Anyway, what i did was.
Remove #EnableWebMvc from the main class
For added ../ to the href depending on the urls e.g /index was fine but /edit/something.html was not
Sorry for wasting peoples time but hopefully this could be useful for another rookie like me

Try to replace th:href with href. It worked for me.
<link rel="icon" href="/favicon.ico" type="image/ico">

For some reason .ico format was not working. I just placed a png image instead and spring automatically picked the favicon.
I placed the png image in \src\main\resources\public
Spring boot + thymeleaf

I had the same issue and fix it removing #EnableAdminServer annotation

Related

Refused to apply style because its MIME type ('application/json') is not a supported

I want to use the fullcalendar library, using gulp and yarn this is the generated link tag:
But I'm getting this error in the console :
Refused to apply style from
'http://localhost/bower_components/fullcalendar/dist/fullcalendar.css'
because its MIME type ('application/json') is not a supported
stylesheet MIME type, and strict MIME checking is enabled.
Why I'm getting this and how can I solve it?
In my case, I found out that I had a typo in css file name. Thus I was trying to import an non existing file.
You're app is serving fullcalendar.css with the wrong MIME type ('application/json') some how. So, my advise is to dig the problem trusting in the error message.
In my case, I was trying Thymeleaf and WebJars with spring-boot for the first time and following blindly some tutorial I added this:
#Configuration
public class WebConfigurer extends WebMvcConfigurerAdapter {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/webjars/**").addResourceLocations("/webjars/");
}
}
Also, my styles were defined in html as below:
<link rel="stylesheet" type="text/css" th:href="#{/webjars/bootstrap/css/bootstrap.min.css}" />
<link rel="stylesheet" type="text/css" th:href="#{/css/main.css}" />
This way, "bootstrap.min.css" and others were given the very same error: "Refused to apply style because its MIME type ('application/json') is not a supported".
I still haven't broken down the reasons for this behavior, but as soon as I realized that spring-boot has an automatic configuration for WebJars, I removed that registration and everything started to work well.
Note: There are some similar tracks with "MIME type ('text/html')" and the reason is usually security filters not allowing the css files and redirecting to html login page. So, keep this in mind and check whether you have some kind of filter/redirect for this request.
Directly put the URL in the browser and see if you can reach it.
For your case, give this url in the browser http://localhost/bower_components/fullcalendar/dist/fullcalendar.css
If you can't reach it, then you have wrong url in your code.
For my case, I had the css file in a directory named css, but in the code I wrote /plugins/css and was getting the same error.
Also, don't forget to give the type="text/css"
So, my code example below:
<head>
<link rel="stylesheet" type="text/css" th:href="#{/css/app.css}">
</head>
If you are using Spring Boot you will not even have to override addResourceHandlers(), just make sure to use th:href and point it to the correct directory.
In my case in the css file
where was a reference to a map file
/*# sourceMappingURL=bootstrap-datepicker.css.map */
that was not present.
I removed the reference to the source map and worked.
You can trying using the relative path to your static content.
<head>
<link rel="stylesheet" type="text/css" href="../css/app.css">
</head>

CSS file blocked: MIME type mismatch (X-Content-Type-Options: nosniff)

I am developing an Angular 4 app and I want to apply some global styles. Following the tutorial at the angular site, I've created a "styles.css" file in the root directory of my app, and I'm referring to that stylesheet in the index.html of my app:
<link rel="stylesheet" type="text/css" href="styles.css">
The angular app is successfully compiled:
$ ng serve
** NG Live Development Server is listening on localhost:4200, open your browser on http://localhost:4200 **
[...]
webpack: Compiled successfully.
But when I visit http://localhost:4200 in a Chromium browser, the console shows an error at
GET http://localhost:4200/styles.css
In a Firefox browser, the error is a bit more explicit:
GET
http://localhost:4200/styles.css [HTTP/1.1 404 Not Found 15ms]
The resource from "http://localhost:4200/styles.css" was blocked due to MIME type mismatch (X-Content-Type-Options: nosniff).
Both files, index.html and styles.css are located in the root directory of my angular app.
I've tried to get more info about the problem :
nosniff
Blocks a request if the requested type is
"style" and the MIME type is not "text/css", or
"script" and the MIME type is not a JavaScript MIME type.
But I don't understand why it's bloking the request, since I've specified type="text/css" when referencing the stylesheet.
I just ran into the same issue. It appears to be a quirk of Express that can manifest itself for a few different reasons, judging by the number of hits from searching the web for "nodejs express css mime type".
Despite the type="text/css" attribute we put in our <link elements, Express is returning the CSS file as
Content-Type: "text/html; charset=utf-8"
whereas it really should be returning it as
Content-Type: "text/css"
For me, the quick and dirty workaround was to simply remove the rel= attribute, i.e., change
<link rel="stylesheet" type="text/css" href="styles.css">
to
<link type="text/css" href="styles.css">
Testing confirmed that the CSS file was downloaded and the styles did actually work, and that was good enough for my purposes.
I also removed rel = "stylesheet", and I no longer get the MIME type error, but the styles are not being loaded
Some answers suggested removing rel="stylesheet", that didn't work out for me however.
According to the expressjs documentation: https://expressjs.com/en/starter/static-files.html
use express.static function to serve static files such as CSS, JavaScript,etc...
app.use(express.static('public'))
and from there you should be able to load any file under the public directory
for example, if you have a style.css file inside the directory {PROJECT_PATH}/public/css/
http://localhost:3000/css/style.css will work.
In running into the same kind of issue for a full stack web application (in development), I simply solved the problem by correctly linking the css file to the page rendered. Removing the rel = stylesheet, as suggested above, prevents the error to show up in the browser but it does not load the styles that should be applied to the page. In short, it isn't a solution.
If you are using express-static you can use this as an example:
Server-side:
app.use(express.static(__dirname + "/public", {
index: false,
immutable: true,
cacheControl: true,
maxAge: "30d"
}));
Client-side:
<link type="text/css" rel="stylesheet" href="/main.css">
Just add a forward slash in front of the file you wish to link to the html page (if you are rendering html pages without using any template engines) and express-static will do the rest automatically for you.
Had a similar problem with a javascript file (as opposed to css) in an Angular app. In reality, the problem wasn't with the Mime type (as the outer error message indicated) but was ultimately a "404 Not Found" error.
In my case, putting the script file anywhere but in the "assets" folder resulted in the 404 and eventually the mime type error. The following tag worked for me in the head section of index.html:
<script src="assets/plugins/jquery.min.js" type="text/javascript"></script>
The assets folder is a sibling of the Index.html file.
This is solved my problem:
app.use('/public', express.static(path.join(__dirname, "public")));
A simple hack is to add a forward slash / before the the path to the stylesheet used. For me it was href='css/style.css', changed it to href='/css/style.css'. Worked like a charm.
I also had this issue.
I moved the script file to a different location and now there is no error:
from <script src="./scripts/simple-keyboard/keyboard.index.min.js" type="text/html"></script>
to <script src="./scripts/keyboard.index.min.js" type="text/javascript"></script>
As noted by Davelli, the issue wasn't a file mismatch but an error not found. It's strange it returned the wrong error!
if this solutions does not help:
app.use(express.static('public'))//for server
<link rel="stylesheet" href="/index.css">//for styles
Then make sure that "public" folder exists in the root directory. This was my case.
I was facing the same problem. But I found out that it has to do with using the right directory for your style.css file. So I tried this line of code below and it worked perfectly.
<link rel="stylesheet" type="text/css" href="/app/scss/style.css">
In my case I just include "/" before "css/style.css"
<link rel="stylesheet" href="css/styles.css" />
to
<link rel="stylesheet" href="/css/styles.css" />
I also use express.static('public')
What seemed to work for me was changing
<script type="text/javascript" src="/lib/matrix.js"></script>
to
<script type="text/javascript" src="./lib/matrix.js"></script>
I ran into this problem as well. I was able to fix the problem with the tip from Kirankumar Gonti.
Use the following line:
app.use('/public', express.static(path.join(__dirname, "public")));
Make sure to set the const path.
You also want to make sure your css folder is nested inside a public folder.
I ran into this problem as well. I was able to fix the problem with the tip from Kirankumar Gonti.
I used the following line of code in my app.js file, I didn't have a public folder but had my style.css stored in a css folder:
app.use('/css', express.static(path.join(__dirname, "css")));
In my /css/style.css file I used:
<link rel="stylesheet" type="text/css" href="/css/style.css" />
For anyone still having this error I was able to solve it by including "src/assets" in my angular.json file
"assets": ["src/favicon.ico", "src/assets", "src/upload.php"]
also the directory of your index.html should not be included in the assets. meaning you should not include "src" in "assets"
In my case I had jumbled up the code blocks below in reverse order so I was getting this error. If you have this issue, follow the below order and it might help
1.
app.use(express.static(path.join(__dirname, 'public')));
2.
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'public/index.html'));
});
3.
app.use('/api', cors(corsOptions), indexRouter);
This is what happened at me,
My site was archieved, so the css and js files are not available. After restore my webhost everything goes well.
So, please check are the URLs is correct or not.

Thymeleaf + CSS+SpringBoot

I have a problem with CSS and Thymeleaf.
In my Spring boot app, I have this structure:
src/main/resource/static/css (for css files)
src/main/resource/static/templates (for html file)
Now, with my html page named ErrorPage and css file named Layout.css, using Thymeleaf I have, in the head of ErrorPage:
<link href="../css/Layout.css" th:href="#{css/Layout.css}" type="text/css" />
But this does not work.
What am I doing wrong?
Move your template folder right under resources:
src/main/resource/static/css (for CSS files);
src/main/resource/templates (for HTML templates).
Then correct the link tag as follows:
<link href="../static/css/Layout.css" th:href="#{/css/Layout.css}" rel="stylesheet" />
Move your template folder right under resources:
src/main/resources/static/css (for CSS files);
src/main/resources/templates (for HTML templates).
Then correct the link tag as follows (relative or absolute):
<link href="../css/firstcss.css" rel="stylesheet">
<link href="/css/secondcss.css" rel="stylesheet">
The old solution with static in front doesn't work for me.
The main culprit of this behaviour is a custom security configuration which is very likely you are doing in your WebSecurityConfigurerAdapter subclass.
If you use SpringBoot 2+ version you should add the following line in your WebSecurityConfigurerAdapter configuration
.requestMatchers(PathRequest.toStaticResources().atCommonLocations()).permitAll()

Getting static web context resources to work on both bookmarkable and non-bookmarkable Wicket pages

In a Wicket 1.4 app, I have some static CSS & JS resources under [project root]/WebContent/css and [project root]/WebContent/js respectively.
My Wicket HTML files are in src/resources/fi/company/product/pages with corresponding Java classes in src/main/fi/company/product/pages. (In the resulting WAR file, the HTML & property files are of course in the same places as Java classes.)
The HTML files contain references to the resources such as:
<head>
<link rel="stylesheet" type="text/css" href="css/main.css"/>
<script type="text/javascript" src="js/calendar.js"></script>
</head>
This works fine everywhere (or so we thought until recently). NB: my Java code does not reference these resources at all.
Looking at the source of a rendered page (whose URL is e.g. http://localhost:8080/report/42.4 or http://localhost:8080/?wicket:interface=:6:::: ), the resource reference appears as:
<link rel="stylesheet" type="text/css" href="../css/main.css"/>
However, we just noticed that when the app is deployed somewhere else than (Tomcat) root, the resources break on non-bookmarkable pages.
In other words, when the URL is e.g.
http://localhost:8080/foobar/?wicket:interface=:2::::
and a page refers to
<link rel="stylesheet" type="text/css" href="../css/main.css"/>
...the browser tries to fetch the resource at the invalid URL
http://localhost:8080/css/main.css
Now, what is the simplest (yet non-hacky) way to get these static resources working, regarless of the deployment path?
I could switch to using bookmarkable pages exclusively (which would require changing the constructors of the pages), but I suppose that shouldn't be necessary...
Edit: Looks like I got CSS resources working (on most places) simply by using <wicket:link>, as advised in this answer:
<head>
<wicket:link>
<link rel="stylesheet" type="text/css" href="css/main.css"/>
</wicket:link>
</head>
However, now the CSS references are broken on a page with an URL like http://localhost:8080/foobar/report/42.9
Wicket is trying to do something strange with the "css/main.css" path:
ERROR org.apache.wicket.RequestCycle - Can't instantiate page using constructor public fi.company.product.pages.ReportPage(org.apache.wicket.PageParameters) and argument 0 = "css" 1 = "main"
org.apache.wicket.WicketRuntimeException: Can't instantiate page using constructor public fi.company.product.pages.ReportPage(org.apache.wicket.PageParameters) and argument 0 = "css" 1 = "main"
at org.apache.wicket.session.DefaultPageFactory.createPage(DefaultPageFactory.java:212)
at org.apache.wicket.session.DefaultPageFactory.newPage(DefaultPageFactory.java:89)
at org.apache.wicket.request.target.component.BookmarkablePageRequestTarget.newPage(BookmarkablePageRequestTarget.java:305)
Edit 2: Actually I'm not sure if <wicket:link> is the right solution here, since these resource files are not "class path resources". I guess my question is, can you make this work while still using web context resources (i.e., without making these class path resources)?
Right, I solved it, and the solution turned out to be very surprising.
Earlier I wrote:
A curious thing is that without any changes, it seems I can no longer
reproduce the problem...
That wasn't quite true, as I had made one small change (that I thought was inconsequential): I had deleted a file WebContent/index.jsp which in our project was a remnant that served no purpose.
Once it dawned on me that this could have fixed it, I did some more testing, and indeed:
For static resources to work as expected, you must not have an index.html or index.jsp file in the root web content directory (i.e., the parent of the CSS and JS resource dirs), as that in some cases breaks ../ references.
This probably isn't even Wicket-specific, but perhaps it is Tomcat-specific—if anyone knows more, feel free to chime in. I'm dubious whether this question ever helps anyone else, but still, glad I got it working!

Favicon Icon-MVC3 ASP.NET

What is the need of favicon.ico. I am trying to use MVC error handling and it complaines file being missed.How do get rid off this error.
Thanks
Go to the RegisterRoutes method of the Global.asax.cs file, and add this, as one of the first lines:
routes.IgnoreRoute("{*favicon}", new { favicon = #"(.*/)?favicon.ico(/.*)?" });
I suggest you use it, instead of getting rid of it. Cause it's part of the web standards in UI design. Don't you like branding of your site? Then this is a crucial part of that branding.
Solution:
<link rel="SHORTCUT ICON" href="http://www.youraddress.com/youricon.ico"/>" if you use localhost then href="http://localhost:port/youricon.ico"
Note:Use other name instead favicon.ico.
Add the following to the beginning of your RegisterRoutes method:
routes.IgnoreRoute("favicon.ico");
Your browser will always ask the site for the favicon, this will ensure mvc doesn't try to resolve it.

Resources