【问题标题】:How to configure spring boot to throw 404 error if route does not exist?如果路由不存在,如何配置spring boot抛出404错误?
【发布时间】:2020-02-05 12:14:58
【问题描述】:

所以我在控制器中有一堆嵌套路由。如果特定的嵌套路由不存在,我想确保应用程序抛出错误。现在,如果嵌套级别大于 2,则应用程序返回 null 而不是抛出错误说找不到路由。

示例:

@RestController 
@RequestMapping(value="v1/")
public class EmployeeController {

    @Autowired
    EmployeeRepository employeeRepository;


    // Get Token Info
    @RequestMapping(value = "read/tokenInfo", method =  RequestMethod.GET)
    public Token getTokenInfo(@AuthenticationPrincipal Token token) {
        return token;
    }


    // List of all employees.
    @GetMapping(path = "read/list")
    public List<Employee> getAllEmployees() {
        return employeeRepository.findAll();
    }

在上面的代码中,假设路由 v1/read/tokenInfo 有 3 个段 - v1、read 和 tokenInfo。如果我输入错误的路线并尝试类似 - v1/read/tokeninfosss 而不是显示错误,它会返回 200OK 并带有 null 消息。

回复:

但是,如果路线只有 2 个级别 - 如下 -

@RestController 
@RequestMapping(value="v1/")
public class EmployeeController {

    @Autowired
    EmployeeRepository employeeRepository;

    // Get Token Info
    @RequestMapping(value = "tokenInfo", method =  RequestMethod.GET)
    public Token getTokenInfo(@AuthenticationPrincipal Token token) {
        return token;
    }

现在如果我打电话 - v1/tokenInfosss,它会抛出一个错误 - 404 错误:

我还配置了如下安全性 -

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.sessionManagement()
        .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
        .and()
        .authorizeRequests()    
        .antMatchers("/local/**").permitAll()
        .antMatchers("/v1/read/**").hasAuthority("Display")
        .antMatchers("/v1/modify/**").hasAuthority("Update")
        .anyRequest().authenticated()
        .and()
        .oauth2ResourceServer()
        .jwt()
        .jwtAuthenticationConverter(getJwtAuthenticationConverter());
}

知道如何配置这个 404 错误吗?

【问题讨论】:

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


    【解决方案1】:

    尝试使用 / 结束你的路径并从 v1 中删除 /
    @RequestMapping(value="v1")

    @RequestMapping(value="/read/tokenInfo/", method = RequestMethod.GET)

    【讨论】:

    • 路径变量在其中的路径不起作用 - /v1/{id}
    • 我用简单的弹簧启动测试你的代码,一切都很好。可能另一个控制器与此路径匹配
    • 是的,你是对的。其他控制器正在匹配,因为我有一个带有签名的控制器 -> v1/{id},其中 id 是字符串类型。每当我调用其他端点(如 v1/list 或 v1/count )时,都会触发这种情况。它与尾随/前导斜杠无关。还是谢谢
    【解决方案2】:

    Spring 会自动执行此操作。如果您没有正确的请求映射注释,spring 将返回 404。问题在于您的请求映射。当你像这样给@RequestMapping(value = "read/tokenInfo", method = RequestMethod.GET)时,它会因为你的路径而接受任何请求,例如read/tokenInfossesf

    默认情况下,Spring MVC 执行 .* 后缀模式匹配,因此映射到 /person 的控制器也隐式映射到 /person.*。

    请检查spring documentation for request mapping annotation

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-17
      • 1970-01-01
      • 1970-01-01
      • 2023-04-07
      • 1970-01-01
      • 2018-10-04
      • 1970-01-01
      • 2012-09-17
      相关资源
      最近更新 更多