【问题标题】:Springboot ajax xhr failed load 404 errorSpringboot ajax xhr 加载失败 404 错误
【发布时间】:2022-01-04 00:51:01
【问题描述】:

我正在向 Controller 发送一个表单值,以通过 Springboot 项目中的 ajax 调用从数据库中加载更多数据。 但收到 404 xhr failed 错误(我也在使用 Spring 安全性)。

我已附上控制器、脚本和错误日志

@GetMapping("/company_selection")
    public String showCompanies(Model model,  @AuthenticationPrincipal CustomUserDetails user) {
        model.addAttribute("pageTitle","Select Company");
        model.addAttribute("companies",companyService.listCompanies(user.getId()));
        model.addAttribute("CompanySelectCriteria", new CompanySelectCriteria());
        Map<Long, String> years = new TreeMap<>();
        model.addAttribute("years", years);
        return "company_select";
    }
    
    @PostMapping(value = "/company_selection", produces = MediaType.APPLICATION_JSON_VALUE , consumes =  MediaType.APPLICATION_JSON_VALUE)
    public @ResponseBody Map<Long, String> showYears(Model model, @RequestBody YearCriteria yearCriteria) {
        Map<Long, String> years = companyService.listYears(yearCriteria.getCompanyName());
        return years;
    }

JQuery Ajax

<script type="text/javascript">
   $(document).ready(function() {
    $("#companies").change(function() {
      var company = $(this).find(":selected").val();
      var json = {
       "companyName" : company
      };
 
      $.ajax({
       type : "POST",
       contentType : "application/json",
       url : "/company_selection",
       data : JSON.stringify(json),
       dataType : 'json',
       cache : false,
       timeout : 600000,
       success : function(data) {    
        var html = '';
        html += '<option value="0"></option>';
        for (let elem of data.entries()) {
            html += '<option value="' + '${elem[0]}' + '">'
                   + '${elem[1]}'
                   + '</option>';
        }
        html += '</option>';
        $('#year_id').html(html);
       },
       error : function(e) {
        alert(e);
       }
      });
    });
   });
  </script>

【问题讨论】:

    标签: java ajax spring-boot http-status-code-404


    【解决方案1】:

    通常 Web 应用程序对所有控制器使用默认上下文路径。它由属性server.servlet.context-path=path 指定。检查它的默认值或指定您自己的值,并使用这样的路径:/path/company_selection

    【讨论】:

    • 我的应用路径默认,localhost:8080显示首页正常,其他页面正常显示
    • 你能在你的控制器类上显示注释吗?
    • 只是@Controller 上面的类名
    • 而且浏览器和你的 Spring Boot 应用之间没有任何代理,对吧?
    • 是的,没有代理
    猜你喜欢
    • 2017-03-09
    • 2017-03-16
    • 2021-01-25
    • 2018-08-02
    • 2016-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-20
    相关资源
    最近更新 更多