0

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.

Rinat
  • 362
  • 3
  • 14
  • 2
    have you tried hitting your rest api via postman? What's the output then? – tryingToLearn Oct 17 '18 at 06:56
  • @Rinat can you check the logs, whether it shown "no mapping found for this url" , also please check after setting context path and try hitting with the new url, this link myt be helpful : https://stackoverflow.com/questions/40670654/how-to-set-context-root-in-spring-mvc-project – Akhil S Kamath Oct 17 '18 at 07:04
  • @tryingtolearn output is: {"timestamp":"2018-10-17T07:08:26.074+0000","status":404,"error":"Not Found","message":"No message available","path":"/documents/updateDocuments"} – Rinat Oct 17 '18 at 07:12
  • It means there is a context path set in your application which needs to be appended in each request. Are you using springboot? If yes , check for context path property in application.properties – tryingToLearn Oct 17 '18 at 07:14
  • @tryingtolearn only server.port and spring.datasource.url, spring.datasource.password, spring.datasource.username in my application.properties file. GET REST endpoints work, but POST not ((( – Rinat Oct 17 '18 at 07:23
  • @tryingtolearn yes, I'm using SpringBoot – Rinat Oct 17 '18 at 07:24
  • The GET rest api that works is in same controller? Try adding a test GET api to this controller and see if it works? – tryingToLearn Oct 17 '18 at 07:27
  • @tryingtolearn, yes both GET and POST in the same controller (in same file) – Rinat Oct 17 '18 at 07:39
  • Please read [Under what circumstances may I add “urgent” or other similar phrases to my question, in order to obtain faster answers?](//meta.stackoverflow.com/q/326569) - the summary is that this is not an ideal way to address volunteers, and is probably counterproductive to obtaining answers. Please refrain from adding this to your questions. – halfer Oct 17 '18 at 19:38
  • @halfer Ok, thank you! – Rinat Oct 17 '18 at 19:42

3 Answers3

1

1) Please check spring startup logs : you can get the url initialized for the project

2) try putting context path for the application,

these link myt be helpful : in spring MVC : How to Set Context root in Spring Mvc Project in spring boot : Add context path to Spring Boot application

sample url :

http://localhost:8088/{contextPath}/documents/updateDocument

3) better use API documentation like swagger ui, you can try hitting the url easly and get the available urls in your controller classes.

Akhil S Kamath
  • 1,012
  • 13
  • 23
0

I think you are missing @Autowired annotation in your code. Try adding this annotation before Constructor and try again. @Autowired public DocumentResources(DocumentsMapper mapper){this.mapper = mapper;}

Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142
Nagaraj S Kharvi
  • 73
  • 1
  • 2
  • 12
0

you need add projectName to addres eg : http://localhost:8088/projectName/documents/updateDocument

Steve Nash
  • 144
  • 6