I am trying to update data in my database. I am using jQuery/AJAX on frontend and REST/MyBatis/MySQL on backend. Unfortunately REST controller returns 404 status code. Please look at my REST controller code:
@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();
}
}
Here is my DocumentsMapper class code:
@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);
}
And here is my AJAX method:
$( "#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);
});
});
Update
I've just tried to switch off Spring Security and POST method became accessible. Here is the authorization features:
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()
;
}
Update
I try to switch on SpringSecurity but disable CSRF .csrf().disable()
. After that POST methods work. I think that disabling the CSRF is not a good idea. This may lead to XSS attacks. So I should configure CSRF-token generation and its interchange.