繁体   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