Spring Boot API with Multiple Controllers?
Apparently Controllers in different packages can't be seen with @springbootApplication notation in the main class. The solution explained here, https://kamwo.me/java-spring-boot-mvc-ontroller-not-called/.
I'm trying Spring Boot and got same problem, and just fixed it, I post my solution here because I think it maybe helpful for someone.
First, put application class ( which contain main method) at the root of controllers's package:
com.example.demo | +-> controller | | | +--> IndexController.java | +--> LoginController.java | +-> Application.java
Application.java
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Spring will scan all the components of sub-packages of demo package
IndexController.java (return index.html view)
package com.example.demo.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
@RequestMapping(value = {""})
public class IndexController {
@GetMapping(value = {""})
public ModelAndView index() {
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("index");
return modelAndView;
}
}
LoginController.java (return login.html view)
package com.example.demo.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
@RequestMapping(value = {"/login"})
public class LoginController {
@GetMapping(value = {""})
public ModelAndView login() {
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("login");
return modelAndView;
}
}
And now I can enter Index view : http://localhost:8080/demo/ and Login view : http://localhost:8080/demo/login