有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java InternalResourceViewResolver找不到页面

我有下一个项目结构:

enter image description here

WebMVC配置类:

@Configuration
@EnableWebMvc
@ComponentScan("com.test.controller")
public class WebMvcConfiguration {
    @Bean
    public InternalResourceViewResolver resolver() {
        return new InternalResourceViewResolver("/WEB-INF/view/", ".html");
    }
}

WebAppInitializer类:

public class WebAppInitializer implements WebApplicationInitializer {
    @Override
    public void onStartup(ServletContext servletContext) {
        AnnotationConfigWebApplicationContext webApplicationContext = new AnnotationConfigWebApplicationContext();
        webApplicationContext.scan("com.test.configuration");
        webApplicationContext.setServletContext(servletContext);

        ServletRegistration.Dynamic servletDispatcher =
            servletContext.addServlet("dispatcher", new DispatcherServlet(webApplicationContext));
        servletDispatcher.setLoadOnStartup(1);
        servletDispatcher.addMapping("/");
    }
}

CustomRestController类:

@RestController
public class CustomRestController {
    @GetMapping(value = "/rest", produces = MediaType.TEXT_PLAIN_VALUE)
    public String main() {
        return "main";
    }
}

CustomPageController类:

@Controller
public class CustomPageController {
    @GetMapping("/page")
    public String main() {
        return "main";
    }
}

Rest控制器正常工作。但PageController失败,出现以下异常:

org.springframework.web.servlet.DispatcherServlet.noHandlerFound No mapping for GET /WEB-INF/view/main.html

共 (1) 个答案

  1. # 1 楼答案

    我忘记在WebMVC配置中启用DefaultServletHandlerConfigurer:

    @Configuration
    @EnableWebMvc
    @ComponentScan("com.test.controller")
    public class WebMvcConfiguration implements WebMvcConfigurer {
        @Override
        public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
            configurer.enable();
        }
    
        @Bean
        public InternalResourceViewResolver resolver() {
            return new InternalResourceViewResolver("/WEB-INF/view/", ".html");
        }
    }