I'm trying to run a simple Spring application but it's impossible.
I have this controller:
@Controller("home")
public class Home {
@RequestMapping("/showHome")
public String showHome(){
return "index";
}
}
This is ViewResolver
:
@Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/view/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
When I run this program like that I'm getting 404 not found
and URL is: http://localhost:8080/E-CommerceFinal-1.0-SNAPSHOT/
But, when I change my controller class and method like this:
@Controller
public class Home {
@RequestMapping("/")
public String showHome(){
return "index";
}
}
My index page works.
CodePudding user response:
In your first version, @Controller("home")
all it does is set home
as the Home
bean name, nothing else. The important thing is @RequestMapping("/showHome")
. With this, you are saying that your showHome()
method will be available at http://localhost:8080/E-CommerceFinal-1.0-SNAPSHOT/showHome
.
In your second version, you are using @RequestMapping("/")
which sets no additional path and that is why http://localhost:8080/E-CommerceFinal-1.0-SNAPSHOT/
works.
CodePudding user response:
If you are trying to set the path for ALL of the endpoints to begin with "home" you would need
@Controller
@RequestMapping("/home")
public class Home {
@RequestMapping("/showHome")
public String showHome(){
return "index";
}
...
@RequestMapping("/someOtherEndpoint")
public String someOtherEndpoint(){
}
}
The above would be available at http://localhost:8080/E-CommerceFinal-1.0-SNAPSHOT/home/showHome and http://localhost:8080/E-CommerceFinal-1.0-SNAPSHOT/home/someOtherEndpoint
Otherwise, as someone mentioned, you're just setting the name of the bean itself, and then using the "/" path that you declared on the showHome endpoint.