wangdu
wangdu

Reputation: 13

404 Request Resource not found

I am using Spring Framework with restful web services, and I am trying to create an API with restful service and use a get method. I have created a method and I'm trying to have it return a string, but instead I get a 404 error - requested resources not found. Please see my code below:

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

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

I am using: localhosr:8080/MyProject/wangdu

Upvotes: 1

Views: 381

Answers (2)

Daniel C.
Daniel C.

Reputation: 5758

Please make sure about this:

  1. The value that the find method is returning is a String with the value "list" and the find method declaration is waiting for a RestResponse object

For example if I have a RestResponse object like this:

public class RestResponse {

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

    public String getValue(){
        return this.value;
    }
}

Then try to return the value in this way:

public RestResponse find(@PathVariable String name, ModelMap model) {
    model.addAttribute("movie", name);
    return new RestResponse("list");
}
  1. Verify that the method has @RequestMapping annotation with the value that your expect from the url

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

  2. By default the proper way to call the rest resource is by the @RequestMapping value that you set at the @RestController level (@RequestMapping("/test")), in this case could be: http://localhost:8080/test/myValue

If you need to use a different context path then you can change it on the application.properties (for spring boot)

server.contextPath=/MyProject/wangdu

In that case you can call the api like this:

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

Here is the complete code for this alternative:

@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");
    }

Upvotes: 1

Anshul Sharma
Anshul Sharma

Reputation: 3512

This error occurs because you forgot to add
@RequestMapping(value = "/{name}", method = RequestMethod.GET)
before your find method:

@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";
    }
}

Upvotes: 3

Related Questions