簡體   English   中英

在非根路由上獲得響應 404

[英]Getting response 404 on non-root routes

1.當我嘗試向“/families”路由發送 GET 請求時,我的應用程序以 404 響應我。

控制器:

package com.example.controller;

import com.example.domain.*;
import com.example.repository.*;
import com.example.view.*;
import com.fasterxml.jackson.core.*;
import com.fasterxml.jackson.databind.*;
import org.springframework.beans.factory.annotation.*;
import org.springframework.stereotype.*;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@RequestMapping(consumes = "application/json", produces = "application/json")
public class FamilyController {
    private FamilyRepository familyRepository;

    public FamilyController(FamilyRepository familyRepo) {
        this.familyRepository = familyRepo;
    }

    @GetMapping("/")
    public String getFamily(){
        List<Family> families = familyRepository.findAll();

        ObjectMapper mapper = new ObjectMapper();
        mapper.disable(MapperFeature.DEFAULT_VIEW_INCLUSION);

        String result = "";
        try {
            result = mapper
                    .writerWithView(FamiliesView.class)
                    .writeValueAsString(families);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        return result;
    }
}

主要類:

package com.example;

import com.example.controller.*;
import org.springframework.boot.*;
import org.springframework.boot.autoconfigure.*;
import org.springframework.context.annotation.*;

@SpringBootApplication
public class ConstantaServerApplication {
    public static void main(String[] args) {
        SpringApplication.run(ConstantaServerApplication.class, args);
    }
}

2.但是當我嘗試將控制器注釋和 GET 請求中的路由更改為“/”時,我得到

"message": "Content type '' not supported"

映射器正常工作。

您的映射不正確。

使用控制器上的@RequestMapping注釋為整個控制器設置/families前綴:

@RestController
@RequestMapping(value = "/families", consumes = "application/json", produces = "application/json")
public class FamilyController {
    @GetMapping("/")
    public String getFamily(){...}
}

或者在你的getFamily方法上調整@GetMapping注釋

@RestController
@RequestMapping(consumes = "application/json", produces = "application/json")
public class FamilyController {
    @GetMapping("/families")
    public String getFamily(){...}
}

或注冊整個應用程序上下文路徑前綴/families通過配置屬性設置server.servlet.context-path ,以價值/families

在上面的代碼中,您可以從控制器級別刪除 @RequestMapping。

@RequestMapping(consumes = "application/json", produces = "application/json")

控制器應該是這樣的。

@RestController
public class FamilyController {

要了解有關行為的更多信息,您可以遵循一些教程,例如baeldung

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM