java - 为什么 REST 控制器返回 404 状态码?
问题描述
我正在尝试更新我的数据库中的数据。我在前端使用 jQuery/AJAX,在后端使用 REST/MyBatis/MySQL。不幸的是 REST 控制器返回 404 状态码。请看我的 REST 控制器代码:
@RestController
@RequestMapping("/documents")
public class DocumentResources {
private DocumentsMapper mapper;
public DocumentResources(DocumentsMapper mapper) {
this.mapper = mapper;
}
@PostMapping("/updateDocument")
public List<Documents> updateDocument (@RequestBody Documents document) {
mapper.updateDocument(document);
return mapper.getAllDocuments();
}
}
这是我的 DocumentsMapper 类代码:
@Mapper
public interface DocumentsMapper {
@Select("select * from documents")
List<Documents> getAllDocuments();
@Update("UPDATE documents SET title = #{title}, author = #{author}, src = #{src} WHERE id =#{id}")
void updateDocument(Documents document);
}
这是我的 AJAX 方法:
$( "#target" ).submit(function( event ) {
event.preventDefault();
var formData = {
id : $("#target #id").val(),
title : $("#target #title").val(),
author : $("#target #author").val(),
src: $("#target #src").val(),
createTime : $("#target #createTime").val(),
editTime : $("#target #editTime").val()
}
$.ajax({
url: 'http://localhost:8088/documents/updateDocument',
type : "POST",
contentType : "application/json",
data : JSON.stringify(formData),
dataType : 'json',
success : function(result) {
},
error: function() {
window.location = "/error";
console.log('error', arguments);
},
complete: function() {
console.log('complete', arguments);
}
}).done(function() {
window.location = "/documents";
console.log('done', arguments);
});
});
更新
我刚刚尝试关闭 Spring Security 并且 POST 方法变得可以访问。以下是授权功能:
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/resources/**", "/signup", "/about").permitAll()
.antMatchers("/administrator/**").hasRole("ADMIN")
.antMatchers("/users/**").hasRole("ADMIN")
.antMatchers("/documents/**").hasRole("ADMIN")
.antMatchers("/db/**").access("hasRole('ADMIN') and hasRole('DBA')")
.anyRequest().authenticated()
.and()
.formLogin()
.and()
.logout().logoutSuccessUrl("/login?logout")
.and()
.exceptionHandling().accessDeniedPage("/403")
// .and()
// .csrf()
;
}
更新
我尝试打开 SpringSecurity 但禁用 CSRF .csrf().disable()
。之后 POST 方法起作用。我认为禁用 CSRF 不是一个好主意。这可能会导致 XSS 攻击。所以我应该配置 CSRF 令牌生成及其交换。
解决方案
1)请查看spring启动日志:可以获取项目初始化的url
2)尝试为应用程序放置上下文路径,
这些链接很有帮助:在spring MVC中:如何 在spring boot中的Spring Mvc项目中设置上下文根目录:向Spring Boot应用程序添加上下文路径
示例网址:
http://localhost:8088/ {contextPath}/documents/updateDocument
3) 更好地使用像 swagger ui 这样的 API 文档,您可以尝试轻松点击 url 并在控制器类中获取可用的 url。
推荐阅读
- javascript - 如何根据 JavaScript 中变量的值更改 CSS 类?
- swift - 如何为 CollectionView Cell 指定行数、列数和间距
- swift - 是否有任何解决方法可以将存储的属性快速放入扩展中?
- assembly - 一个词在给定语句中使用了多少次。MIPS MARS 组件
- rest - REST API - 更多参数以方便使用
- r - 我如何摆脱 ¦ 登录我的数据
- c++ - int&referenceToA = a; 怎么样?可能的?
- python - 如何检查是否已经选择了某些内容?
- http - 托管在不同 Web 服务器上的 HTTP 请求对象的 TCP 连接
- swift - 奇怪的编译器错误:“expectation”产生“XCTestExpectation”,而不是预期的上下文结果类型“XCTestExpectation”