下面是来自springboot-features-developing-web-applications中的一段话:
翻译:" 如果你想要保留springboot mvc的特点,但是想要添加一些额外的mvc配置(拦截器、格式化程序、视图控制器和其他特性),你可以自己创建一个带有@Configuration
注解的类并且实现WebMvcConfigurer
接口,但是不能带有@EnableWebMvc
注解。如果您希望提供的定制情况RequestMappingHandlerMapping
,RequestMappingHandlerAdapter
或者 ExceptionHandlerExceptionResolver
,你可以声明一个WebMvcRegistrationsAdapter
实例来提供这样的组件。
如果你想要完全的控制spring mvc,那么你可以在你创建的类中添加@Configuration
和 @EnableWebMvc
注解 "
当我们使用的thymeleaf(模版引擎)之后,html页面就只能放在指定的页面(templates)下面,这就导致一个问题——必须通过controller跳转到HTML页面。这就带来一个问题
,我们首页应该怎么解决呢? 下面我们将介绍两个方式解决上述的问题。
第一种方式:通过controller进行视图控制
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class DemoController {
@RequestMapping({"/","/index.html"})
public String index(){
return "index";
}
}
第二种方式:通过"添加视图控制器"来实现
在springboot-features-developing-web-applications中,我们可知,我们可以通过通过创建自己的类实现对spring mvc的扩展,如下:
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 MyConfig implements WebMvcConfigurer {
// 配置首页视图控制器
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("index");
registry.addViewController("/index.html").setViewName("index");
}
}
经过上述的两种方式后,我们就可以将url为http://localhost:8080/
和http://localhost:8080/index.html
转换成http://localhost:8080/index
。
理想如星辰,我们要像航海者一样,借星光的位置而航行…