【问题标题】:404 Request Resource not found404 请求资源未找到
【发布时间】:2017-08-19 06:06:06
【问题描述】:

我正在使用带有 RESTful Web 服务的 Spring Framework,并且我正在尝试创建一个具有 RESTful 服务的 API 并使用 get 方法。我创建了一个方法,我试图让它返回一个字符串,但我得到一个 404 错误 - 未找到请求的资源。请参阅下面的代码:

@RestController
@RequestMapping("/test")
public class AreaController {

    public RestResponse find(@PathVariable String name, ModelMap model) {
        model.addAttribute("movie", name);
        return "list";
    }
}

我正在使用:localhosr:8080/MyProject/wangdu

【问题讨论】:

  • 本地 URL 不应该是 /test 吗?

标签: spring rest http


【解决方案1】:

出现此错误是因为您忘记在 find 方法前添加
@RequestMapping(value = "/{name}", method = RequestMethod.GET)

@RestController
@RequestMapping("/test")
public class AreaController {

    @RequestMapping(value = "/{name}", method = RequestMethod.GET)
    public RestResponse find(@PathVariable String name, ModelMap model) {
        model.addAttribute("movie", name);
        return "list";
    }
}

【讨论】:

    【解决方案2】:

    请确认:

    1. find 方法返回的值是一个值为 "list" 的字符串,并且 find 方法声明正在等待 RestResponse 对象

    例如,如果我有一个像这样的RestResponse 对象:

    public class RestResponse {
    
        private String value;
        public RestResponse(String value){
            this.value=value;
        }
    
        public String getValue(){
            return this.value;
        }
    }
    

    然后尝试以这种方式返回值:

    public RestResponse find(@PathVariable String name, ModelMap model) {
        model.addAttribute("movie", name);
        return new RestResponse("list");
    }
    
    1. 验证该方法是否具有 @RequestMapping 注释以及您期望从 url 获得的值

      @RequestMapping(method = RequestMethod.GET, value = "/{name}")

    2. 默认情况下,调用 rest 资源的正确方法是通过您在 @RestController 级别 (@RequestMapping("/test")) 设置的 @RequestMapping 值,在这种情况下可能是:http://localhost:8080/test/myValue

    如果您需要使用不同的上下文路径,那么您可以在 application.properties 上更改它(用于 spring boot)

    server.contextPath=/MyProject/wangdu
    

    在这种情况下,您可以像这样调用 api:

    http://localhost:8080/MyProject/wangdu/test/myValue

    这是此替代方案的完整代码:

    @RestController
    @RequestMapping("/test")
    public class AreaController {
    
    
        @RequestMapping(method = RequestMethod.GET, value = "/{name}")
        public RestResponse find(@PathVariable String name, ModelMap model) {
            model.addAttribute("movie", name);
            return new RestResponse("list");
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-01-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-15
      • 2015-10-11
      相关资源
      最近更新 更多