[英]Why REST controller returns 404 status code?
我正在嘗試更新數據庫中的數據。 我在前端使用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 Project中設置上下文根 : 在Spring Boot應用程序中添加上下文路徑
樣本網址:
http:// localhost:8088 / {contextPath} / documents / updateDocument
3)更好地使用諸如swagger ui之類的API文檔,您可以嘗試輕松訪問URL並在控制器類中獲取可用的URL。
我認為您在代碼中缺少@Autowired注釋。 嘗試在構造方法之前添加此批注,然后重試。 @Autowired公共DocumentResources(DocumentsMapper映射器){this.mapper =映射器;}
您需要添加projectName以添加地址,例如: http:// localhost:8088 / projectName / documents / updateDocument
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.