繁体   English   中英

如果路由不存在,如何配置 spring 引导以引发 404 错误?

[英]How to configure spring boot to throw 404 error if route does not exist?

所以我在 controller 中有一堆嵌套路由。 如果特定的嵌套路由不存在,我想确保应用程序抛出错误。 现在,如果嵌套级别超过 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 错误: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 错误吗?

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

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

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

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

请同时检查spring 文档以获取请求映射注释

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM