我正在使用Spring Boot v2.1.9.RELEASE和Thymeleaf开发一个Web应用程序。该应用程序将服务器端渲染(Spring MVC常规控制器)与通过AJAX调用的其余控制器混合在一起。只要GET
和POST
是我使用的唯一HTTP方法,该页面就可以像超级按钮一样工作。一旦添加了DELETE
REST控制器(完全不相关但尚未使用),CSS和JS资源就会停止加载,并在浏览器控制台中显示如下错误:
The resource from “http://localhost:8080/css/demo.css” was blocked due to MIME type (“application/json”) mismatch (X-Content-Type-Options: nosniff)
如果删除新控制器,则该页面将再次开始工作。
[当我使用网络监视器检查请求时,发现:
X-Content-Type-Options: nosniff
标头始终出现在响应中,与Spring Security documentation一致。DELETE
端点不存在,则按预期返回GET /css/demo.css
请求并带有HTTP 200
代码。 Accept
(请求标头)和Content-Type
(响应标头)都标记为text/css
。HTTP 405
。 Accept
标头为text/css
,但Content-Type
变为application/json
。另外,添加了新的响应头:Allow: DELETE
。我的猜测是,当Spring扫描控制器并找到DELETE
方法时,会自动添加一些额外的配置,但是我找不到任何引用来确认这一点。我想知道为什么会这样,如何避免这种行为。
由于我正在本地开发,所以我的Spring Security配置非常简单:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Bean
public AuthenticationManagerConfigurer authConfigurer() {
return new InMemoryAuthenticationManagerConfigurer();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
authConfigurer().configure(auth);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest()
.authenticated()
.and()
.formLogin();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
我要添加的REST控制器几乎什么都不做:
@RestController
public class MotivosController {
private final String CONTROLLER_PATH = "/rest/motivos/{id}";
@RequestMapping(name=CONTROLLER_PATH, method=RequestMethod.DELETE)
public void deleteMotivo(@PathVariable(name="id") String id) {
logger.debug("Eliminando el motivo " + id);
}
// Other members I consider unrelated to the problem go here...
}
CSS和JS文件正在加载到template.html
文件夹下的src/main/resources/templates
文件中,如下所示:
<link type="text/css" href="/css/demo.css" rel="stylesheet" />
答案比我想象的要容易,我的假设完全错误。我将@RequestMapping
的name
属性与value
属性混淆了,因此,任何URL都与该方法匹配。将name
更改为value
即可使用。