如何在不为每个页面放置addViewController的情况下添加页面?

时间:2018-12-29 03:09:01

标签: java spring spring-mvc spring-boot

我正在研究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。

谢谢!

1 个答案:

答案 0 :(得分:0)

例如,如果您在ViewResolver中设置了一个config class bean,则常见的情况如下:

@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/**