Search code examples
javaspring-bootbackendrequest-mapping

SpringBoot Request Mapping not working as expected


I am new to spring boot and trying to make a starter application ran into this issue, the code is simple:

@RestController
public class MovieController {
    @RequestMapping("/")
    public String allMovies(){
        return "All Movies";
    }
}

I would expect this code to display All Movies when i go to localhoast:8080/ but it just shows me the boilerplate no explicit mapping for error. This is a fresh project i changed nothing during the while process i just have some other classes but none of them interfere with this class. The project is here: https://github.com/hozaifaO/Movie-Review . Another note to add is that i have a similar boiler plate starter project with the same code and that one works the only difference is that this one has mongodb as a dependency. Any help is appreciated.

I was expecting a string msg but i was greeted by boilerplate error mapping page.

UPDATE: Changing the code to this did not work.

@RestController
@RequestMapping("/movies")
public class MovieController {
    @GetMapping()
    public String allMovies(){
        return "All Movies";
    }
}

However, i did try to do this in a different class so i made the mapping happen in the Application class and it works if i do it in that class but i dont want to. Here is the code from that class,

@SpringBootApplication
@RestController
@RequestMapping("/abc")
public class MovieReviewApplication {

    public static void main(String[] args) {
        SpringApplication.run(MovieReviewApplication.class, args);

    }
    @GetMapping
    public String root(){
        return "Movies";
    }
}

All the code can be seen on the Github page link above including the pom file. Video of me running the software and showing whats wrong https://www.veed.io/view/3b14100c-c541-4d0d-9ffd-477439c3747e?panel=share


Solution

  • @RequestMapping is both a a class level & method level annotation. At class level ,it is used to create base URI. Every URI specified in method level annotation is appended to base URI specified on the top of the class.The URI specified at method level is added to clearly define or identify that the specific method of the class has been made request to. In addition you can use ,path parameters, method=get/post/put etc attributes in method level annotation. The new way of implementing method level annotation is @GetMapping/@PostMapping.

    You need to specify baseURI @ class level & Can use @Getmapping or @RequestMapping(method = RequestMethod.GET) at method level.

    Missing class level annotation is causing the issue.

    @RestController
    @RequestMapping("/")
    public class MovieController {
       
        @GetMapping
        public String allMovies(){
            return "All Movies";
        }
    }