简体   繁体   中英

Spring-MVC: Controller working in one project but not the other(404 not found)

I have the following controller:

 import org.springframework.web.bind.annotation.GetMapping;
 import org.springframework.web.bind.annotation.RequestMapping;
 import org.springframework.web.bind.annotation.RestController;
 @RestController
 @RequestMapping(value="/")
 public class ToDoController 
 {  
   @GetMapping
   public String print()
   {
     return "Hello";
   }
 }

I as well run the spring app as follows:

 import java.util.Collections;
 import org.springframework.boot.SpringApplication;
 import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Startup 
{
    public static void main(String[] args) 
    {
        SpringApplication app = new SpringApplication(Startup.class);
        app.setDefaultProperties(Collections
                .singletonMap("server.port", "9005"));
        app.run(args);
    }

}

Now when i run localhost:9005/ I do see the following pop up

2021-05-19 12:05:00.961 INFO 40900 --- [nio-9005-exec-1] oac.c.C.[Tomcat].[localhost].[/]: Initializing Spring DispatcherServlet 'dispatcherServlet' 2021-05-19 12:05:00.961 INFO 40900 --- [nio-9005-exec-1] osweb.servlet.DispatcherServlet: Initializing Servlet 'dispatcherServlet' 2021-05-19 12:05:00.962 INFO 40900 --- [nio-9005-exec-1] osweb.servlet.DispatcherServlet: Completed initialization in 1 ms

Which I think means some connection is working but I am getting a 404 error on the web page.

Now what is odd is that when I copy paste both these classes to another project(in a package I have worked previously and know works), the code runs fine. However if in the same project I created a new package and placed new controllers in that package with a new Startup class, the controllers also do not work(404 error).

I built this project with eclipse and included all dependencies in class path, I never had to make a web.xml file and most of the solutions I found require you to change that file.

Any help would be appreciated as I haven't done anything different from the project/package that does work and the one's that do not.

What packages do Startup and ToDoController reside in?

If the controller resides in a package that is not a 'descendant' of the Startup package, it will not get picked up by component scan by default. You need to use @SpringBootApplication.scanBasePackages to point Spring at the additional packages to scan.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM