【问题标题】:Why REST controller returns 404 status code?为什么 REST 控制器返回 404 状态码?
【发布时间】:2018-10-17 06:49:05
【问题描述】:

我正在尝试更新我的数据库中的数据。我在前端使用 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-token 生成及其交换。

【问题讨论】:

  • 你试过通过邮递员打你的rest api吗?那么输出是什么?
  • @Rinat 你能检查一下日志,是否显示“没有找到此 url 的映射”,还请在设置上下文路径后检查并尝试使用新的 url,这个链接很有帮助:@ 987654321@
  • @tryingtolearn 输出为:{"timestamp":"2018-10-17T07:08:26.074+0000","status":404,"error":"Not Found","message" :"没有可用的消息","path":"/documents/updateDocuments"}
  • 这意味着您的应用程序中设置了一个上下文路径,需要在每个请求中附加。你用的是springboot吗?如果是,请检查 application.properties 中的上下文路径属性
  • @tryingtolearn only server.port and spring.datasource.url, spring.datasource.password, spring.datasource.username in my application.properties 文件。 GET REST 端点有效,但 POST 无效 (((

标签: java spring rest


【解决方案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) 更好的使用API​​文档,比如swagger ui,你可以试试打 轻松获取 url 并在您的控制器类中获取可用的 url。

【讨论】:

    【解决方案2】:

    您需要将 projectName 添加到地址 例如:http://localhost:8088/projectName/documents/updateDocument

    【讨论】:

      【解决方案3】:

      我认为您的代码中缺少 @Autowired 注释。 尝试在构造函数之前添加此注释,然后重试。 @自动连线 公共 DocumentResources(DocumentsMapper 映射器){this.mapper = mapper;}

      【讨论】:

      • 如果 OP 遇到注入问题,上下文将失败。
      猜你喜欢
      • 2020-08-15
      • 2010-11-28
      • 2018-06-04
      • 1970-01-01
      • 1970-01-01
      • 2014-10-26
      • 2020-11-28
      • 2012-03-30
      • 2022-02-09
      相关资源
      最近更新 更多