Spring Boot 没有返回正确的 MIME 类型 [英] Spring Boot not returning correct MIME type

查看:37
本文介绍了Spring Boot 没有返回正确的 MIME 类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 Spring Boot、Spring Security 和 Thymeleaf 制作一个 Spring MVC 应用程序.

问题是 - 当我请求一个包含 html 和 css 的页面时,我没有为我的 css 文件获取正确的 MIME 类型,因此为什么 Chrome 无法加载状态为取消"和消息拒绝应用来自'http://localhost:8080/login'的样式因为它的 MIME 类型 ('text/html') 不是受支持的样式表 MIME 类型,并且启用了严格的 MIME 检查."

我正确链接了 css 文件:" "

css 文件包含在:

资源 -> 静态 -> css -> style.css

我已允许安全配置文件中资源文件夹中的所有资源:

 包 org.isp.configuration;导入 org.isp.services.api.UserService;导入 org.springframework.beans.factory.annotation.Autowired;导入 org.springframework.context.annotation.Bean;导入 org.springframework.context.annotation.Configuration;导入 org.springframework.http.MediaType;导入 org.springframework.security.authentication.dao.DaoAuthenticationProvider;导入 org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;导入 org.springframework.security.config.annotation.web.builders.HttpSecurity;导入 org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;导入 org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;导入 org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;导入 org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer;@配置@启用网络安全公共类 WebSecurityConfig 扩展了 WebSecurityConfigurerAdapter {@自动连线私人用户服务用户服务;@覆盖受保护的无效配置(AuthenticationManagerBuilder auth)抛出异常{auth.authenticationProvider(authenticationProvider());}@豆角,扁豆public DaoAuthenticationProvider authenticationProvider() {DaoAuthenticationProvider authProvider= new DaoAuthenticationProvider();authProvider.setUserDetailsS​​ervice(this.userService);authProvider.setPasswordEncoder(getBCryptPasswordEncoder());返回 authProvider;}@覆盖protected void configure(HttpSecurity http) 抛出异常 {字符串 [] 允许 = 新字符串 []{"/", "/home","/register","/about","/png/**","/css/**","/icons/**","/img/**","/js/**","/layer/**"};http.authorizeRequests().antMatchers(permitted).permitAll().anyRequest().authenticated().和().formLogin().loginPage("/login").permitAll().defaultSuccessUrl("/dashboard").usernameParameter("用户名").passwordParameter("密码").和().logout().logoutSuccessUrl("/login?logout").permitAll().和().exceptionHandling().accessDeniedPage("/unauthorized").和().csrf().disable();}@豆角,扁豆公共 BCryptPasswordEncoder getBCryptPasswordEncoder(){返回新的 BCryptPasswordEncoder();}}

这是我的 html 页面:

<html lang="en" xmlns="http://www.w3.org/1999/xhtml"xmlns:th="http://www.thymeleaf.org" ><头><title>索引</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">**<身体><div th:include="~{fragments/navbar::navbar}"></div><div class="容器"><h3>首页</h3><p>这是项目的主页!</p>

<div th:include="~{fragments/footer::footer}" class="footer"></div></html>

任何想法如何修复不正确的 MIME 类型?是不是缺少什么配置?

解决方案

我一直在为同样的问题苦苦挣扎,我终于意识到这是一个红鲱鱼 - 真正的问题是 404,并且 MIME 类型错误来自 Spring 对其的处理.如 Spring Boot 文档中所述,它的内置错误处理会自动重定向到 /error 并将错误详细信息输出为 JSON.当我检查日志时,我在网络服务器访问日志中看到了 404,在我的应用程序日志中看到了以下内容:

DEBUG DispatcherServlet:869 - 名为dispatcherServlet"的 DispatcherServlet 正在处理 [/error] 的 GET 请求DEBUG RequestMappingHandlerMapping:310 - 查找路径/error 的处理程序方法DEBUG RequestMappingHandlerMapping:317 - 返回处理程序方法 [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 - 写入 [{timestamp=Fri Apr 06 14:06:54 PDT 2018, status=404, error=Not Found, message=No message available, path=/css/style.css}] 为application/json" 使用 [org.springframework.http.converter.json.MappingJackson2HttpMessageConverter@5ef96137]

所以,您真正的问题是 Spring 没有找到您的静态资源.您需要确保 resources 文件夹在您的类路径中,或者使用 spring.resources.static-locations 属性显式设置位置.

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?

解决方案

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.

这篇关于Spring Boot 没有返回正确的 MIME 类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆