I am facing the issue with IE browser.It is loading the icons for first time load. but if i refresh the page the icons are not visible. Can you please tell me how to fix this from server side? This is related to Font-awesome disappears after refresh for all ie browsers ie11,ie10,ie9 . but it does nt have the complete solution
We had this same problem because we were storing the FA CSS file locally. The font #import's would fail on refreshes, probably because it does a different HTTP call than the one for the local file. We reverted to their CDN and it fixed the problem. If you downloaded the FA files and aren't pulling them in through a CDN, then change your <link> tag in your <head> to:
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
Once we did that FontAwesome was being served up on every refresh without problem.
In my case i was using java and the only thing that works was this cache filter that i made.
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebFilter("*")
public class CacheFilter implements Filter {
/**
* #constructor CacheFilter
* #date 28/09/2015
*/
public CacheFilter() {
//construtor
}
/* (non-Javadoc)
* #see javax.servlet.Filter#destroy()
*/
#Override
public void destroy() {
//metodo vazio
}
/* (non-Javadoc)
* #see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
*/
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletResponse httpResponse = (HttpServletResponse) response;
HttpServletRequest httpRequest = (HttpServletRequest) request;
String page = httpRequest.getRequestURI();
if (!page.contains("fontawesome-webfont") || !page.endsWith(".eot")){
httpResponse.setHeader("Expires", "-1");
httpResponse.setHeader("Cache-Control", "no-store, no-cache, must-revalidate, post-check=0, pre-check=0");
httpResponse.setHeader("Pragma", "no-cache");
}else if(page.contains("fontawesome-webfont") && page.endsWith(".eot")){
httpResponse.setHeader("Expires", "-1");
httpResponse.setHeader("Cache-Control", "public");
httpResponse.setHeader("Pragma", "cache");
}
chain.doFilter(request, response);
}
/* (non-Javadoc)
* #see javax.servlet.Filter#init(javax.servlet.FilterConfig)
*/
#Override
public void init(FilterConfig fConfig) throws ServletException {
//metodo vazio
}
}
I did the same thing as https://stackoverflow.com/a/37196841/1982385 except that I did it on the reverse proxy (HAProxy) instead of from the servlet itself.
backend app
server server1 10.10.14.4:9090 check
acl is_woff capture.req.uri -m sub .woff
acl is_ttf capture.req.uri -m sub .ttf
acl is_eot capture.req.uri -m sub .eot
http-response set-header Cache-Control public if is_eot or is_woff or is_ttf
http-response set-header Expires -1 if is_eot or is_woff or is_ttf
http-response set-header Pragma cache if is_eot or is_woff or is_ttf
Suggestion provided by CV Harris is working fine. But, we didn't want to use files from CDN.
For us, icons issue occurred after upgrading Spring Security to 4.2.3. So, as given in Spring security configuration, added following in spring configuration.
defaults-disable="true"
Now icons are displayed in IE11.
I know... old question... but still relevant. I had the same issue... using a CDN worked, but not hosting the FA css myself.
Turns out it was related to caching as others have suggested. I had turned caching off for everything in the BeginRequest method below (for some reason which now escapes me... troubleshooting something else probably), but it seems that FA really wants to be cached... /shrug.
protected void Application_BeginRequest()
{
Context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
}
Commenting this out fixed FA icons on refreshes, though I now have the task of making it a little more fine grained...
Related
I'm trying to make a Spring MVC app with Spring boot, Spring Security and Thymeleaf.
The problem is - when i'm requesting a page with it's html and css, i'm not getting the correct MIME type for my css file, thus why Chrome cannot load it with status "canceled" and the message "Refused to apply style from 'http://localhost:8080/login' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled."
I'm linking the css file correctly:
" "
The css file is contained in:
resources -> static -> css - > style.css
I've allowed all resouces from the resources folder in the Security config file:
package org.isp.configuration;
import org.isp.services.api.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer;
#Configuration
#EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private UserService userService;
#Override
protected void configure(AuthenticationManagerBuilder auth)
throws Exception {
auth.authenticationProvider(authenticationProvider());
}
#Bean
public DaoAuthenticationProvider authenticationProvider() {
DaoAuthenticationProvider authProvider
= new DaoAuthenticationProvider();
authProvider.setUserDetailsService(this.userService);
authProvider.setPasswordEncoder(getBCryptPasswordEncoder());
return authProvider;
}
#Override
protected void configure(HttpSecurity http) throws Exception {
String[] permitted = new String[]{
"/", "/home","/register","/about","/png/**",
"/css/**","/icons/**","/img/**","/js/**","/layer/**"
};
http
.authorizeRequests()
.antMatchers(permitted).permitAll()
.anyRequest().authenticated()
.and()
.formLogin().loginPage("/login").permitAll()
.defaultSuccessUrl("/dashboard")
.usernameParameter("username")
.passwordParameter("password")
.and()
.logout().logoutSuccessUrl("/login?logout").permitAll()
.and()
.exceptionHandling().accessDeniedPage("/unauthorized")
.and()
.csrf().disable();
}
#Bean
public BCryptPasswordEncoder getBCryptPasswordEncoder(){
return new BCryptPasswordEncoder();
}
}
This is my html page:
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org" >
<head>
<title>Index</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
**<link rel="stylesheet" href="../static/css/style.css" type="text/css">**
</head>
<body>
<div th:include="~{fragments/navbar :: navbar}"></div>
<div class="container">
<h3>Home</h3>
<p>This is the home page of the project!</p>
</div>
<div th:include="~{fragments/footer :: footer}" class="footer"></div>
</body>
</html>
Any ideas how can i fix the incorrect MIME type? Is there any configuration im missing?
In my case, I have to permit requests for static files to get it to work.
#Configuration
#EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Overide
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/js/**", "/css/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll();
}
}
I've just been struggling with the same issue, and I finally realized that it was a red herring - the real problem was 404, and the MIME type error came from Spring's handling of it. As explained in the Spring Boot docs, its built-in error handling automatically redirects to /error and outputs the error details as JSON. When I checked my logs, I saw a 404 in my webserver access log and the following in my application log:
DEBUG DispatcherServlet:869 - DispatcherServlet with name 'dispatcherServlet' processing GET request for [/error]
DEBUG RequestMappingHandlerMapping:310 - Looking up handler method for path /error
DEBUG RequestMappingHandlerMapping:317 - Returning handler method [public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)]
DEBUG HttpEntityMethodProcessor:234 - Written [{timestamp=Fri Apr 06 14:06:54 PDT 2018, status=404, error=Not Found, message=No message available, path=/css/style.css}] as "application/json" using [org.springframework.http.converter.json.MappingJackson2HttpMessageConverter#5ef96137]
So, your real problem is that Spring is not finding your static resources. You'll want to make sure the resources folder is in your classpath, or explicitly set the locations using the spring.resources.static-locations property.
In my case, I have used additional filter. So all kind of request will go through that filter. even css and js file used to go through that.
At this point, for some request in the ratio of 1/7 or 1/10, I get mime type issue, for css file the server returns with the type of application/javascript or application/json and ect.
Then I used #WebFilter and allows only api request to go through that filter.
#WebFilter(urlPatterns = "/api/*")
Now the css and js files not allowed in that additional filter. and then I did't find issue with mime type.
In my point of view, when we have too many filters the backend fails to handle frequent request for resources (js, css, img ...), So it returns with wrong MIME type.
Hope, this would help someone, who face this kind of issue
A client had the case today (24 nov 2021) when Spring Security was redirecting most of the requested urls to "/login" equivalent functional endpoint. No assets were loaded, and the same message you get about mimetype was in their Google Chrome console logs.
Diagnostic was done with entering the assets with wrong mimetype and see the loading of the "/login" endpoint.
It was resolved with adding some Spring Security mapping rules in their SecurityConfig.class of their Spring Boot Application, so the webapp is running well now.
We have a requirement of enabling universal link in our application. We have a java based web application(spring) and a iOS app. To enable universal link as per apple we need to create a json file apple-app-association-file and host this file in the server.
Now java web app is deployed in tomcat in windows server and apche 2.4 is being used as web server. Please let me know how to host the apple-app-association-file in the tomcat or web server or inside the war file(inside the code), we are using maven structure.
according to docs, we need to remove the file extentsion and file should be access as below:
url of web app: https://xyz.example.com
where xyz.example.com is mapped to a web app which is there in webapp folder in tomcat.(localhost:8080/webApp)
apple-app-association-file to be accessed as: https://xyz.example.com/apple-app-association-file
now as the extension is not there how can i host it.Do i need to make the code changes and treated it as servle request. Even if i do so it wont be a good idea to execute a servet just to access a file
Also, it's also important that the file is served with the correct MIME-type, for Universal Links it can be served as application/json. How to set mime type in tomcat or java web app(spring)
First rename file to apple-app-site-association.json, then write next Spring configuration:
#EnableWebMvc
public class WebClientConfig extends WebMvcConfigurerAdapter {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/.well-known/*")
.addResourceLocations("/path/to/your/static/resources")
.resourceChain(true)
.addResolver(new PathResourceResolver() {
#Override
protected Resource getResource(String resourcePath, Resource location) throws IOException {
if (resourcePath.equals("apple-app-site-association")) {
return location.createRelative("apple-app-site-association.json");
}
return super.getResource(resourcePath, location);
}
});
}
}
As described here: developer.apple.com
You can place the file at the root of your server or in the .well-known subdirectory.
Then the file will be served with the correct MIME-type "application/json" and accessed as: https://xyz.example.com/.well-known/apple-app-association-file
The Solution from pITer Simonov works for me! But i had to add the root path
inside
< servlet-mapping > (in web.xml)
like this:
< url-pattern >/</url-pattern >
After that, the resource handler work fine!
I did it with a standard REST controller + endpoint.
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
#RestController
#RequestMapping("/.well-known")
#Slf4j
public class WebClientConfig {
#GetMapping(value = "/apple-app-site-association",
produces = MediaType.APPLICATION_JSON_VALUE)
public String addResourceHandlers() {
String json = "";
InputStream inputStream = getClass().getResourceAsStream("/apple-app-association.json");
try(InputStream stream = inputStream) {
json = StreamUtils.copyToString(stream, Charset.forName("UTF-8"));
} catch (IOException ioe) {
log.error("Apple app association could not be retrieved! iOS app will be impacted. Error: " +
ioe.getMessage());
}
return json;
}
}
Note: the apple-app-asociation.json file is under src/main/resources
I am using following meta tags to prevent browser caching for page:
<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate, max-stale=0, post-check=0, pre-check=0" />
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Expires" content="-1" />
<meta http-equiv="Vary" content="*" />
Case:
Browser is already opened with page1.
New link is pasted in the browser address bar and now secured page page2 is opened.
User performs action on page2 and is redirected to page3.
When clicking back button on page3, then user gets redirected to page1 (no caching and works fine in this case). When user clicks forward button on page1, then the user is forwarded to the secured page page2. This shouldn't happen.
All of above is tested on IE9.
How is this caused and how can I solve it?
Your initial attempt with HTML <meta http-equiv> tags specifies the right header values, however, this doesn't work at all because your pages are already served over HTTP. The <meta http-equiv> headers specifies "HTTP-equivalent" headers which are only used when the pages are not served using the HTTP protocol.
For example, when the pages are opened from local disk file system like as if you were doubleclicking a .html file in local disk file system explorer. This would open the .html file via file:// URI instead of http:// URI.
You should be setting those headers on the real HTTP response. You can investigate the headers of the current HTTP response by pressing F12 in Chrome/FireFox>=23/IE>=9 and exploring the HTTP traffic in Network tab. In case of specifically IE9/10, click the Start capturing button, reload the page, select the HTML page, click Go to detailed view button and finally click the Response headers tab. Here's a screenshot of how it look like in IE10 on your current question:
The right way to get those headers to end up there is using HttpServletResponse#setHeader() and friends like setDateHeader(), addHeader(), etc. As you figured, one way is a servlet filter.
See also:
Avoid back button on JSF web application
I found out that the best solution is the following filter:
import java.io.IOException;
import javax.faces.application.ResourceHandler;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet Filter implementation class NoCacheFilter
*/
#WebFilter(urlPatterns = {"*.xhtml"})
public class NoCacheFilter implements Filter {
/**
* Default constructor.
*/
public NoCacheFilter() {
// TODO Auto-generated constructor stub
}
/**
* #see Filter#destroy()
*/
public void destroy() {
// TODO Auto-generated method stub
}
/**
* #see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
*/
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
// apply no caching for all web pages except resources, you can customize that to be applied for specific pages
if (!req.getRequestURI().startsWith(req.getContextPath() + ResourceHandler.RESOURCE_IDENTIFIER)) { // Skip JSF resources (CSS/JS/Images/etc)
res.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1.
res.setHeader("Pragma", "no-cache"); // HTTP 1.0.
res.setDateHeader("Expires", 0); // Proxies.
}
chain.doFilter(request, response);
}
/**
* #see Filter#init(FilterConfig)
*/
public void init(FilterConfig fConfig) throws ServletException {
// TODO Auto-generated method stub
}
}
according to the answer in this question:
Redirect to login page when user clicks on back button after logout in JSF
I'm developing an application with RESTEasy and JBOSS 5.1.
For specific situations, I have to return 404 error (not found).
In the sources, I'm using
import org.jboss.resteasy.spi.NotFoundException;
throw new NotFoundException(...);
The problem is that, in the header response, I have
Status Code: 500 internal server error
even if in the body the exception is:
org.jboss.resteasy.spi.UnhandledException: org.jboss.resteasy.spi.NotFoundException
This is a normal behavior? It's not possible to return Status Code: 404?
I encounter some problem. I found the root cause. The built-in exception handle is only occur in resteasy newest version build 2.3.1 GA. If you upgrade to this version.You can get the expected result.
It does seem a bit strange that RestEASY does not handle the NotFoundException out of the box. It should, according to the docs:
Resteasy has a set of built-in exceptions that are thrown by it when it encounters errors during dispatching or marshalling.
Anyways, you can work around it by adding an ExceptionMapper:
import org.jboss.resteasy.core.Dispatcher;
import org.jboss.resteasy.mock.MockDispatcherFactory;
import org.jboss.resteasy.mock.MockHttpRequest;
import org.jboss.resteasy.mock.MockHttpResponse;
import org.jboss.resteasy.spi.NotFoundException;
import org.junit.Assert;
import org.junit.Test;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
public class ExceptionTest {
#Path("/")
public static class Service {
#GET
public String notFound() throws NotFoundException {
throw new NotFoundException("");
}
}
public static class FailureExceptionMapper implements ExceptionMapper<NotFoundException> {
#Override
public Response toResponse(NotFoundException exception) {
return Response.status(exception.getErrorCode()).build();
}
}
#Test
public void test() throws Exception {
Dispatcher dispatcher = MockDispatcherFactory.createDispatcher();
dispatcher.getProviderFactory().addExceptionMapper(new FailureExceptionMapper());
dispatcher.getRegistry().addSingletonResource(new Service());
MockHttpRequest request = MockHttpRequest.get("/");
MockHttpResponse response = new MockHttpResponse();
dispatcher.invoke(request, response);
Assert.assertEquals(404, response.getStatus());
}
}
I believe that instead of throwing an exception you should use:
import javax.ws.rs.core.Response;
return Response.status(404).build();
in your rest method when you need to return a not found.
regards.
Maybe a custom javax.servlet.Filter can help.
I am exporting my List to CSV file through Servlet. Everything is working fine. but i want to set default/ dynamic width for cell/column?
Here is my coding. Your swift reply will be helpful..
Thanks in advance.
package com.uson.stat.action;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class ExportAction extends HttpServlet {
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("application/CSV");
res.setHeader("Cache-Control", "public");
res.setHeader("Pragma", "public");
res.setHeader("Content-Disposition", "attachment; filename= \"test.csv"+ "\"");
String content = "Test Article"+","+"Viewed on 01-02-2010"+","+"Guest";
System.out.println("content >>>>>>" + content);
res.getOutputStream().print(content);
}
}
output will be:
Test Article Viewed on 01-01-2010 Guest
But output is displaying like this:
Test ArtiViewed on Guest
It is displaying fine in each cell. But I need to increase the size manually in Excel. file. How can i set the cell width dynamically/default size?
How to resolve this?
Gnaniyar Zubair
"How can i set the cell width dynamically/default size?"
You can't.
CSV is just the data. Nothing more. No color, no font, no width. Nothing.