我有以下 Spring MVC 代码:
配置文件:
public class MainWebAppInitializer implements WebApplicationInitializer {
@Override
public void onStartup(final ServletContext sc) throws ServletException {
AnnotationConfigWebApplicationContext root =
new AnnotationConfigWebApplicationContext();
root.register(WebConfig.class);
root.setServletContext(sc);
root.scan("testspring");
sc.addListener(new ContextLoaderListener(root));
ServletRegistration.Dynamic appServlet =
sc.addServlet("dispatcher", new DispatcherServlet(new GenericWebApplicationContext()));
appServlet.setLoadOnStartup(1);
appServlet.addMapping("/");
}
}
@EnableWebMvc
@Configuration
@ComponentScan("testspring")
public class WebConfig extends WebMvcConfigurerAdapter {
/*
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("index");
}*/
@Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver bean = new InternalResourceViewResolver();
bean.setViewClass(JstlView.class);
bean.setPrefix("/WEB-INF/view/");
bean.setSuffix(".html");
return bean;
}
}
Controller :
@Controller
public class HomeController {
@RequestMapping(value = "/")
public String home() {
System.out.println("HHomeController: Passing through...");
return "home.html";
}
}
@RestController
public class TestRestController {
@RequestMapping(value = "/api")
public String home() {
System.out.println("Rest: Passing through...");
return "some json";
}
}
部署时出现以下错误:
但是,访问 /api
页面效果很好。
编辑:
将 home.html
替换为 home
后,错误仍然存在 - 在 IDE 中和浏览器中的 404 中:
也许它是相关的 - 我在其中一个配置类中弹出此消息:
最佳答案
删除 .html 只需返回引用中的 View ,如下所示:“home”
关于java - HTTP 状态 404 – 未找到 : for controller - no view resolvers found in Idea,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61580907/