我正在尝试更新数据库中的数据。我在前端使用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令牌生成及其互换。
答案 0 :(得分:1)
1)请检查spring启动日志:您可以初始化url 用于项目
2)尝试为应用程序放置上下文路径,
这些链接可能会有所帮助: 在春季MVC中:How to Set Context root in Spring Mvc Project 在春季靴中:Add context path to Spring Boot application
示例网址:
http://localhost:8088/ {contextPath} / documents / updateDocument
3)更好地使用swagger ui等API文档,您可以尝试点击 轻松获取网址,并在控制器类中获取可用的网址。
答案 1 :(得分:0)
我认为您在代码中缺少@Autowired注释。 尝试在构造方法之前添加此批注,然后重试。 @Autowired public DocumentResources(DocumentsMapper mapper){this.mapper = mapper;}
答案 2 :(得分:0)
您需要将projectName添加到addres 例如:http://localhost:8088/projectName/documents/updateDocument