java - 如何在不为每个页面添加 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。
谢谢!
解决方案
例如,如果您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/**
.
推荐阅读
- python - Django 保存注册扩展 AbstractBaseUser
- r - 我无法在 R Leafjet 中的地图上放置标记
- c# - 通过 AJAX 请求返回部分视图的 ASP.NET Core 策略
- flutter - 颤振的邮件依赖项不起作用
- firebase - Firestore如何查询包含数组中任何值的字段
- python - 在多个条件下合并 Pandas 数据框
- android - 安卓广播短信
- laravel - Laravel Storage 不存储创建的 PDF 文件
- python - 当 discord bot 关闭时,会收到来自 asyncpg 错误的垃圾邮件
- java - 如何只填写 ArrayList 的偶数索引?