SpringBoot设置上下文路径后,请求出现404的原因

SpringBoot设置上下文路径后,请求出现404的原因,第1张

SpringBoot设置上下文路径后,请求出现404的原因

我本想的是设置上下文路径来做为父请求路径,这样就可以直接写方法上的请求路径了,结果出现了404.经过调试最后得出结果,设置了上下文路径与没有设置的效果一样。

yml配置文件如下:

server:
  port: 8888 #设置端口号
  servlet:
    context-path: /test #设置上下文路径

代码如下

package com.example.testnotblank.testcontroller;

import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;


@RestController
@RequestMapping("/test")
@Validated
public class TestController {
    @RequestMapping("/testNot")
    public  String  test(@Validated @NotNull(message = "msg不能为空") String msg, @NotBlank String str, @Size(min = 6) String size){
        System.out.println(msg);
        System.out.println(str);
        System.out.println(size);
        System.out.println("我的注解终于可以使用了");
        return "success";
    }

    @RequestMapping("/test")
    public  String testTwo(){
     return  "success";
    }

}

 我原本写的请求路径如下:

http://localhost:8888/test/test

结果出现了404,我不理解阿,为什么没有进入到方法中,我又改成/test/testNot,还是不可以,我想是不是上下文路径没有设置成功,我就去看Boot的启动信息,结果大失所望,已经设置成功了阿。我也想那是不是因为父请求路径和方法的请求路径重合的问题(完全没有依据),我就又写了一个Controller(如下图),然后访问的请求路径是http://localhost:8888/test还是不可以,最后我想难道上下文路径没有被算到请求路径,然后修改请求路径为http://localhost:8888/test/test,终于进入了TestContextController 。

package com.example.testnotblank.testcontroller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


@RestController
public class TestContextController {

    @RequestMapping("test")
    public  String test() {
        return "success";
    }
}

最后得出结论:上下文请求路径没有被当成请求路径的一部分,也就是说如果想访问TestController需要写成下面的请求路径

http://localhost:8888/test/test/test

虽然解决了这个问题,但是不是很理解那设置上下文的请求路径意义在那,如果有大佬看到,请赐教,最后祝大家身体健康,万事如意。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5721813.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-18
下一篇 2022-12-18

发表评论

登录后才能评论

评论列表(0条)

保存