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 want localhost:8080/add/hello
Then it should be like below:
@RestController
@RequestMapping("/add")
public class HomeController {
@GetMapping(value = "/hello")
public String add() {
return "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 calling
localhost:8080/add/hello
will give the desired output
In case you have a context path as app then call localhost:8080/app/add/hello
Instead of doing @RestController("/add")
, Do this,
@RestController
@RequestMapping("/add")
Then you should be able to call localhost:8080/<ApplicationContext>/add/hello
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.