I am working on a Spring Boot Application. I am getting a 404 error on hitting the URL-path which I have configured. Where am I going wrong?
HomeController.java
package com.example.homes;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController("/add")
public class HomeController {
@GetMapping("/hello")
public String add() {
return "Hello";
}
}
HomeApplication.java
package com.example.homes;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
public class HomeApplication {
public static void main(String[] args) {
SpringApplication.run(HomeApplication.class, args);
System.out.println("Inside main");
}
}
You are missing RequestMapping for /add
. You kept as @RestController
property. It should be @RequestMapping("/add")
. In your current code hello
is mapped to root.
try localhost:8080/hello
and it will work.
If you wantlocalhost:8080/add/hello
Then it should be like below:
@RestController
@RequestMapping("/add")
public class HomeController {
@GetMapping(value = "/hello")
public String add() {
return "Hello";
}
}
Instead of doing @RestController("/add")
, Do this,
@RestController
@RequestMapping("/add")
Then you should be able to call localhost:8080/<ApplicationContext>/add/hello
@RestController is a specialized version of @Controller
which adds @Controller
and @ResponseBody
annotation automatically. so we do not have to add @ResponseBody
to our mapping methods.
@RequestMapping maps HTTP requests to handler methods of MVC and REST controllers.
Here possible suspect is @RestController("/add")
which should be @RequestMapping("/add")
@RequestMapping at Class Level
@RestController
@RequestMapping("/add")
public class HomeController {
//localhost:8080/add/hello (No Context Path in application.properties)
@GetMapping("/hello")
public String add() {
return "Hello";
}
}
@RequestMapping at Method Level
@RestController
public class HomeController {
//localhost:8080/hello (No Context Path in application.properties)
@GetMapping("/hello")
public String add() {
return "Hello";
}
}
If you don't have any context path defined in application.properties
then callinglocalhost:8080/add/hello
will give the desired output
In case you have a context path as app then call localhost:8080/app/add/hello
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With