首页 > 解决方案 > 如何在不为每个页面添加 addViewController 的情况下添加页面?

问题描述

我正在研究spring框架,并在互联网上学习了一些教程,然后我发现了这个:

    package control;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

    @Configuration
    public class MVCController implements WebMvcConfigurer {
        public void addViewControllers(ViewControllerRegistry registry) {
              registry.addViewController("/index").setViewName("index");
              registry.addViewController("/").setViewName("index");
              registry.addViewController("/hello").setViewName("hello");
              registry.addViewController("/login").setViewName("login");
        }

    }

所以我的疑问是:

我正在使用 spring 5 和 Java JRE 1.8。

谢谢!

标签: javaspringspring-mvcspring-boot

解决方案


例如,如果您ViewResolver在您的.config class

@Bean
public ViewResolver viewResolver() {
    InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();

    viewResolver.setPrefix("/WEB-INF/view/");
    viewResolver.setSuffix(".jsp");

    return viewResolver;
}

在此之后,您可以使用注释创建控制器类@Controller,您将在其中分配@RequestMapping将侦听分配的目标的注释。

例如,

@Controller
public class yourCustomController {

//this will be your home page
@RequestMapping(value ="/")
public String showHomePage(){
//the return statement will look in the path defined in the view resolver and add the .jsp suffix ( so it will display file "/web-inf/view/my-home-page.jsp" )
  return "my-home-page";
}
}

您还可以将控制器分配给某些路径,例如, @Controller(value="/blog")所有控制器@RequestMappings都将映射到root/blog/**.


推荐阅读