I'am trying to create a simple controller with Spring Boot Congifuration is:
@Configuration
@EnableWebMvc
@ComponentScan (basePackages = { "ru.spb.chat.controller" })
public class WebConfig implements WebMvcConfigurer {
@Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver bean = new InternalResourceViewResolver();
bean.setPrefix("/WEB-INF/view/");
bean.setSuffix(".html");
return bean;
}
}
and for servlet:
public class MainWebAppInitializer implements WebApplicationInitializer {
@Override
public void onStartup(final ServletContext sc) throws ServletException {
AnnotationConfigWebApplicationContext root =
new AnnotationConfigWebApplicationContext();
root.scan("ru.spb");
sc.addListener(new ContextLoaderListener(root));
ServletRegistration.Dynamic appServlet =
sc.addServlet("mvc", new DispatcherServlet(new GenericWebApplicationContext()));
appServlet.setLoadOnStartup(1);
appServlet.addMapping("/");
}
}
My controller.
@Controller
public class RootController {
@GetMapping ("/")
public String root() {
return "login";
}
}
But when I try to map on "/" it returns 404-ERROR This is my project-structure:
Remove your WebConfig
and remove your ServletInitializer
and MainWebAppInitializer
. (You can probably also remove the WebSocketConfig
and use the auto-configuration from Spring Boot.).
Let your ChatApplication
extend SpringBootServletInitializer
and implement the configure
method.
@SpringBootApplication
public class ChatApplication extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(ChatApplication.class, args);
}
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return builder.sources(ChatApplication.class);
}
}
Then in your application.properties
add
spring.mvc.view.prefix=/WEB-INF/view/
spring.mvc.view.suffix=.html
Now you are using the proper Spring Boot auto-configuration AND proper way of creating a WAR which is executable.
That being said, you generally don't want a WAR (only if you use JSP, which is discouraged with embedded containers).
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.