我正在研究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。
谢谢!
答案 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/**
。